code
stringlengths
2.5k
150k
kind
stringclasses
1 value
wordpress class WP_REST_Users_Controller {} class WP\_REST\_Users\_Controller {} ==================================== Core class used to manage users via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_users_controller/__construct) β€” Constructor. * [check\_reassign](wp_rest_users_controller/check_reassign) β€” Checks for a valid value for the reassign parameter when deleting users. * [check\_role\_update](wp_rest_users_controller/check_role_update) β€” Determines if the current user is allowed to make the desired roles change. * [check\_user\_password](wp_rest_users_controller/check_user_password) β€” Check a user password for the REST API. * [check\_username](wp_rest_users_controller/check_username) β€” Check a username for the REST API. * [create\_item](wp_rest_users_controller/create_item) β€” Creates a single user. * [create\_item\_permissions\_check](wp_rest_users_controller/create_item_permissions_check) β€” Checks if a given request has access create users. * [delete\_current\_item](wp_rest_users_controller/delete_current_item) β€” Deletes the current user. * [delete\_current\_item\_permissions\_check](wp_rest_users_controller/delete_current_item_permissions_check) β€” Checks if a given request has access to delete the current user. * [delete\_item](wp_rest_users_controller/delete_item) β€” Deletes a single user. * [delete\_item\_permissions\_check](wp_rest_users_controller/delete_item_permissions_check) β€” Checks if a given request has access delete a user. * [get\_collection\_params](wp_rest_users_controller/get_collection_params) β€” Retrieves the query params for collections. * [get\_current\_item](wp_rest_users_controller/get_current_item) β€” Retrieves the current user. * [get\_item](wp_rest_users_controller/get_item) β€” Retrieves a single user. * [get\_item\_permissions\_check](wp_rest_users_controller/get_item_permissions_check) β€” Checks if a given request has access to read a user. * [get\_item\_schema](wp_rest_users_controller/get_item_schema) β€” Retrieves the user's schema, conforming to JSON Schema. * [get\_items](wp_rest_users_controller/get_items) β€” Retrieves all users. * [get\_items\_permissions\_check](wp_rest_users_controller/get_items_permissions_check) β€” Permissions check for getting all users. * [get\_user](wp_rest_users_controller/get_user) β€” Get the user, if the ID is valid. * [prepare\_item\_for\_database](wp_rest_users_controller/prepare_item_for_database) β€” Prepares a single user for creation or update. * [prepare\_item\_for\_response](wp_rest_users_controller/prepare_item_for_response) β€” Prepares a single user output for response. * [prepare\_links](wp_rest_users_controller/prepare_links) β€” Prepares links for the user request. * [register\_routes](wp_rest_users_controller/register_routes) β€” Registers the routes for users. * [update\_current\_item](wp_rest_users_controller/update_current_item) β€” Updates the current user. * [update\_current\_item\_permissions\_check](wp_rest_users_controller/update_current_item_permissions_check) β€” Checks if a given request has access to update the current user. * [update\_item](wp_rest_users_controller/update_item) β€” Updates a single user. * [update\_item\_permissions\_check](wp_rest_users_controller/update_item_permissions_check) β€” Checks if a given request has access to update a user. File: `wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php/) ``` class WP_REST_Users_Controller extends WP_REST_Controller { /** * Instance of a user meta fields object. * * @since 4.7.0 * @var WP_REST_User_Meta_Fields */ protected $meta; /** * Constructor. * * @since 4.7.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'users'; $this->meta = new WP_REST_User_Meta_Fields(); } /** * Registers the routes for users. * * @since 4.7.0 * * @see register_rest_route() */ 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 ), ), '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 user.' ), '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 users do not support trashing.' ), ), 'reassign' => array( 'type' => 'integer', 'description' => __( 'Reassign the deleted user\'s posts and links to this user ID.' ), 'required' => true, 'sanitize_callback' => array( $this, 'check_reassign' ), ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/me', array( array( 'methods' => WP_REST_Server::READABLE, 'permission_callback' => '__return_true', 'callback' => array( $this, 'get_current_item' ), 'args' => array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ), ), array( 'methods' => WP_REST_Server::EDITABLE, 'callback' => array( $this, 'update_current_item' ), 'permission_callback' => array( $this, 'update_current_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_current_item' ), 'permission_callback' => array( $this, 'delete_current_item_permissions_check' ), 'args' => array( 'force' => array( 'type' => 'boolean', 'default' => false, 'description' => __( 'Required to be true, as users do not support trashing.' ), ), 'reassign' => array( 'type' => 'integer', 'description' => __( 'Reassign the deleted user\'s posts and links to this user ID.' ), 'required' => true, 'sanitize_callback' => array( $this, 'check_reassign' ), ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks for a valid value for the reassign parameter when deleting users. * * The value can be an integer, 'false', false, or ''. * * @since 4.7.0 * * @param int|bool $value The value passed to the reassign parameter. * @param WP_REST_Request $request Full details about the request. * @param string $param The parameter that is being sanitized. * @return int|bool|WP_Error */ public function check_reassign( $value, $request, $param ) { if ( is_numeric( $value ) ) { return $value; } if ( empty( $value ) || false === $value || 'false' === $value ) { return false; } return new WP_Error( 'rest_invalid_param', __( 'Invalid user parameter(s).' ), array( 'status' => 400 ) ); } /** * Permissions check for getting all users. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, otherwise WP_Error object. */ public function get_items_permissions_check( $request ) { // Check if roles is specified in GET request and if user can list users. if ( ! empty( $request['roles'] ) && ! current_user_can( 'list_users' ) ) { return new WP_Error( 'rest_user_cannot_view', __( 'Sorry, you are not allowed to filter users by role.' ), array( 'status' => rest_authorization_required_code() ) ); } // Check if capabilities is specified in GET request and if user can list users. if ( ! empty( $request['capabilities'] ) && ! current_user_can( 'list_users' ) ) { return new WP_Error( 'rest_user_cannot_view', __( 'Sorry, you are not allowed to filter users by capability.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( 'edit' === $request['context'] && ! current_user_can( 'list_users' ) ) { return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to list users.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( in_array( $request['orderby'], array( 'email', 'registered_date' ), true ) && ! current_user_can( 'list_users' ) ) { return new WP_Error( 'rest_forbidden_orderby', __( 'Sorry, you are not allowed to order users by this parameter.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( 'authors' === $request['who'] ) { $types = get_post_types( array( 'show_in_rest' => true ), 'objects' ); foreach ( $types as $type ) { if ( post_type_supports( $type->name, 'author' ) && current_user_can( $type->cap->edit_posts ) ) { return true; } } return new WP_Error( 'rest_forbidden_who', __( 'Sorry, you are not allowed to query users by this parameter.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Retrieves all users. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ 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', 'per_page' => 'number', 'search' => 'search', 'roles' => 'role__in', 'capabilities' => 'capability__in', 'slug' => 'nicename__in', ); $prepared_args = array(); /* * 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( $registered['offset'] ) && ! empty( $request['offset'] ) ) { $prepared_args['offset'] = $request['offset']; } else { $prepared_args['offset'] = ( $request['page'] - 1 ) * $prepared_args['number']; } if ( isset( $registered['orderby'] ) ) { $orderby_possibles = array( 'id' => 'ID', 'include' => 'include', 'name' => 'display_name', 'registered_date' => 'registered', 'slug' => 'user_nicename', 'include_slugs' => 'nicename__in', 'email' => 'user_email', 'url' => 'user_url', ); $prepared_args['orderby'] = $orderby_possibles[ $request['orderby'] ]; } if ( isset( $registered['who'] ) && ! empty( $request['who'] ) && 'authors' === $request['who'] ) { $prepared_args['who'] = 'authors'; } elseif ( ! current_user_can( 'list_users' ) ) { $prepared_args['has_published_posts'] = get_post_types( array( 'show_in_rest' => true ), 'names' ); } if ( ! empty( $request['has_published_posts'] ) ) { $prepared_args['has_published_posts'] = ( true === $request['has_published_posts'] ) ? get_post_types( array( 'show_in_rest' => true ), 'names' ) : (array) $request['has_published_posts']; } if ( ! empty( $prepared_args['search'] ) ) { $prepared_args['search'] = '*' . $prepared_args['search'] . '*'; } /** * Filters WP_User_Query arguments when querying users via the REST API. * * @link https://developer.wordpress.org/reference/classes/wp_user_query/ * * @since 4.7.0 * * @param array $prepared_args Array of arguments for WP_User_Query. * @param WP_REST_Request $request The REST API request. */ $prepared_args = apply_filters( 'rest_user_query', $prepared_args, $request ); $query = new WP_User_Query( $prepared_args ); $users = array(); foreach ( $query->results as $user ) { $data = $this->prepare_item_for_response( $user, $request ); $users[] = $this->prepare_response_for_collection( $data ); } $response = rest_ensure_response( $users ); // Store pagination values for headers then unset for count query. $per_page = (int) $prepared_args['number']; $page = ceil( ( ( (int) $prepared_args['offset'] ) / $per_page ) + 1 ); $prepared_args['fields'] = 'ID'; $total_users = $query->get_total(); if ( $total_users < 1 ) { // Out-of-bounds, run the query again without LIMIT for total count. unset( $prepared_args['number'], $prepared_args['offset'] ); $count_query = new WP_User_Query( $prepared_args ); $total_users = $count_query->get_total(); } $response->header( 'X-WP-Total', (int) $total_users ); $max_pages = ceil( $total_users / $per_page ); $response->header( 'X-WP-TotalPages', (int) $max_pages ); $base = add_query_arg( urlencode_deep( $request->get_query_params() ), rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) ); 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; } /** * Get the user, if the ID is valid. * * @since 4.7.2 * * @param int $id Supplied ID. * @return WP_User|WP_Error True if ID is valid, WP_Error otherwise. */ protected function get_user( $id ) { $error = new WP_Error( 'rest_user_invalid_id', __( 'Invalid user ID.' ), array( 'status' => 404 ) ); if ( (int) $id <= 0 ) { return $error; } $user = get_userdata( (int) $id ); if ( empty( $user ) || ! $user->exists() ) { return $error; } if ( is_multisite() && ! is_user_member_of_blog( $user->ID ) ) { return $error; } return $user; } /** * Checks if a given request has access to read a user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, otherwise WP_Error object. */ public function get_item_permissions_check( $request ) { $user = $this->get_user( $request['id'] ); if ( is_wp_error( $user ) ) { return $user; } $types = get_post_types( array( 'show_in_rest' => true ), 'names' ); if ( get_current_user_id() === $user->ID ) { return true; } if ( 'edit' === $request['context'] && ! current_user_can( 'list_users' ) ) { return new WP_Error( 'rest_user_cannot_view', __( 'Sorry, you are not allowed to list users.' ), array( 'status' => rest_authorization_required_code() ) ); } elseif ( ! count_user_posts( $user->ID, $types ) && ! current_user_can( 'edit_user', $user->ID ) && ! current_user_can( 'list_users' ) ) { return new WP_Error( 'rest_user_cannot_view', __( 'Sorry, you are not allowed to list users.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Retrieves a single user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { $user = $this->get_user( $request['id'] ); if ( is_wp_error( $user ) ) { return $user; } $user = $this->prepare_item_for_response( $user, $request ); $response = rest_ensure_response( $user ); return $response; } /** * Retrieves the current user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_current_item( $request ) { $current_user_id = get_current_user_id(); if ( empty( $current_user_id ) ) { return new WP_Error( 'rest_not_logged_in', __( 'You are not currently logged in.' ), array( 'status' => 401 ) ); } $user = wp_get_current_user(); $response = $this->prepare_item_for_response( $user, $request ); $response = rest_ensure_response( $response ); return $response; } /** * Checks if a given request has access create users. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise. */ public function create_item_permissions_check( $request ) { if ( ! current_user_can( 'create_users' ) ) { return new WP_Error( 'rest_cannot_create_user', __( 'Sorry, you are not allowed to create new users.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Creates a single user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function create_item( $request ) { if ( ! empty( $request['id'] ) ) { return new WP_Error( 'rest_user_exists', __( 'Cannot create existing user.' ), array( 'status' => 400 ) ); } $schema = $this->get_item_schema(); if ( ! empty( $request['roles'] ) && ! empty( $schema['properties']['roles'] ) ) { $check_permission = $this->check_role_update( $request['id'], $request['roles'] ); if ( is_wp_error( $check_permission ) ) { return $check_permission; } } $user = $this->prepare_item_for_database( $request ); if ( is_multisite() ) { $ret = wpmu_validate_user_signup( $user->user_login, $user->user_email ); if ( is_wp_error( $ret['errors'] ) && $ret['errors']->has_errors() ) { $error = new WP_Error( 'rest_invalid_param', __( 'Invalid user parameter(s).' ), array( 'status' => 400 ) ); foreach ( $ret['errors']->errors as $code => $messages ) { foreach ( $messages as $message ) { $error->add( $code, $message ); } $error_data = $error->get_error_data( $code ); if ( $error_data ) { $error->add_data( $error_data, $code ); } } return $error; } } if ( is_multisite() ) { $user_id = wpmu_create_user( $user->user_login, $user->user_pass, $user->user_email ); if ( ! $user_id ) { return new WP_Error( 'rest_user_create', __( 'Error creating new user.' ), array( 'status' => 500 ) ); } $user->ID = $user_id; $user_id = wp_update_user( wp_slash( (array) $user ) ); if ( is_wp_error( $user_id ) ) { return $user_id; } $result = add_user_to_blog( get_site()->id, $user_id, '' ); if ( is_wp_error( $result ) ) { return $result; } } else { $user_id = wp_insert_user( wp_slash( (array) $user ) ); if ( is_wp_error( $user_id ) ) { return $user_id; } } $user = get_user_by( 'id', $user_id ); /** * Fires immediately after a user is created or updated via the REST API. * * @since 4.7.0 * * @param WP_User $user Inserted or updated user object. * @param WP_REST_Request $request Request object. * @param bool $creating True when creating a user, false when updating. */ do_action( 'rest_insert_user', $user, $request, true ); if ( ! empty( $request['roles'] ) && ! empty( $schema['properties']['roles'] ) ) { array_map( array( $user, 'add_role' ), $request['roles'] ); } if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { $meta_update = $this->meta->update_value( $request['meta'], $user_id ); if ( is_wp_error( $meta_update ) ) { return $meta_update; } } $user = get_user_by( 'id', $user_id ); $fields_update = $this->update_additional_fields_for_object( $user, $request ); if ( is_wp_error( $fields_update ) ) { return $fields_update; } $request->set_param( 'context', 'edit' ); /** * Fires after a user is completely created or updated via the REST API. * * @since 5.0.0 * * @param WP_User $user Inserted or updated user object. * @param WP_REST_Request $request Request object. * @param bool $creating True when creating a user, false when updating. */ do_action( 'rest_after_insert_user', $user, $request, true ); $response = $this->prepare_item_for_response( $user, $request ); $response = rest_ensure_response( $response ); $response->set_status( 201 ); $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $user_id ) ) ); return $response; } /** * Checks if a given request has access to update a user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise. */ public function update_item_permissions_check( $request ) { $user = $this->get_user( $request['id'] ); if ( is_wp_error( $user ) ) { return $user; } if ( ! empty( $request['roles'] ) ) { if ( ! current_user_can( 'promote_user', $user->ID ) ) { return new WP_Error( 'rest_cannot_edit_roles', __( 'Sorry, you are not allowed to edit roles of this user.' ), array( 'status' => rest_authorization_required_code() ) ); } $request_params = array_keys( $request->get_params() ); sort( $request_params ); // If only 'id' and 'roles' are specified (we are only trying to // edit roles), then only the 'promote_user' cap is required. if ( array( 'id', 'roles' ) === $request_params ) { return true; } } if ( ! current_user_can( 'edit_user', $user->ID ) ) { return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this user.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Updates a single user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function update_item( $request ) { $user = $this->get_user( $request['id'] ); if ( is_wp_error( $user ) ) { return $user; } $id = $user->ID; if ( ! $user ) { return new WP_Error( 'rest_user_invalid_id', __( 'Invalid user ID.' ), array( 'status' => 404 ) ); } $owner_id = false; if ( is_string( $request['email'] ) ) { $owner_id = email_exists( $request['email'] ); } if ( $owner_id && $owner_id !== $id ) { return new WP_Error( 'rest_user_invalid_email', __( 'Invalid email address.' ), array( 'status' => 400 ) ); } if ( ! empty( $request['username'] ) && $request['username'] !== $user->user_login ) { return new WP_Error( 'rest_user_invalid_argument', __( 'Username is not editable.' ), array( 'status' => 400 ) ); } if ( ! empty( $request['slug'] ) && $request['slug'] !== $user->user_nicename && get_user_by( 'slug', $request['slug'] ) ) { return new WP_Error( 'rest_user_invalid_slug', __( 'Invalid slug.' ), array( 'status' => 400 ) ); } if ( ! empty( $request['roles'] ) ) { $check_permission = $this->check_role_update( $id, $request['roles'] ); if ( is_wp_error( $check_permission ) ) { return $check_permission; } } $user = $this->prepare_item_for_database( $request ); // Ensure we're operating on the same user we already checked. $user->ID = $id; $user_id = wp_update_user( wp_slash( (array) $user ) ); if ( is_wp_error( $user_id ) ) { return $user_id; } $user = get_user_by( 'id', $user_id ); /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php */ do_action( 'rest_insert_user', $user, $request, false ); if ( ! empty( $request['roles'] ) ) { array_map( array( $user, 'add_role' ), $request['roles'] ); } $schema = $this->get_item_schema(); if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { $meta_update = $this->meta->update_value( $request['meta'], $id ); if ( is_wp_error( $meta_update ) ) { return $meta_update; } } $user = get_user_by( 'id', $user_id ); $fields_update = $this->update_additional_fields_for_object( $user, $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-users-controller.php */ do_action( 'rest_after_insert_user', $user, $request, false ); $response = $this->prepare_item_for_response( $user, $request ); $response = rest_ensure_response( $response ); return $response; } /** * Checks if a given request has access to update the current user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise. */ public function update_current_item_permissions_check( $request ) { $request['id'] = get_current_user_id(); return $this->update_item_permissions_check( $request ); } /** * Updates the current user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function update_current_item( $request ) { $request['id'] = get_current_user_id(); return $this->update_item( $request ); } /** * Checks if a given request has access delete a user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise. */ public function delete_item_permissions_check( $request ) { $user = $this->get_user( $request['id'] ); if ( is_wp_error( $user ) ) { return $user; } if ( ! current_user_can( 'delete_user', $user->ID ) ) { return new WP_Error( 'rest_user_cannot_delete', __( 'Sorry, you are not allowed to delete this user.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Deletes a single user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function delete_item( $request ) { // We don't support delete requests in multisite. if ( is_multisite() ) { return new WP_Error( 'rest_cannot_delete', __( 'The user cannot be deleted.' ), array( 'status' => 501 ) ); } $user = $this->get_user( $request['id'] ); if ( is_wp_error( $user ) ) { return $user; } $id = $user->ID; $reassign = false === $request['reassign'] ? null : absint( $request['reassign'] ); $force = isset( $request['force'] ) ? (bool) $request['force'] : false; // We don't support trashing for users. if ( ! $force ) { return new WP_Error( 'rest_trash_not_supported', /* translators: %s: force=true */ sprintf( __( "Users do not support trashing. Set '%s' to delete." ), 'force=true' ), array( 'status' => 501 ) ); } if ( ! empty( $reassign ) ) { if ( $reassign === $id || ! get_userdata( $reassign ) ) { return new WP_Error( 'rest_user_invalid_reassign', __( 'Invalid user ID for reassignment.' ), array( 'status' => 400 ) ); } } $request->set_param( 'context', 'edit' ); $previous = $this->prepare_item_for_response( $user, $request ); // Include user admin functions to get access to wp_delete_user(). require_once ABSPATH . 'wp-admin/includes/user.php'; $result = wp_delete_user( $id, $reassign ); if ( ! $result ) { return new WP_Error( 'rest_cannot_delete', __( 'The user cannot be deleted.' ), array( 'status' => 500 ) ); } $response = new WP_REST_Response(); $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data(), ) ); /** * Fires immediately after a user is deleted via the REST API. * * @since 4.7.0 * * @param WP_User $user The user data. * @param WP_REST_Response $response The response returned from the API. * @param WP_REST_Request $request The request sent to the API. */ do_action( 'rest_delete_user', $user, $response, $request ); return $response; } /** * Checks if a given request has access to delete the current user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise. */ public function delete_current_item_permissions_check( $request ) { $request['id'] = get_current_user_id(); return $this->delete_item_permissions_check( $request ); } /** * Deletes the current user. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function delete_current_item( $request ) { $request['id'] = get_current_user_id(); return $this->delete_item( $request ); } /** * Prepares a single user output for response. * * @since 4.7.0 * @since 5.9.0 Renamed `$user` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_User $item User object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $user = $item; $data = array(); $fields = $this->get_fields_for_response( $request ); if ( in_array( 'id', $fields, true ) ) { $data['id'] = $user->ID; } if ( in_array( 'username', $fields, true ) ) { $data['username'] = $user->user_login; } if ( in_array( 'name', $fields, true ) ) { $data['name'] = $user->display_name; } if ( in_array( 'first_name', $fields, true ) ) { $data['first_name'] = $user->first_name; } if ( in_array( 'last_name', $fields, true ) ) { $data['last_name'] = $user->last_name; } if ( in_array( 'email', $fields, true ) ) { $data['email'] = $user->user_email; } if ( in_array( 'url', $fields, true ) ) { $data['url'] = $user->user_url; } if ( in_array( 'description', $fields, true ) ) { $data['description'] = $user->description; } if ( in_array( 'link', $fields, true ) ) { $data['link'] = get_author_posts_url( $user->ID, $user->user_nicename ); } if ( in_array( 'locale', $fields, true ) ) { $data['locale'] = get_user_locale( $user ); } if ( in_array( 'nickname', $fields, true ) ) { $data['nickname'] = $user->nickname; } if ( in_array( 'slug', $fields, true ) ) { $data['slug'] = $user->user_nicename; } if ( in_array( 'roles', $fields, true ) ) { // Defensively call array_values() to ensure an array is returned. $data['roles'] = array_values( $user->roles ); } if ( in_array( 'registered_date', $fields, true ) ) { $data['registered_date'] = gmdate( 'c', strtotime( $user->user_registered ) ); } if ( in_array( 'capabilities', $fields, true ) ) { $data['capabilities'] = (object) $user->allcaps; } if ( in_array( 'extra_capabilities', $fields, true ) ) { $data['extra_capabilities'] = (object) $user->caps; } if ( in_array( 'avatar_urls', $fields, true ) ) { $data['avatar_urls'] = rest_get_avatar_urls( $user ); } if ( in_array( 'meta', $fields, true ) ) { $data['meta'] = $this->meta->get_value( $user->ID, $request ); } $context = ! empty( $request['context'] ) ? $request['context'] : 'embed'; $data = $this->add_additional_fields_to_object( $data, $request ); $data = $this->filter_response_by_context( $data, $context ); // Wrap the data in a response object. $response = rest_ensure_response( $data ); if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { $response->add_links( $this->prepare_links( $user ) ); } /** * Filters user data returned from the REST API. * * @since 4.7.0 * * @param WP_REST_Response $response The response object. * @param WP_User $user User object used to create response. * @param WP_REST_Request $request Request object. */ return apply_filters( 'rest_prepare_user', $response, $user, $request ); } /** * Prepares links for the user request. * * @since 4.7.0 * * @param WP_User $user User object. * @return array Links for the given user. */ protected function prepare_links( $user ) { $links = array( 'self' => array( 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $user->ID ) ), ), 'collection' => array( 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ), ), ); return $links; } /** * Prepares a single user for creation or update. * * @since 4.7.0 * * @param WP_REST_Request $request Request object. * @return object User object. */ protected function prepare_item_for_database( $request ) { $prepared_user = new stdClass; $schema = $this->get_item_schema(); // Required arguments. if ( isset( $request['email'] ) && ! empty( $schema['properties']['email'] ) ) { $prepared_user->user_email = $request['email']; } if ( isset( $request['username'] ) && ! empty( $schema['properties']['username'] ) ) { $prepared_user->user_login = $request['username']; } if ( isset( $request['password'] ) && ! empty( $schema['properties']['password'] ) ) { $prepared_user->user_pass = $request['password']; } // Optional arguments. if ( isset( $request['id'] ) ) { $prepared_user->ID = absint( $request['id'] ); } if ( isset( $request['name'] ) && ! empty( $schema['properties']['name'] ) ) { $prepared_user->display_name = $request['name']; } if ( isset( $request['first_name'] ) && ! empty( $schema['properties']['first_name'] ) ) { $prepared_user->first_name = $request['first_name']; } if ( isset( $request['last_name'] ) && ! empty( $schema['properties']['last_name'] ) ) { $prepared_user->last_name = $request['last_name']; } if ( isset( $request['nickname'] ) && ! empty( $schema['properties']['nickname'] ) ) { $prepared_user->nickname = $request['nickname']; } if ( isset( $request['slug'] ) && ! empty( $schema['properties']['slug'] ) ) { $prepared_user->user_nicename = $request['slug']; } if ( isset( $request['description'] ) && ! empty( $schema['properties']['description'] ) ) { $prepared_user->description = $request['description']; } if ( isset( $request['url'] ) && ! empty( $schema['properties']['url'] ) ) { $prepared_user->user_url = $request['url']; } if ( isset( $request['locale'] ) && ! empty( $schema['properties']['locale'] ) ) { $prepared_user->locale = $request['locale']; } // Setting roles will be handled outside of this function. if ( isset( $request['roles'] ) ) { $prepared_user->role = false; } /** * Filters user data before insertion via the REST API. * * @since 4.7.0 * * @param object $prepared_user User object. * @param WP_REST_Request $request Request object. */ return apply_filters( 'rest_pre_insert_user', $prepared_user, $request ); } /** * Determines if the current user is allowed to make the desired roles change. * * @since 4.7.0 * * @global WP_Roles $wp_roles WordPress role management object. * * @param int $user_id User ID. * @param array $roles New user roles. * @return true|WP_Error True if the current user is allowed to make the role change, * otherwise a WP_Error object. */ protected function check_role_update( $user_id, $roles ) { global $wp_roles; foreach ( $roles as $role ) { if ( ! isset( $wp_roles->role_objects[ $role ] ) ) { return new WP_Error( 'rest_user_invalid_role', /* translators: %s: Role key. */ sprintf( __( 'The role %s does not exist.' ), $role ), array( 'status' => 400 ) ); } $potential_role = $wp_roles->role_objects[ $role ]; /* * Don't let anyone with 'edit_users' (admins) edit their own role to something without it. * Multisite super admins can freely edit their blog roles -- they possess all caps. */ if ( ! ( is_multisite() && current_user_can( 'manage_sites' ) ) && get_current_user_id() === $user_id && ! $potential_role->has_cap( 'edit_users' ) ) { return new WP_Error( 'rest_user_invalid_role', __( 'Sorry, you are not allowed to give users that role.' ), array( 'status' => rest_authorization_required_code() ) ); } // Include user admin functions to get access to get_editable_roles(). require_once ABSPATH . 'wp-admin/includes/user.php'; // The new role must be editable by the logged-in user. $editable_roles = get_editable_roles(); if ( empty( $editable_roles[ $role ] ) ) { return new WP_Error( 'rest_user_invalid_role', __( 'Sorry, you are not allowed to give users that role.' ), array( 'status' => 403 ) ); } } return true; } /** * Check a username for the REST API. * * Performs a couple of checks like edit_user() in wp-admin/includes/user.php. * * @since 4.7.0 * * @param string $value The username submitted in the request. * @param WP_REST_Request $request Full details about the request. * @param string $param The parameter name. * @return string|WP_Error The sanitized username, if valid, otherwise an error. */ public function check_username( $value, $request, $param ) { $username = (string) $value; if ( ! validate_username( $username ) ) { return new WP_Error( 'rest_user_invalid_username', __( 'This username is invalid because it uses illegal characters. Please enter a valid username.' ), array( 'status' => 400 ) ); } /** This filter is documented in wp-includes/user.php */ $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() ); if ( in_array( strtolower( $username ), array_map( 'strtolower', $illegal_logins ), true ) ) { return new WP_Error( 'rest_user_invalid_username', __( 'Sorry, that username is not allowed.' ), array( 'status' => 400 ) ); } return $username; } /** * Check a user password for the REST API. * * Performs a couple of checks like edit_user() in wp-admin/includes/user.php. * * @since 4.7.0 * * @param string $value The password submitted in the request. * @param WP_REST_Request $request Full details about the request. * @param string $param The parameter name. * @return string|WP_Error The sanitized password, if valid, otherwise an error. */ public function check_user_password( $value, $request, $param ) { $password = (string) $value; if ( empty( $password ) ) { return new WP_Error( 'rest_user_invalid_password', __( 'Passwords cannot be empty.' ), array( 'status' => 400 ) ); } if ( false !== strpos( $password, '\\' ) ) { return new WP_Error( 'rest_user_invalid_password', sprintf( /* translators: %s: The '\' character. */ __( 'Passwords cannot contain the "%s" character.' ), '\\' ), array( 'status' => 400 ) ); } return $password; } /** * Retrieves the user's schema, conforming to JSON Schema. * * @since 4.7.0 * * @return array Item schema data. */ 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' => 'user', 'type' => 'object', 'properties' => array( 'id' => array( 'description' => __( 'Unique identifier for the user.' ), 'type' => 'integer', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'username' => array( 'description' => __( 'Login name for the user.' ), 'type' => 'string', 'context' => array( 'edit' ), 'required' => true, 'arg_options' => array( 'sanitize_callback' => array( $this, 'check_username' ), ), ), 'name' => array( 'description' => __( 'Display name for the user.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'first_name' => array( 'description' => __( 'First name for the user.' ), 'type' => 'string', 'context' => array( 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'last_name' => array( 'description' => __( 'Last name for the user.' ), 'type' => 'string', 'context' => array( 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'email' => array( 'description' => __( 'The email address for the user.' ), 'type' => 'string', 'format' => 'email', 'context' => array( 'edit' ), 'required' => true, ), 'url' => array( 'description' => __( 'URL of the user.' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'embed', 'view', 'edit' ), ), 'description' => array( 'description' => __( 'Description of the user.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), ), 'link' => array( 'description' => __( 'Author URL of the user.' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'locale' => array( 'description' => __( 'Locale for the user.' ), 'type' => 'string', 'enum' => array_merge( array( '', 'en_US' ), get_available_languages() ), 'context' => array( 'edit' ), ), 'nickname' => array( 'description' => __( 'The nickname for the user.' ), 'type' => 'string', 'context' => array( 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'slug' => array( 'description' => __( 'An alphanumeric identifier for the user.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'arg_options' => array( 'sanitize_callback' => array( $this, 'sanitize_slug' ), ), ), 'registered_date' => array( 'description' => __( 'Registration date for the user.' ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'edit' ), 'readonly' => true, ), 'roles' => array( 'description' => __( 'Roles assigned to the user.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), 'context' => array( 'edit' ), ), 'password' => array( 'description' => __( 'Password for the user (never included).' ), 'type' => 'string', 'context' => array(), // Password is never displayed. 'required' => true, 'arg_options' => array( 'sanitize_callback' => array( $this, 'check_user_password' ), ), ), 'capabilities' => array( 'description' => __( 'All capabilities assigned to the user.' ), 'type' => 'object', 'context' => array( 'edit' ), 'readonly' => true, ), 'extra_capabilities' => array( 'description' => __( 'Any extra capabilities assigned to the user.' ), 'type' => 'object', 'context' => array( 'edit' ), 'readonly' => true, ), ), ); if ( get_option( 'show_avatars' ) ) { $avatar_properties = array(); $avatar_sizes = rest_get_avatar_sizes(); foreach ( $avatar_sizes as $size ) { $avatar_properties[ $size ] = array( /* translators: %d: Avatar image size in pixels. */ 'description' => sprintf( __( 'Avatar URL with image size of %d pixels.' ), $size ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'embed', 'view', 'edit' ), ); } $schema['properties']['avatar_urls'] = array( 'description' => __( 'Avatar URLs for the user.' ), 'type' => 'object', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, 'properties' => $avatar_properties, ); } $schema['properties']['meta'] = $this->meta->get_field_schema(); $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the query params for collections. * * @since 4.7.0 * * @return array Collection parameters. */ public function get_collection_params() { $query_params = parent::get_collection_params(); $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(), ); $query_params['offset'] = array( 'description' => __( 'Offset the result set by a specific number of items.' ), 'type' => 'integer', ); $query_params['order'] = array( 'default' => 'asc', 'description' => __( 'Order sort attribute ascending or descending.' ), 'enum' => array( 'asc', 'desc' ), 'type' => 'string', ); $query_params['orderby'] = array( 'default' => 'name', 'description' => __( 'Sort collection by user attribute.' ), 'enum' => array( 'id', 'include', 'name', 'registered_date', 'slug', 'include_slugs', 'email', 'url', ), 'type' => 'string', ); $query_params['slug'] = array( 'description' => __( 'Limit result set to users with one or more specific slugs.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), ); $query_params['roles'] = array( 'description' => __( 'Limit result set to users matching at least one specific role provided. Accepts csv list or single role.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), ); $query_params['capabilities'] = array( 'description' => __( 'Limit result set to users matching at least one specific capability provided. Accepts csv list or single capability.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), ); $query_params['who'] = array( 'description' => __( 'Limit result set to users who are considered authors.' ), 'type' => 'string', 'enum' => array( 'authors', ), ); $query_params['has_published_posts'] = array( 'description' => __( 'Limit result set to users who have published posts.' ), 'type' => array( 'boolean', 'array' ), 'items' => array( 'type' => 'string', 'enum' => get_post_types( array( 'show_in_rest' => true ), 'names' ), ), ); /** * Filters REST API collection parameters for the users controller. * * This filter registers the collection parameter, but does not map the * collection parameter to an internal WP_User_Query parameter. Use the * `rest_user_query` filter to set WP_User_Query arguments. * * @since 4.7.0 * * @param array $query_params JSON Schema-formatted collection parameters. */ return apply_filters( 'rest_user_collection_params', $query_params ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
programming_docs
wordpress class WP_Customize_Theme_Control {} class WP\_Customize\_Theme\_Control {} ====================================== Customize Theme Control class. * [WP\_Customize\_Control](wp_customize_control) * [content\_template](wp_customize_theme_control/content_template) β€” Render a JS template for theme display. * [render\_content](wp_customize_theme_control/render_content) β€” Don't render the control content from PHP, as it's rendered via JS on load. * [to\_json](wp_customize_theme_control/to_json) β€” Refresh the parameters passed to the JavaScript via JSON. File: `wp-includes/customize/class-wp-customize-theme-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-theme-control.php/) ``` class WP_Customize_Theme_Control extends WP_Customize_Control { /** * Customize control type. * * @since 4.2.0 * @var string */ public $type = 'theme'; /** * Theme object. * * @since 4.2.0 * @var WP_Theme */ public $theme; /** * Refresh the parameters passed to the JavaScript via JSON. * * @since 4.2.0 * * @see WP_Customize_Control::to_json() */ public function to_json() { parent::to_json(); $this->json['theme'] = $this->theme; } /** * Don't render the control content from PHP, as it's rendered via JS on load. * * @since 4.2.0 */ public function render_content() {} /** * Render a JS template for theme display. * * @since 4.2.0 */ public function content_template() { /* translators: %s: Theme name. */ $details_label = sprintf( __( 'Details for theme: %s' ), '{{ data.theme.name }}' ); /* translators: %s: Theme name. */ $customize_label = sprintf( __( 'Customize theme: %s' ), '{{ data.theme.name }}' ); /* translators: %s: Theme name. */ $preview_label = sprintf( __( 'Live preview theme: %s' ), '{{ data.theme.name }}' ); /* translators: %s: Theme name. */ $install_label = sprintf( __( 'Install and preview theme: %s' ), '{{ data.theme.name }}' ); ?> <# if ( data.theme.active ) { #> <div class="theme active" tabindex="0" aria-describedby="{{ data.section }}-{{ data.theme.id }}-action"> <# } else { #> <div class="theme" tabindex="0" aria-describedby="{{ data.section }}-{{ data.theme.id }}-action"> <# } #> <# if ( data.theme.screenshot && data.theme.screenshot[0] ) { #> <div class="theme-screenshot"> <img data-src="{{ data.theme.screenshot[0] }}?ver={{ data.theme.version }}" alt="" /> </div> <# } else { #> <div class="theme-screenshot blank"></div> <# } #> <span class="more-details theme-details" id="{{ data.section }}-{{ data.theme.id }}-action" aria-label="<?php echo esc_attr( $details_label ); ?>"><?php _e( 'Theme Details' ); ?></span> <div class="theme-author"> <?php /* translators: Theme author name. */ printf( _x( 'By %s', 'theme author' ), '{{ data.theme.author }}' ); ?> </div> <# if ( 'installed' === data.theme.type && data.theme.hasUpdate ) { #> <# if ( data.theme.updateResponse.compatibleWP && data.theme.updateResponse.compatiblePHP ) { #> <div class="update-message notice inline notice-warning notice-alt" data-slug="{{ data.theme.id }}"> <p> <?php if ( is_multisite() ) { _e( 'New version available.' ); } else { printf( /* translators: %s: "Update now" button. */ __( 'New version available. %s' ), '<button class="button-link update-theme" type="button">' . __( 'Update now' ) . '</button>' ); } ?> </p> </div> <# } else { #> <div class="update-message notice inline notice-error notice-alt" data-slug="{{ data.theme.id }}"> <p> <# if ( ! data.theme.updateResponse.compatibleWP && ! data.theme.updateResponse.compatiblePHP ) { #> <?php printf( /* translators: %s: Theme name. */ __( 'There is a new version of %s available, but it does not work with your versions of WordPress and PHP.' ), '{{{ data.theme.name }}}' ); if ( current_user_can( 'update_core' ) && current_user_can( 'update_php' ) ) { printf( /* translators: 1: URL to WordPress Updates screen, 2: URL to Update PHP page. */ ' ' . __( '<a href="%1$s">Please update WordPress</a>, and then <a href="%2$s">learn more about updating PHP</a>.' ), self_admin_url( 'update-core.php' ), esc_url( wp_get_update_php_url() ) ); wp_update_php_annotation( '</p><p><em>', '</em>' ); } elseif ( current_user_can( 'update_core' ) ) { printf( /* translators: %s: URL to WordPress Updates screen. */ ' ' . __( '<a href="%s">Please update WordPress</a>.' ), self_admin_url( 'update-core.php' ) ); } elseif ( current_user_can( 'update_php' ) ) { printf( /* translators: %s: URL to Update PHP page. */ ' ' . __( '<a href="%s">Learn more about updating PHP</a>.' ), esc_url( wp_get_update_php_url() ) ); wp_update_php_annotation( '</p><p><em>', '</em>' ); } ?> <# } else if ( ! data.theme.updateResponse.compatibleWP ) { #> <?php printf( /* translators: %s: Theme name. */ __( 'There is a new version of %s available, but it does not work with your version of WordPress.' ), '{{{ data.theme.name }}}' ); if ( current_user_can( 'update_core' ) ) { printf( /* translators: %s: URL to WordPress Updates screen. */ ' ' . __( '<a href="%s">Please update WordPress</a>.' ), self_admin_url( 'update-core.php' ) ); } ?> <# } else if ( ! data.theme.updateResponse.compatiblePHP ) { #> <?php printf( /* translators: %s: Theme name. */ __( 'There is a new version of %s available, but it does not work with your version of PHP.' ), '{{{ data.theme.name }}}' ); if ( current_user_can( 'update_php' ) ) { printf( /* translators: %s: URL to Update PHP page. */ ' ' . __( '<a href="%s">Learn more about updating PHP</a>.' ), esc_url( wp_get_update_php_url() ) ); wp_update_php_annotation( '</p><p><em>', '</em>' ); } ?> <# } #> </p> </div> <# } #> <# } #> <# if ( ! data.theme.compatibleWP || ! data.theme.compatiblePHP ) { #> <div class="notice notice-error notice-alt"><p> <# if ( ! data.theme.compatibleWP && ! data.theme.compatiblePHP ) { #> <?php _e( 'This theme does not work with your versions of WordPress and PHP.' ); if ( current_user_can( 'update_core' ) && current_user_can( 'update_php' ) ) { printf( /* translators: 1: URL to WordPress Updates screen, 2: URL to Update PHP page. */ ' ' . __( '<a href="%1$s">Please update WordPress</a>, and then <a href="%2$s">learn more about updating PHP</a>.' ), self_admin_url( 'update-core.php' ), esc_url( wp_get_update_php_url() ) ); wp_update_php_annotation( '</p><p><em>', '</em>' ); } elseif ( current_user_can( 'update_core' ) ) { printf( /* translators: %s: URL to WordPress Updates screen. */ ' ' . __( '<a href="%s">Please update WordPress</a>.' ), self_admin_url( 'update-core.php' ) ); } elseif ( current_user_can( 'update_php' ) ) { printf( /* translators: %s: URL to Update PHP page. */ ' ' . __( '<a href="%s">Learn more about updating PHP</a>.' ), esc_url( wp_get_update_php_url() ) ); wp_update_php_annotation( '</p><p><em>', '</em>' ); } ?> <# } else if ( ! data.theme.compatibleWP ) { #> <?php _e( 'This theme does not work with your version of WordPress.' ); if ( current_user_can( 'update_core' ) ) { printf( /* translators: %s: URL to WordPress Updates screen. */ ' ' . __( '<a href="%s">Please update WordPress</a>.' ), self_admin_url( 'update-core.php' ) ); } ?> <# } else if ( ! data.theme.compatiblePHP ) { #> <?php _e( 'This theme does not work with your version of PHP.' ); if ( current_user_can( 'update_php' ) ) { printf( /* translators: %s: URL to Update PHP page. */ ' ' . __( '<a href="%s">Learn more about updating PHP</a>.' ), esc_url( wp_get_update_php_url() ) ); wp_update_php_annotation( '</p><p><em>', '</em>' ); } ?> <# } #> </p></div> <# } #> <# if ( data.theme.active ) { #> <div class="theme-id-container"> <h3 class="theme-name" id="{{ data.section }}-{{ data.theme.id }}-name"> <span><?php _ex( 'Previewing:', 'theme' ); ?></span> {{ data.theme.name }} </h3> <div class="theme-actions"> <button type="button" class="button button-primary customize-theme" aria-label="<?php echo esc_attr( $customize_label ); ?>"><?php _e( 'Customize' ); ?></button> </div> </div> <div class="notice notice-success notice-alt"><p><?php _ex( 'Installed', 'theme' ); ?></p></div> <# } else if ( 'installed' === data.theme.type ) { #> <# if ( data.theme.blockTheme ) { #> <div class="theme-id-container"> <h3 class="theme-name" id="{{ data.section }}-{{ data.theme.id }}-name">{{ data.theme.name }}</h3> <div class="theme-actions"> <# if ( data.theme.actions.activate ) { #> <?php /* translators: %s: Theme name. */ $aria_label = sprintf( _x( 'Activate %s', 'theme' ), '{{ data.name }}' ); ?> <a href="{{{ data.theme.actions.activate }}}" class="button button-primary activate" aria-label="<?php echo esc_attr( $aria_label ); ?>"><?php _e( 'Activate' ); ?></a> <# } #> </div> </div> <div class="notice notice-error notice-alt"><p> <?php _e( 'This theme doesn\'t support Customizer.' ); ?> <# if ( data.theme.actions.activate ) { #> <?php echo ' '; printf( /* translators: %s: URL to the themes page (also it activates the theme). */ __( 'However, you can still <a href="%s">activate this theme</a>, and use the Site Editor to customize it.' ), '{{{ data.theme.actions.activate }}}' ); ?> <# } #> </p></div> <# } else { #> <div class="theme-id-container"> <h3 class="theme-name" id="{{ data.section }}-{{ data.theme.id }}-name">{{ data.theme.name }}</h3> <div class="theme-actions"> <# if ( data.theme.compatibleWP && data.theme.compatiblePHP ) { #> <button type="button" class="button button-primary preview-theme" aria-label="<?php echo esc_attr( $preview_label ); ?>" data-slug="{{ data.theme.id }}"><?php _e( 'Live Preview' ); ?></button> <# } else { #> <button type="button" class="button button-primary disabled" aria-label="<?php echo esc_attr( $preview_label ); ?>"><?php _e( 'Live Preview' ); ?></button> <# } #> </div> </div> <div class="notice notice-success notice-alt"><p><?php _ex( 'Installed', 'theme' ); ?></p></div> <# } #> <# } else { #> <div class="theme-id-container"> <h3 class="theme-name" id="{{ data.section }}-{{ data.theme.id }}-name">{{ data.theme.name }}</h3> <div class="theme-actions"> <# if ( data.theme.compatibleWP && data.theme.compatiblePHP ) { #> <button type="button" class="button button-primary theme-install preview" aria-label="<?php echo esc_attr( $install_label ); ?>" data-slug="{{ data.theme.id }}" data-name="{{ data.theme.name }}"><?php _e( 'Install &amp; Preview' ); ?></button> <# } else { #> <button type="button" class="button button-primary disabled" aria-label="<?php echo esc_attr( $install_label ); ?>" disabled><?php _e( 'Install &amp; Preview' ); ?></button> <# } #> </div> </div> <# } #> </div> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Control](wp_customize_control) wp-includes/class-wp-customize-control.php | Customize Control class. | | Version | Description | | --- | --- | | [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. | wordpress class WP_Date_Query {} class WP\_Date\_Query {} ======================== Class for generating SQL clauses that filter a primary query according to date. [WP\_Date\_Query](wp_date_query) is a helper that allows primary query classes, such as [WP\_Query](wp_query), to filter their results by date columns, by generating `WHERE` subclauses to be attached to the primary SQL query string. Attempting to filter by an invalid date value (eg month=13) will generate SQL that will return no results. In these cases, a [\_doing\_it\_wrong()](../functions/_doing_it_wrong) error notice is also thrown. See [WP\_Date\_Query::validate\_date\_values()](wp_date_query/validate_date_values). * [\_\_construct](wp_date_query/__construct) β€” Constructor. * [build\_mysql\_datetime](wp_date_query/build_mysql_datetime) β€” Builds a MySQL format date/time based on some query parameters. * [build\_time\_query](wp_date_query/build_time_query) β€” Builds a query string for comparing time values (hour, minute, second). * [build\_value](wp_date_query/build_value) β€” Builds and validates a value string based on the comparison operator. * [get\_compare](wp_date_query/get_compare) β€” Determines and validates what comparison operator to use. * [get\_sql](wp_date_query/get_sql) β€” Generates WHERE clause to be appended to a main query. * [get\_sql\_clauses](wp_date_query/get_sql_clauses) β€” Generates SQL clauses to be appended to a main query. * [get\_sql\_for\_clause](wp_date_query/get_sql_for_clause) β€” Turns a first-order date query into SQL for a WHERE clause. * [get\_sql\_for\_query](wp_date_query/get_sql_for_query) β€” Generates SQL clauses for a single query array. * [get\_sql\_for\_subquery](wp_date_query/get_sql_for_subquery) β€” Turns a single date clause into pieces for a WHERE clause. * [is\_first\_order\_clause](wp_date_query/is_first_order_clause) β€” Determines whether this is a first-order clause. * [sanitize\_query](wp_date_query/sanitize_query) β€” Recursive-friendly query sanitizer. * [sanitize\_relation](wp_date_query/sanitize_relation) β€” Sanitizes a 'relation' operator. * [validate\_column](wp_date_query/validate_column) β€” Validates a column name parameter. * [validate\_date\_values](wp_date_query/validate_date_values) β€” Validates the given date\_query values and triggers errors if something is not valid. File: `wp-includes/class-wp-date-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-date-query.php/) ``` class WP_Date_Query { /** * Array of date queries. * * See WP_Date_Query::__construct() for information on date query arguments. * * @since 3.7.0 * @var array */ public $queries = array(); /** * The default relation between top-level queries. Can be either 'AND' or 'OR'. * * @since 3.7.0 * @var string */ public $relation = 'AND'; /** * The column to query against. Can be changed via the query arguments. * * @since 3.7.0 * @var string */ public $column = 'post_date'; /** * The value comparison operator. Can be changed via the query arguments. * * @since 3.7.0 * @var string */ public $compare = '='; /** * Supported time-related parameter keys. * * @since 4.1.0 * @var string[] */ public $time_keys = array( 'after', 'before', 'year', 'month', 'monthnum', 'week', 'w', 'dayofyear', 'day', 'dayofweek', 'dayofweek_iso', 'hour', 'minute', 'second' ); /** * Constructor. * * Time-related parameters that normally require integer values ('year', 'month', 'week', 'dayofyear', 'day', * 'dayofweek', 'dayofweek_iso', 'hour', 'minute', 'second') accept arrays of integers for some values of * 'compare'. When 'compare' is 'IN' or 'NOT IN', arrays are accepted; when 'compare' is 'BETWEEN' or 'NOT * BETWEEN', arrays of two valid values are required. See individual argument descriptions for accepted values. * * @since 3.7.0 * @since 4.0.0 The $inclusive logic was updated to include all times within the date range. * @since 4.1.0 Introduced 'dayofweek_iso' time type parameter. * * @param array $date_query { * Array of date query clauses. * * @type array ...$0 { * @type string $column Optional. The column to query against. If undefined, inherits the value of * the `$default_column` parameter. See WP_Date_Query::validate_column() and * the {@see 'date_query_valid_columns'} filter for the list of accepted values. * Default 'post_date'. * @type string $compare Optional. The comparison operator. Accepts '=', '!=', '>', '>=', '<', '<=', * 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'. Default '='. * @type string $relation Optional. The boolean relationship between the date queries. Accepts 'OR' or 'AND'. * Default 'OR'. * @type array ...$0 { * Optional. An array of first-order clause parameters, or another fully-formed date query. * * @type string|array $before { * Optional. Date to retrieve posts before. Accepts `strtotime()`-compatible string, * or array of 'year', 'month', 'day' values. * * @type string $year The four-digit year. Default empty. Accepts any four-digit year. * @type string $month Optional when passing array.The month of the year. * Default (string:empty)|(array:1). Accepts numbers 1-12. * @type string $day Optional when passing array.The day of the month. * Default (string:empty)|(array:1). Accepts numbers 1-31. * } * @type string|array $after { * Optional. Date to retrieve posts after. Accepts `strtotime()`-compatible string, * or array of 'year', 'month', 'day' values. * * @type string $year The four-digit year. Accepts any four-digit year. Default empty. * @type string $month Optional when passing array. The month of the year. Accepts numbers 1-12. * Default (string:empty)|(array:12). * @type string $day Optional when passing array.The day of the month. Accepts numbers 1-31. * Default (string:empty)|(array:last day of month). * } * @type string $column Optional. Used to add a clause comparing a column other than * the column specified in the top-level `$column` parameter. * See WP_Date_Query::validate_column() and * the {@see 'date_query_valid_columns'} filter for the list * of accepted values. Default is the value of top-level `$column`. * @type string $compare Optional. The comparison operator. Accepts '=', '!=', '>', '>=', * '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'. 'IN', * 'NOT IN', 'BETWEEN', and 'NOT BETWEEN'. Comparisons support * arrays in some time-related parameters. Default '='. * @type bool $inclusive Optional. Include results from dates specified in 'before' or * 'after'. Default false. * @type int|int[] $year Optional. The four-digit year number. Accepts any four-digit year * or an array of years if `$compare` supports it. Default empty. * @type int|int[] $month Optional. The two-digit month number. Accepts numbers 1-12 or an * array of valid numbers if `$compare` supports it. Default empty. * @type int|int[] $week Optional. The week number of the year. Accepts numbers 0-53 or an * array of valid numbers if `$compare` supports it. Default empty. * @type int|int[] $dayofyear Optional. The day number of the year. Accepts numbers 1-366 or an * array of valid numbers if `$compare` supports it. * @type int|int[] $day Optional. The day of the month. Accepts numbers 1-31 or an array * of valid numbers if `$compare` supports it. Default empty. * @type int|int[] $dayofweek Optional. The day number of the week. Accepts numbers 1-7 (1 is * Sunday) or an array of valid numbers if `$compare` supports it. * Default empty. * @type int|int[] $dayofweek_iso Optional. The day number of the week (ISO). Accepts numbers 1-7 * (1 is Monday) or an array of valid numbers if `$compare` supports it. * Default empty. * @type int|int[] $hour Optional. The hour of the day. Accepts numbers 0-23 or an array * of valid numbers if `$compare` supports it. Default empty. * @type int|int[] $minute Optional. The minute of the hour. Accepts numbers 0-59 or an array * of valid numbers if `$compare` supports it. Default empty. * @type int|int[] $second Optional. The second of the minute. Accepts numbers 0-59 or an * array of valid numbers if `$compare` supports it. Default empty. * } * } * } * @param string $default_column Optional. Default column to query against. See WP_Date_Query::validate_column() * and the {@see 'date_query_valid_columns'} filter for the list of accepted values. * Default 'post_date'. */ public function __construct( $date_query, $default_column = 'post_date' ) { if ( empty( $date_query ) || ! is_array( $date_query ) ) { return; } if ( isset( $date_query['relation'] ) ) { $this->relation = $this->sanitize_relation( $date_query['relation'] ); } else { $this->relation = 'AND'; } // Support for passing time-based keys in the top level of the $date_query array. if ( ! isset( $date_query[0] ) ) { $date_query = array( $date_query ); } if ( ! empty( $date_query['column'] ) ) { $date_query['column'] = esc_sql( $date_query['column'] ); } else { $date_query['column'] = esc_sql( $default_column ); } $this->column = $this->validate_column( $this->column ); $this->compare = $this->get_compare( $date_query ); $this->queries = $this->sanitize_query( $date_query ); } /** * Recursive-friendly query sanitizer. * * Ensures that each query-level clause has a 'relation' key, and that * each first-order clause contains all the necessary keys from `$defaults`. * * @since 4.1.0 * * @param array $queries * @param array $parent_query * @return array Sanitized queries. */ public function sanitize_query( $queries, $parent_query = null ) { $cleaned_query = array(); $defaults = array( 'column' => 'post_date', 'compare' => '=', 'relation' => 'AND', ); // Numeric keys should always have array values. foreach ( $queries as $qkey => $qvalue ) { if ( is_numeric( $qkey ) && ! is_array( $qvalue ) ) { unset( $queries[ $qkey ] ); } } // Each query should have a value for each default key. Inherit from the parent when possible. foreach ( $defaults as $dkey => $dvalue ) { if ( isset( $queries[ $dkey ] ) ) { continue; } if ( isset( $parent_query[ $dkey ] ) ) { $queries[ $dkey ] = $parent_query[ $dkey ]; } else { $queries[ $dkey ] = $dvalue; } } // Validate the dates passed in the query. if ( $this->is_first_order_clause( $queries ) ) { $this->validate_date_values( $queries ); } // Sanitize the relation parameter. $queries['relation'] = $this->sanitize_relation( $queries['relation'] ); foreach ( $queries as $key => $q ) { if ( ! is_array( $q ) || in_array( $key, $this->time_keys, true ) ) { // This is a first-order query. Trust the values and sanitize when building SQL. $cleaned_query[ $key ] = $q; } else { // Any array without a time key is another query, so we recurse. $cleaned_query[] = $this->sanitize_query( $q, $queries ); } } return $cleaned_query; } /** * Determines whether this is a first-order clause. * * Checks to see if the current clause has any time-related keys. * If so, it's first-order. * * @since 4.1.0 * * @param array $query Query clause. * @return bool True if this is a first-order clause. */ protected function is_first_order_clause( $query ) { $time_keys = array_intersect( $this->time_keys, array_keys( $query ) ); return ! empty( $time_keys ); } /** * Determines and validates what comparison operator to use. * * @since 3.7.0 * * @param array $query A date query or a date subquery. * @return string The comparison operator. */ public function get_compare( $query ) { if ( ! empty( $query['compare'] ) && in_array( $query['compare'], array( '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ), true ) ) { return strtoupper( $query['compare'] ); } return $this->compare; } /** * Validates the given date_query values and triggers errors if something is not valid. * * Note that date queries with invalid date ranges are allowed to * continue (though of course no items will be found for impossible dates). * This method only generates debug notices for these cases. * * @since 4.1.0 * * @param array $date_query The date_query array. * @return bool True if all values in the query are valid, false if one or more fail. */ public function validate_date_values( $date_query = array() ) { if ( empty( $date_query ) ) { return false; } $valid = true; /* * Validate 'before' and 'after' up front, then let the * validation routine continue to be sure that all invalid * values generate errors too. */ if ( array_key_exists( 'before', $date_query ) && is_array( $date_query['before'] ) ) { $valid = $this->validate_date_values( $date_query['before'] ); } if ( array_key_exists( 'after', $date_query ) && is_array( $date_query['after'] ) ) { $valid = $this->validate_date_values( $date_query['after'] ); } // Array containing all min-max checks. $min_max_checks = array(); // Days per year. if ( array_key_exists( 'year', $date_query ) ) { /* * If a year exists in the date query, we can use it to get the days. * If multiple years are provided (as in a BETWEEN), use the first one. */ if ( is_array( $date_query['year'] ) ) { $_year = reset( $date_query['year'] ); } else { $_year = $date_query['year']; } $max_days_of_year = gmdate( 'z', mktime( 0, 0, 0, 12, 31, $_year ) ) + 1; } else { // Otherwise we use the max of 366 (leap-year). $max_days_of_year = 366; } $min_max_checks['dayofyear'] = array( 'min' => 1, 'max' => $max_days_of_year, ); // Days per week. $min_max_checks['dayofweek'] = array( 'min' => 1, 'max' => 7, ); // Days per week. $min_max_checks['dayofweek_iso'] = array( 'min' => 1, 'max' => 7, ); // Months per year. $min_max_checks['month'] = array( 'min' => 1, 'max' => 12, ); // Weeks per year. if ( isset( $_year ) ) { /* * If we have a specific year, use it to calculate number of weeks. * Note: the number of weeks in a year is the date in which Dec 28 appears. */ $week_count = gmdate( 'W', mktime( 0, 0, 0, 12, 28, $_year ) ); } else { // Otherwise set the week-count to a maximum of 53. $week_count = 53; } $min_max_checks['week'] = array( 'min' => 1, 'max' => $week_count, ); // Days per month. $min_max_checks['day'] = array( 'min' => 1, 'max' => 31, ); // Hours per day. $min_max_checks['hour'] = array( 'min' => 0, 'max' => 23, ); // Minutes per hour. $min_max_checks['minute'] = array( 'min' => 0, 'max' => 59, ); // Seconds per minute. $min_max_checks['second'] = array( 'min' => 0, 'max' => 59, ); // Concatenate and throw a notice for each invalid value. foreach ( $min_max_checks as $key => $check ) { if ( ! array_key_exists( $key, $date_query ) ) { continue; } // Throw a notice for each failing value. foreach ( (array) $date_query[ $key ] as $_value ) { $is_between = $_value >= $check['min'] && $_value <= $check['max']; if ( ! is_numeric( $_value ) || ! $is_between ) { $error = sprintf( /* translators: Date query invalid date message. 1: Invalid value, 2: Type of value, 3: Minimum valid value, 4: Maximum valid value. */ __( 'Invalid value %1$s for %2$s. Expected value should be between %3$s and %4$s.' ), '<code>' . esc_html( $_value ) . '</code>', '<code>' . esc_html( $key ) . '</code>', '<code>' . esc_html( $check['min'] ) . '</code>', '<code>' . esc_html( $check['max'] ) . '</code>' ); _doing_it_wrong( __CLASS__, $error, '4.1.0' ); $valid = false; } } } // If we already have invalid date messages, don't bother running through checkdate(). if ( ! $valid ) { return $valid; } $day_month_year_error_msg = ''; $day_exists = array_key_exists( 'day', $date_query ) && is_numeric( $date_query['day'] ); $month_exists = array_key_exists( 'month', $date_query ) && is_numeric( $date_query['month'] ); $year_exists = array_key_exists( 'year', $date_query ) && is_numeric( $date_query['year'] ); if ( $day_exists && $month_exists && $year_exists ) { // 1. Checking day, month, year combination. if ( ! wp_checkdate( $date_query['month'], $date_query['day'], $date_query['year'], sprintf( '%s-%s-%s', $date_query['year'], $date_query['month'], $date_query['day'] ) ) ) { $day_month_year_error_msg = sprintf( /* translators: 1: Year, 2: Month, 3: Day of month. */ __( 'The following values do not describe a valid date: year %1$s, month %2$s, day %3$s.' ), '<code>' . esc_html( $date_query['year'] ) . '</code>', '<code>' . esc_html( $date_query['month'] ) . '</code>', '<code>' . esc_html( $date_query['day'] ) . '</code>' ); $valid = false; } } elseif ( $day_exists && $month_exists ) { /* * 2. checking day, month combination * We use 2012 because, as a leap year, it's the most permissive. */ if ( ! wp_checkdate( $date_query['month'], $date_query['day'], 2012, sprintf( '2012-%s-%s', $date_query['month'], $date_query['day'] ) ) ) { $day_month_year_error_msg = sprintf( /* translators: 1: Month, 2: Day of month. */ __( 'The following values do not describe a valid date: month %1$s, day %2$s.' ), '<code>' . esc_html( $date_query['month'] ) . '</code>', '<code>' . esc_html( $date_query['day'] ) . '</code>' ); $valid = false; } } if ( ! empty( $day_month_year_error_msg ) ) { _doing_it_wrong( __CLASS__, $day_month_year_error_msg, '4.1.0' ); } return $valid; } /** * Validates a column name parameter. * * Column names without a table prefix (like 'post_date') are checked against a list of * allowed and known tables, and then, if found, have a table prefix (such as 'wp_posts.') * prepended. Prefixed column names (such as 'wp_posts.post_date') bypass this allowed * check, and are only sanitized to remove illegal characters. * * @since 3.7.0 * * @param string $column The user-supplied column name. * @return string A validated column name value. */ public function validate_column( $column ) { global $wpdb; $valid_columns = array( 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt', 'comment_date', 'comment_date_gmt', 'user_registered', 'registered', 'last_updated', ); // Attempt to detect a table prefix. if ( false === strpos( $column, '.' ) ) { /** * Filters the list of valid date query columns. * * @since 3.7.0 * @since 4.1.0 Added 'user_registered' to the default recognized columns. * @since 4.6.0 Added 'registered' and 'last_updated' to the default recognized columns. * * @param string[] $valid_columns An array of valid date query columns. Defaults * are 'post_date', 'post_date_gmt', 'post_modified', * 'post_modified_gmt', 'comment_date', 'comment_date_gmt', * 'user_registered', 'registered', 'last_updated'. */ if ( ! in_array( $column, apply_filters( 'date_query_valid_columns', $valid_columns ), true ) ) { $column = 'post_date'; } $known_columns = array( $wpdb->posts => array( 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt', ), $wpdb->comments => array( 'comment_date', 'comment_date_gmt', ), $wpdb->users => array( 'user_registered', ), $wpdb->blogs => array( 'registered', 'last_updated', ), ); // If it's a known column name, add the appropriate table prefix. foreach ( $known_columns as $table_name => $table_columns ) { if ( in_array( $column, $table_columns, true ) ) { $column = $table_name . '.' . $column; break; } } } // Remove unsafe characters. return preg_replace( '/[^a-zA-Z0-9_$\.]/', '', $column ); } /** * Generates WHERE clause to be appended to a main query. * * @since 3.7.0 * * @return string MySQL WHERE clause. */ public function get_sql() { $sql = $this->get_sql_clauses(); $where = $sql['where']; /** * Filters the date query WHERE clause. * * @since 3.7.0 * * @param string $where WHERE clause of the date query. * @param WP_Date_Query $query The WP_Date_Query instance. */ return apply_filters( 'get_date_sql', $where, $this ); } /** * Generates SQL clauses to be appended to a main query. * * Called by the public WP_Date_Query::get_sql(), this method is abstracted * out to maintain parity with the other Query classes. * * @since 4.1.0 * * @return string[] { * Array containing JOIN and WHERE SQL clauses to append to the main query. * * @type string $join SQL fragment to append to the main JOIN clause. * @type string $where SQL fragment to append to the main WHERE clause. * } */ protected function get_sql_clauses() { $sql = $this->get_sql_for_query( $this->queries ); if ( ! empty( $sql['where'] ) ) { $sql['where'] = ' AND ' . $sql['where']; } return $sql; } /** * Generates SQL clauses for a single query array. * * If nested subqueries are found, this method recurses the tree to * produce the properly nested SQL. * * @since 4.1.0 * * @param array $query Query to parse. * @param int $depth Optional. Number of tree levels deep we currently are. * Used to calculate indentation. Default 0. * @return array { * Array containing JOIN and WHERE SQL clauses to append to a single query array. * * @type string $join SQL fragment to append to the main JOIN clause. * @type string $where SQL fragment to append to the main WHERE clause. * } */ protected function get_sql_for_query( $query, $depth = 0 ) { $sql_chunks = array( 'join' => array(), 'where' => array(), ); $sql = array( 'join' => '', 'where' => '', ); $indent = ''; for ( $i = 0; $i < $depth; $i++ ) { $indent .= ' '; } foreach ( $query as $key => $clause ) { if ( 'relation' === $key ) { $relation = $query['relation']; } elseif ( is_array( $clause ) ) { // This is a first-order clause. if ( $this->is_first_order_clause( $clause ) ) { $clause_sql = $this->get_sql_for_clause( $clause, $query ); $where_count = count( $clause_sql['where'] ); if ( ! $where_count ) { $sql_chunks['where'][] = ''; } elseif ( 1 === $where_count ) { $sql_chunks['where'][] = $clause_sql['where'][0]; } else { $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )'; } $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] ); // This is a subquery, so we recurse. } else { $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 ); $sql_chunks['where'][] = $clause_sql['where']; $sql_chunks['join'][] = $clause_sql['join']; } } } // Filter to remove empties. $sql_chunks['join'] = array_filter( $sql_chunks['join'] ); $sql_chunks['where'] = array_filter( $sql_chunks['where'] ); if ( empty( $relation ) ) { $relation = 'AND'; } // Filter duplicate JOIN clauses and combine into a single string. if ( ! empty( $sql_chunks['join'] ) ) { $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) ); } // Generate a single WHERE clause with proper brackets and indentation. if ( ! empty( $sql_chunks['where'] ) ) { $sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')'; } return $sql; } /** * Turns a single date clause into pieces for a WHERE clause. * * A wrapper for get_sql_for_clause(), included here for backward * compatibility while retaining the naming convention across Query classes. * * @since 3.7.0 * * @param array $query Date query arguments. * @return string[] { * Array containing JOIN and WHERE SQL clauses to append to the main query. * * @type string $join SQL fragment to append to the main JOIN clause. * @type string $where SQL fragment to append to the main WHERE clause. * } */ protected function get_sql_for_subquery( $query ) { return $this->get_sql_for_clause( $query, '' ); } /** * Turns a first-order date query into SQL for a WHERE clause. * * @since 4.1.0 * * @param array $query Date query clause. * @param array $parent_query Parent query of the current date query. * @return string[] { * Array containing JOIN and WHERE SQL clauses to append to the main query. * * @type string $join SQL fragment to append to the main JOIN clause. * @type string $where SQL fragment to append to the main WHERE clause. * } */ protected function get_sql_for_clause( $query, $parent_query ) { global $wpdb; // The sub-parts of a $where part. $where_parts = array(); $column = ( ! empty( $query['column'] ) ) ? esc_sql( $query['column'] ) : $this->column; $column = $this->validate_column( $column ); $compare = $this->get_compare( $query ); $inclusive = ! empty( $query['inclusive'] ); // Assign greater- and less-than values. $lt = '<'; $gt = '>'; if ( $inclusive ) { $lt .= '='; $gt .= '='; } // Range queries. if ( ! empty( $query['after'] ) ) { $where_parts[] = $wpdb->prepare( "$column $gt %s", $this->build_mysql_datetime( $query['after'], ! $inclusive ) ); } if ( ! empty( $query['before'] ) ) { $where_parts[] = $wpdb->prepare( "$column $lt %s", $this->build_mysql_datetime( $query['before'], $inclusive ) ); } // Specific value queries. $date_units = array( 'YEAR' => array( 'year' ), 'MONTH' => array( 'month', 'monthnum' ), '_wp_mysql_week' => array( 'week', 'w' ), 'DAYOFYEAR' => array( 'dayofyear' ), 'DAYOFMONTH' => array( 'day' ), 'DAYOFWEEK' => array( 'dayofweek' ), 'WEEKDAY' => array( 'dayofweek_iso' ), ); // Check of the possible date units and add them to the query. foreach ( $date_units as $sql_part => $query_parts ) { foreach ( $query_parts as $query_part ) { if ( isset( $query[ $query_part ] ) ) { $value = $this->build_value( $compare, $query[ $query_part ] ); if ( $value ) { switch ( $sql_part ) { case '_wp_mysql_week': $where_parts[] = _wp_mysql_week( $column ) . " $compare $value"; break; case 'WEEKDAY': $where_parts[] = "$sql_part( $column ) + 1 $compare $value"; break; default: $where_parts[] = "$sql_part( $column ) $compare $value"; } break; } } } } if ( isset( $query['hour'] ) || isset( $query['minute'] ) || isset( $query['second'] ) ) { // Avoid notices. foreach ( array( 'hour', 'minute', 'second' ) as $unit ) { if ( ! isset( $query[ $unit ] ) ) { $query[ $unit ] = null; } } $time_query = $this->build_time_query( $column, $compare, $query['hour'], $query['minute'], $query['second'] ); if ( $time_query ) { $where_parts[] = $time_query; } } /* * Return an array of 'join' and 'where' for compatibility * with other query classes. */ return array( 'where' => $where_parts, 'join' => array(), ); } /** * Builds and validates a value string based on the comparison operator. * * @since 3.7.0 * * @param string $compare The compare operator to use. * @param string|array $value The value. * @return string|false|int The value to be used in SQL or false on error. */ public function build_value( $compare, $value ) { if ( ! isset( $value ) ) { return false; } switch ( $compare ) { case 'IN': case 'NOT IN': $value = (array) $value; // Remove non-numeric values. $value = array_filter( $value, 'is_numeric' ); if ( empty( $value ) ) { return false; } return '(' . implode( ',', array_map( 'intval', $value ) ) . ')'; case 'BETWEEN': case 'NOT BETWEEN': if ( ! is_array( $value ) || 2 !== count( $value ) ) { $value = array( $value, $value ); } else { $value = array_values( $value ); } // If either value is non-numeric, bail. foreach ( $value as $v ) { if ( ! is_numeric( $v ) ) { return false; } } $value = array_map( 'intval', $value ); return $value[0] . ' AND ' . $value[1]; default: if ( ! is_numeric( $value ) ) { return false; } return (int) $value; } } /** * Builds a MySQL format date/time based on some query parameters. * * You can pass an array of values (year, month, etc.) with missing parameter values being defaulted to * either the maximum or minimum values (controlled by the $default_to parameter). Alternatively you can * pass a string that will be passed to date_create(). * * @since 3.7.0 * * @param string|array $datetime An array of parameters or a strotime() string. * @param bool $default_to_max Whether to round up incomplete dates. Supported by values * of $datetime that are arrays, or string values that are a * subset of MySQL date format ('Y', 'Y-m', 'Y-m-d', 'Y-m-d H:i'). * Default: false. * @return string|false A MySQL format date/time or false on failure. */ public function build_mysql_datetime( $datetime, $default_to_max = false ) { if ( ! is_array( $datetime ) ) { /* * Try to parse some common date formats, so we can detect * the level of precision and support the 'inclusive' parameter. */ if ( preg_match( '/^(\d{4})$/', $datetime, $matches ) ) { // Y $datetime = array( 'year' => (int) $matches[1], ); } elseif ( preg_match( '/^(\d{4})\-(\d{2})$/', $datetime, $matches ) ) { // Y-m $datetime = array( 'year' => (int) $matches[1], 'month' => (int) $matches[2], ); } elseif ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2})$/', $datetime, $matches ) ) { // Y-m-d $datetime = array( 'year' => (int) $matches[1], 'month' => (int) $matches[2], 'day' => (int) $matches[3], ); } elseif ( preg_match( '/^(\d{4})\-(\d{2})\-(\d{2}) (\d{2}):(\d{2})$/', $datetime, $matches ) ) { // Y-m-d H:i $datetime = array( 'year' => (int) $matches[1], 'month' => (int) $matches[2], 'day' => (int) $matches[3], 'hour' => (int) $matches[4], 'minute' => (int) $matches[5], ); } // If no match is found, we don't support default_to_max. if ( ! is_array( $datetime ) ) { $wp_timezone = wp_timezone(); // Assume local timezone if not provided. $dt = date_create( $datetime, $wp_timezone ); if ( false === $dt ) { return gmdate( 'Y-m-d H:i:s', false ); } return $dt->setTimezone( $wp_timezone )->format( 'Y-m-d H:i:s' ); } } $datetime = array_map( 'absint', $datetime ); if ( ! isset( $datetime['year'] ) ) { $datetime['year'] = current_time( 'Y' ); } if ( ! isset( $datetime['month'] ) ) { $datetime['month'] = ( $default_to_max ) ? 12 : 1; } if ( ! isset( $datetime['day'] ) ) { $datetime['day'] = ( $default_to_max ) ? (int) gmdate( 't', mktime( 0, 0, 0, $datetime['month'], 1, $datetime['year'] ) ) : 1; } if ( ! isset( $datetime['hour'] ) ) { $datetime['hour'] = ( $default_to_max ) ? 23 : 0; } if ( ! isset( $datetime['minute'] ) ) { $datetime['minute'] = ( $default_to_max ) ? 59 : 0; } if ( ! isset( $datetime['second'] ) ) { $datetime['second'] = ( $default_to_max ) ? 59 : 0; } return sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['minute'], $datetime['second'] ); } /** * Builds a query string for comparing time values (hour, minute, second). * * If just hour, minute, or second is set than a normal comparison will be done. * However if multiple values are passed, a pseudo-decimal time will be created * in order to be able to accurately compare against. * * @since 3.7.0 * * @param string $column The column to query against. Needs to be pre-validated! * @param string $compare The comparison operator. Needs to be pre-validated! * @param int|null $hour Optional. An hour value (0-23). * @param int|null $minute Optional. A minute value (0-59). * @param int|null $second Optional. A second value (0-59). * @return string|false A query part or false on failure. */ public function build_time_query( $column, $compare, $hour = null, $minute = null, $second = null ) { global $wpdb; // Have to have at least one. if ( ! isset( $hour ) && ! isset( $minute ) && ! isset( $second ) ) { return false; } // Complex combined queries aren't supported for multi-value queries. if ( in_array( $compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ), true ) ) { $return = array(); $value = $this->build_value( $compare, $hour ); if ( false !== $value ) { $return[] = "HOUR( $column ) $compare $value"; } $value = $this->build_value( $compare, $minute ); if ( false !== $value ) { $return[] = "MINUTE( $column ) $compare $value"; } $value = $this->build_value( $compare, $second ); if ( false !== $value ) { $return[] = "SECOND( $column ) $compare $value"; } return implode( ' AND ', $return ); } // Cases where just one unit is set. if ( isset( $hour ) && ! isset( $minute ) && ! isset( $second ) ) { $value = $this->build_value( $compare, $hour ); if ( false !== $value ) { return "HOUR( $column ) $compare $value"; } } elseif ( ! isset( $hour ) && isset( $minute ) && ! isset( $second ) ) { $value = $this->build_value( $compare, $minute ); if ( false !== $value ) { return "MINUTE( $column ) $compare $value"; } } elseif ( ! isset( $hour ) && ! isset( $minute ) && isset( $second ) ) { $value = $this->build_value( $compare, $second ); if ( false !== $value ) { return "SECOND( $column ) $compare $value"; } } // Single units were already handled. Since hour & second isn't allowed, minute must to be set. if ( ! isset( $minute ) ) { return false; } $format = ''; $time = ''; // Hour. if ( null !== $hour ) { $format .= '%H.'; $time .= sprintf( '%02d', $hour ) . '.'; } else { $format .= '0.'; $time .= '0.'; } // Minute. $format .= '%i'; $time .= sprintf( '%02d', $minute ); if ( isset( $second ) ) { $format .= '%s'; $time .= sprintf( '%02d', $second ); } return $wpdb->prepare( "DATE_FORMAT( $column, %s ) $compare %f", $format, $time ); } /** * Sanitizes a 'relation' operator. * * @since 6.0.3 * * @param string $relation Raw relation key from the query argument. * @return string Sanitized relation ('AND' or 'OR'). */ public function sanitize_relation( $relation ) { if ( 'OR' === strtoupper( $relation ) ) { return 'OR'; } else { return 'AND'; } } } ``` | Version | Description | | --- | --- | | [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Widget_Types_Controller {} class WP\_REST\_Widget\_Types\_Controller {} ============================================ Core class to access widget types via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_widget_types_controller/__construct) β€” Constructor. * [check\_read\_permission](wp_rest_widget_types_controller/check_read_permission) β€” Checks whether the user can read widget types. * [encode\_form\_data](wp_rest_widget_types_controller/encode_form_data) β€” An RPC-style endpoint which can be used by clients to turn user input in a widget admin form into an encoded instance object. * [get\_collection\_params](wp_rest_widget_types_controller/get_collection_params) β€” Retrieves the query params for collections. * [get\_item](wp_rest_widget_types_controller/get_item) β€” Retrieves a single widget type from the collection. * [get\_item\_permissions\_check](wp_rest_widget_types_controller/get_item_permissions_check) β€” Checks if a given request has access to read a widget type. * [get\_item\_schema](wp_rest_widget_types_controller/get_item_schema) β€” Retrieves the widget type's schema, conforming to JSON Schema. * [get\_items](wp_rest_widget_types_controller/get_items) β€” Retrieves the list of all widget types. * [get\_items\_permissions\_check](wp_rest_widget_types_controller/get_items_permissions_check) β€” Checks whether a given request has permission to read widget types. * [get\_widget](wp_rest_widget_types_controller/get_widget) β€” Gets the details about the requested widget. * [get\_widget\_form](wp_rest_widget_types_controller/get_widget_form) β€” Returns the output of WP\_Widget::form() when called with the provided instance. Used by encode\_form\_data() to preview a widget's form. * [get\_widget\_preview](wp_rest_widget_types_controller/get_widget_preview) β€” Returns the output of WP\_Widget::widget() when called with the provided instance. Used by encode\_form\_data() to preview a widget. * [get\_widgets](wp_rest_widget_types_controller/get_widgets) β€” Normalize array of widgets. * [prepare\_item\_for\_response](wp_rest_widget_types_controller/prepare_item_for_response) β€” Prepares a widget type object for serialization. * [prepare\_links](wp_rest_widget_types_controller/prepare_links) β€” Prepares links for the widget type. * [register\_routes](wp_rest_widget_types_controller/register_routes) β€” Registers the widget type routes. * [render](wp_rest_widget_types_controller/render) β€” Renders a single Legacy Widget and wraps it in a JSON-encodable array. * [render\_legacy\_widget\_preview\_iframe](wp_rest_widget_types_controller/render_legacy_widget_preview_iframe) β€” Renders a page containing a preview of the requested Legacy Widget block. File: `wp-includes/rest-api/endpoints/class-wp-rest-widget-types-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-widget-types-controller.php/) ``` class WP_REST_Widget_Types_Controller extends WP_REST_Controller { /** * Constructor. * * @since 5.8.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'widget-types'; } /** * Registers the widget type routes. * * @since 5.8.0 * * @see register_rest_route() */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => $this->get_collection_params(), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[a-zA-Z0-9_-]+)', array( 'args' => array( 'id' => array( 'description' => __( 'The widget type id.' ), 'type' => 'string', ), ), array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'permission_callback' => array( $this, 'get_item_permissions_check' ), 'args' => $this->get_collection_params(), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[a-zA-Z0-9_-]+)/encode', array( 'args' => array( 'id' => array( 'description' => __( 'The widget type id.' ), 'type' => 'string', 'required' => true, ), 'instance' => array( 'description' => __( 'Current instance settings of the widget.' ), 'type' => 'object', ), 'form_data' => array( 'description' => __( 'Serialized widget form data to encode into instance settings.' ), 'type' => 'string', 'sanitize_callback' => static function( $string ) { $array = array(); wp_parse_str( $string, $array ); return $array; }, ), ), array( 'methods' => WP_REST_Server::CREATABLE, 'permission_callback' => array( $this, 'get_item_permissions_check' ), 'callback' => array( $this, 'encode_form_data' ), ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[a-zA-Z0-9_-]+)/render', array( array( 'methods' => WP_REST_Server::CREATABLE, 'permission_callback' => array( $this, 'get_item_permissions_check' ), 'callback' => array( $this, 'render' ), 'args' => array( 'id' => array( 'description' => __( 'The widget type id.' ), 'type' => 'string', 'required' => true, ), 'instance' => array( 'description' => __( 'Current instance settings of the widget.' ), 'type' => 'object', ), ), ), ) ); } /** * Checks whether a given request has permission to read widget types. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { return $this->check_read_permission(); } /** * Retrieves the list of all widget types. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { $data = array(); foreach ( $this->get_widgets() as $widget ) { $widget_type = $this->prepare_item_for_response( $widget, $request ); $data[] = $this->prepare_response_for_collection( $widget_type ); } return rest_ensure_response( $data ); } /** * Checks if a given request has access to read a widget type. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise. */ public function get_item_permissions_check( $request ) { $check = $this->check_read_permission(); if ( is_wp_error( $check ) ) { return $check; } $widget_id = $request['id']; $widget_type = $this->get_widget( $widget_id ); if ( is_wp_error( $widget_type ) ) { return $widget_type; } return true; } /** * Checks whether the user can read widget types. * * @since 5.8.0 * * @return true|WP_Error True if the widget type is visible, WP_Error otherwise. */ protected function check_read_permission() { if ( ! current_user_can( 'edit_theme_options' ) ) { return new WP_Error( 'rest_cannot_manage_widgets', __( 'Sorry, you are not allowed to manage widgets on this site.' ), array( 'status' => rest_authorization_required_code(), ) ); } return true; } /** * Gets the details about the requested widget. * * @since 5.8.0 * * @param string $id The widget type id. * @return array|WP_Error The array of widget data if the name is valid, WP_Error otherwise. */ public function get_widget( $id ) { foreach ( $this->get_widgets() as $widget ) { if ( $id === $widget['id'] ) { return $widget; } } return new WP_Error( 'rest_widget_type_invalid', __( 'Invalid widget type.' ), array( 'status' => 404 ) ); } /** * Normalize array of widgets. * * @since 5.8.0 * * @global WP_Widget_Factory $wp_widget_factory * @global array $wp_registered_widgets The list of registered widgets. * * @return array Array of widgets. */ protected function get_widgets() { global $wp_widget_factory, $wp_registered_widgets; $widgets = array(); foreach ( $wp_registered_widgets as $widget ) { $parsed_id = wp_parse_widget_id( $widget['id'] ); $widget_object = $wp_widget_factory->get_widget_object( $parsed_id['id_base'] ); $widget['id'] = $parsed_id['id_base']; $widget['is_multi'] = (bool) $widget_object; if ( isset( $widget['name'] ) ) { $widget['name'] = html_entity_decode( $widget['name'], ENT_QUOTES, get_bloginfo( 'charset' ) ); } if ( isset( $widget['description'] ) ) { $widget['description'] = html_entity_decode( $widget['description'], ENT_QUOTES, get_bloginfo( 'charset' ) ); } unset( $widget['callback'] ); $classname = ''; foreach ( (array) $widget['classname'] as $cn ) { if ( is_string( $cn ) ) { $classname .= '_' . $cn; } elseif ( is_object( $cn ) ) { $classname .= '_' . get_class( $cn ); } } $widget['classname'] = ltrim( $classname, '_' ); $widgets[ $widget['id'] ] = $widget; } ksort( $widgets ); return $widgets; } /** * Retrieves a single widget type from the collection. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { $widget_id = $request['id']; $widget_type = $this->get_widget( $widget_id ); if ( is_wp_error( $widget_type ) ) { return $widget_type; } $data = $this->prepare_item_for_response( $widget_type, $request ); return rest_ensure_response( $data ); } /** * Prepares a widget type object for serialization. * * @since 5.8.0 * @since 5.9.0 Renamed `$widget_type` to `$item` to match parent class for PHP 8 named parameter support. * * @param array $item Widget type data. * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response Widget type data. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $widget_type = $item; $fields = $this->get_fields_for_response( $request ); $data = array( 'id' => $widget_type['id'], ); $schema = $this->get_item_schema(); $extra_fields = array( 'name', 'description', 'is_multi', 'classname', 'widget_class', 'option_name', 'customize_selective_refresh', ); foreach ( $extra_fields as $extra_field ) { if ( ! rest_is_field_included( $extra_field, $fields ) ) { continue; } if ( isset( $widget_type[ $extra_field ] ) ) { $field = $widget_type[ $extra_field ]; } elseif ( array_key_exists( 'default', $schema['properties'][ $extra_field ] ) ) { $field = $schema['properties'][ $extra_field ]['default']; } else { $field = ''; } $data[ $extra_field ] = rest_sanitize_value_from_schema( $field, $schema['properties'][ $extra_field ] ); } $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( $widget_type ) ); } /** * Filters the REST API response for a widget type. * * @since 5.8.0 * * @param WP_REST_Response $response The response object. * @param array $widget_type The array of widget data. * @param WP_REST_Request $request The request object. */ return apply_filters( 'rest_prepare_widget_type', $response, $widget_type, $request ); } /** * Prepares links for the widget type. * * @since 5.8.0 * * @param array $widget_type Widget type data. * @return array Links for the given widget type. */ protected function prepare_links( $widget_type ) { return array( 'collection' => array( 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ), ), 'self' => array( 'href' => rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $widget_type['id'] ) ), ), ); } /** * Retrieves the widget type's schema, conforming to JSON Schema. * * @since 5.8.0 * * @return array Item schema data. */ 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' => 'widget-type', 'type' => 'object', 'properties' => array( 'id' => array( 'description' => __( 'Unique slug identifying the widget type.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'name' => array( 'description' => __( 'Human-readable name identifying the widget type.' ), 'type' => 'string', 'default' => '', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'description' => array( 'description' => __( 'Description of the widget.' ), 'type' => 'string', 'default' => '', 'context' => array( 'view', 'edit', 'embed' ), ), 'is_multi' => array( 'description' => __( 'Whether the widget supports multiple instances' ), 'type' => 'boolean', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'classname' => array( 'description' => __( 'Class name' ), 'type' => 'string', 'default' => '', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), ), ); $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * An RPC-style endpoint which can be used by clients to turn user input in * a widget admin form into an encoded instance object. * * Accepts: * * - id: A widget type ID. * - instance: A widget's encoded instance object. Optional. * - form_data: Form data from submitting a widget's admin form. Optional. * * Returns: * - instance: The encoded instance object after updating the widget with * the given form data. * - form: The widget's admin form after updating the widget with the * given form data. * * @since 5.8.0 * * @global WP_Widget_Factory $wp_widget_factory * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function encode_form_data( $request ) { global $wp_widget_factory; $id = $request['id']; $widget_object = $wp_widget_factory->get_widget_object( $id ); if ( ! $widget_object ) { return new WP_Error( 'rest_invalid_widget', __( 'Cannot preview a widget that does not extend WP_Widget.' ), array( 'status' => 400 ) ); } // Set the widget's number so that the id attributes in the HTML that we // return are predictable. if ( isset( $request['number'] ) && is_numeric( $request['number'] ) ) { $widget_object->_set( (int) $request['number'] ); } else { $widget_object->_set( -1 ); } if ( isset( $request['instance']['encoded'], $request['instance']['hash'] ) ) { $serialized_instance = base64_decode( $request['instance']['encoded'] ); if ( ! hash_equals( wp_hash( $serialized_instance ), $request['instance']['hash'] ) ) { return new WP_Error( 'rest_invalid_widget', __( 'The provided instance is malformed.' ), array( 'status' => 400 ) ); } $instance = unserialize( $serialized_instance ); } else { $instance = array(); } if ( isset( $request['form_data'][ "widget-$id" ] ) && is_array( $request['form_data'][ "widget-$id" ] ) ) { $new_instance = array_values( $request['form_data'][ "widget-$id" ] )[0]; $old_instance = $instance; $instance = $widget_object->update( $new_instance, $old_instance ); /** This filter is documented in wp-includes/class-wp-widget.php */ $instance = apply_filters( 'widget_update_callback', $instance, $new_instance, $old_instance, $widget_object ); } $serialized_instance = serialize( $instance ); $widget_key = $wp_widget_factory->get_widget_key( $id ); $response = array( 'form' => trim( $this->get_widget_form( $widget_object, $instance ) ), 'preview' => trim( $this->get_widget_preview( $widget_key, $instance ) ), 'instance' => array( 'encoded' => base64_encode( $serialized_instance ), 'hash' => wp_hash( $serialized_instance ), ), ); if ( ! empty( $widget_object->widget_options['show_instance_in_rest'] ) ) { // Use new stdClass so that JSON result is {} and not []. $response['instance']['raw'] = empty( $instance ) ? new stdClass : $instance; } return rest_ensure_response( $response ); } /** * Returns the output of WP_Widget::widget() when called with the provided * instance. Used by encode_form_data() to preview a widget. * @since 5.8.0 * * @param string $widget The widget's PHP class name (see class-wp-widget.php). * @param array $instance Widget instance settings. * @return string */ private function get_widget_preview( $widget, $instance ) { ob_start(); the_widget( $widget, $instance ); return ob_get_clean(); } /** * Returns the output of WP_Widget::form() when called with the provided * instance. Used by encode_form_data() to preview a widget's form. * * @since 5.8.0 * * @param WP_Widget $widget_object Widget object to call widget() on. * @param array $instance Widget instance settings. * @return string */ private function get_widget_form( $widget_object, $instance ) { ob_start(); /** This filter is documented in wp-includes/class-wp-widget.php */ $instance = apply_filters( 'widget_form_callback', $instance, $widget_object ); if ( false !== $instance ) { $return = $widget_object->form( $instance ); /** This filter is documented in wp-includes/class-wp-widget.php */ do_action_ref_array( 'in_widget_form', array( &$widget_object, &$return, $instance ) ); } return ob_get_clean(); } /** * Renders a single Legacy Widget and wraps it in a JSON-encodable array. * * @since 5.9.0 * * @param WP_REST_Request $request Full details about the request. * * @return array An array with rendered Legacy Widget HTML. */ public function render( $request ) { return array( 'preview' => $this->render_legacy_widget_preview_iframe( $request['id'], isset( $request['instance'] ) ? $request['instance'] : null ), ); } /** * Renders a page containing a preview of the requested Legacy Widget block. * * @since 5.9.0 * * @param string $id_base The id base of the requested widget. * @param array $instance The widget instance attributes. * * @return string Rendered Legacy Widget block preview. */ private function render_legacy_widget_preview_iframe( $id_base, $instance ) { if ( ! defined( 'IFRAME_REQUEST' ) ) { define( 'IFRAME_REQUEST', true ); } ob_start(); ?> <!doctype html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="profile" href="https://gmpg.org/xfn/11" /> <?php wp_head(); ?> <style> /* Reset theme styles */ html, body, #page, #content { padding: 0 !important; margin: 0 !important; } </style> </head> <body <?php body_class(); ?>> <div id="page" class="site"> <div id="content" class="site-content"> <?php $registry = WP_Block_Type_Registry::get_instance(); $block = $registry->get_registered( 'core/legacy-widget' ); echo $block->render( array( 'idBase' => $id_base, 'instance' => $instance, ) ); ?> </div><!-- #content --> </div><!-- #page --> <?php wp_footer(); ?> </body> </html> <?php return ob_get_clean(); } /** * Retrieves the query params for collections. * * @since 5.8.0 * * @return array Collection parameters. */ public function get_collection_params() { return array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
programming_docs
wordpress class WP_Privacy_Requests_Table {} class WP\_Privacy\_Requests\_Table {} ===================================== List Table API: [WP\_Privacy\_Requests\_Table](wp_privacy_requests_table) class * [column\_cb](wp_privacy_requests_table/column_cb) β€” Checkbox column. * [column\_created\_timestamp](wp_privacy_requests_table/column_created_timestamp) β€” Created timestamp column. Overridden by children. * [column\_default](wp_privacy_requests_table/column_default) β€” Default column handler. * [column\_email](wp_privacy_requests_table/column_email) β€” Actions column. Overridden by children. * [column\_next\_steps](wp_privacy_requests_table/column_next_steps) β€” Next steps column. Overridden by children. * [column\_status](wp_privacy_requests_table/column_status) β€” Status column. * [embed\_scripts](wp_privacy_requests_table/embed_scripts) β€” Embed scripts used to perform actions. Overridden by children. * [get\_admin\_url](wp_privacy_requests_table/get_admin_url) β€” Normalize the admin URL to the current page (by request\_type). * [get\_bulk\_actions](wp_privacy_requests_table/get_bulk_actions) β€” Get bulk actions. * [get\_columns](wp_privacy_requests_table/get_columns) β€” Get columns to show in the list table. * [get\_default\_primary\_column\_name](wp_privacy_requests_table/get_default_primary_column_name) β€” Default primary column. * [get\_request\_counts](wp_privacy_requests_table/get_request_counts) β€” Count number of requests for each status. * [get\_sortable\_columns](wp_privacy_requests_table/get_sortable_columns) β€” Get a list of sortable columns. * [get\_timestamp\_as\_date](wp_privacy_requests_table/get_timestamp_as_date) β€” Convert timestamp for display. * [get\_views](wp_privacy_requests_table/get_views) β€” Get an associative array ( id => link ) with the list of views available on this table. * [prepare\_items](wp_privacy_requests_table/prepare_items) β€” Prepare items to output. * [process\_bulk\_action](wp_privacy_requests_table/process_bulk_action) β€” Process bulk actions. * [single\_row](wp_privacy_requests_table/single_row) β€” Generates content for a single row of the table, File: `wp-admin/includes/class-wp-privacy-requests-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-requests-table.php/) ``` abstract class WP_Privacy_Requests_Table extends WP_List_Table { /** * Action name for the requests this table will work with. Classes * which inherit from WP_Privacy_Requests_Table should define this. * * Example: 'export_personal_data'. * * @since 4.9.6 * * @var string $request_type Name of action. */ protected $request_type = 'INVALID'; /** * Post type to be used. * * @since 4.9.6 * * @var string $post_type The post type. */ protected $post_type = 'INVALID'; /** * Get columns to show in the list table. * * @since 4.9.6 * * @return string[] Array of column titles keyed by their column name. */ public function get_columns() { $columns = array( 'cb' => '<input type="checkbox" />', 'email' => __( 'Requester' ), 'status' => __( 'Status' ), 'created_timestamp' => __( 'Requested' ), 'next_steps' => __( 'Next steps' ), ); return $columns; } /** * Normalize the admin URL to the current page (by request_type). * * @since 5.3.0 * * @return string URL to the current admin page. */ protected function get_admin_url() { $pagenow = str_replace( '_', '-', $this->request_type ); if ( 'remove-personal-data' === $pagenow ) { $pagenow = 'erase-personal-data'; } return admin_url( $pagenow . '.php' ); } /** * Get a list of sortable columns. * * @since 4.9.6 * * @return array Default sortable columns. */ protected function get_sortable_columns() { /* * The initial sorting is by 'Requested' (post_date) and descending. * With initial sorting, the first click on 'Requested' should be ascending. * With 'Requester' sorting active, the next click on 'Requested' should be descending. */ $desc_first = isset( $_GET['orderby'] ); return array( 'email' => 'requester', 'created_timestamp' => array( 'requested', $desc_first ), ); } /** * Default primary column. * * @since 4.9.6 * * @return string Default primary column name. */ protected function get_default_primary_column_name() { return 'email'; } /** * Count number of requests for each status. * * @since 4.9.6 * * @global wpdb $wpdb WordPress database abstraction object. * * @return object Number of posts for each status. */ protected function get_request_counts() { global $wpdb; $cache_key = $this->post_type . '-' . $this->request_type; $counts = wp_cache_get( $cache_key, 'counts' ); if ( false !== $counts ) { return $counts; } $query = " SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s AND post_name = %s GROUP BY post_status"; $results = (array) $wpdb->get_results( $wpdb->prepare( $query, $this->post_type, $this->request_type ), ARRAY_A ); $counts = array_fill_keys( get_post_stati(), 0 ); foreach ( $results as $row ) { $counts[ $row['post_status'] ] = $row['num_posts']; } $counts = (object) $counts; wp_cache_set( $cache_key, $counts, 'counts' ); return $counts; } /** * Get an associative array ( id => link ) with the list of views available on this table. * * @since 4.9.6 * * @return string[] An array of HTML links keyed by their view. */ protected function get_views() { $current_status = isset( $_REQUEST['filter-status'] ) ? sanitize_text_field( $_REQUEST['filter-status'] ) : ''; $statuses = _wp_privacy_statuses(); $views = array(); $counts = $this->get_request_counts(); $total_requests = absint( array_sum( (array) $counts ) ); // Normalized admin URL. $admin_url = $this->get_admin_url(); $status_label = sprintf( /* translators: %s: Number of requests. */ _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $total_requests, 'requests' ), number_format_i18n( $total_requests ) ); $views['all'] = array( 'url' => esc_url( $admin_url ), 'label' => $status_label, 'current' => empty( $current_status ), ); foreach ( $statuses as $status => $label ) { $post_status = get_post_status_object( $status ); if ( ! $post_status ) { continue; } $total_status_requests = absint( $counts->{$status} ); if ( ! $total_status_requests ) { continue; } $status_label = sprintf( translate_nooped_plural( $post_status->label_count, $total_status_requests ), number_format_i18n( $total_status_requests ) ); $status_link = add_query_arg( 'filter-status', $status, $admin_url ); $views[ $status ] = array( 'url' => esc_url( $status_link ), 'label' => $status_label, 'current' => $status === $current_status, ); } return $this->get_views_links( $views ); } /** * Get bulk actions. * * @since 4.9.6 * * @return array Array of bulk action labels keyed by their action. */ protected function get_bulk_actions() { return array( 'resend' => __( 'Resend confirmation requests' ), 'complete' => __( 'Mark requests as completed' ), 'delete' => __( 'Delete requests' ), ); } /** * Process bulk actions. * * @since 4.9.6 * @since 5.6.0 Added support for the `complete` action. */ public function process_bulk_action() { $action = $this->current_action(); $request_ids = isset( $_REQUEST['request_id'] ) ? wp_parse_id_list( wp_unslash( $_REQUEST['request_id'] ) ) : array(); if ( empty( $request_ids ) ) { return; } $count = 0; $failures = 0; check_admin_referer( 'bulk-privacy_requests' ); switch ( $action ) { case 'resend': foreach ( $request_ids as $request_id ) { $resend = _wp_privacy_resend_request( $request_id ); if ( $resend && ! is_wp_error( $resend ) ) { $count++; } else { $failures++; } } if ( $failures ) { add_settings_error( 'bulk_action', 'bulk_action', sprintf( /* translators: %d: Number of requests. */ _n( '%d confirmation request failed to resend.', '%d confirmation requests failed to resend.', $failures ), $failures ), 'error' ); } if ( $count ) { add_settings_error( 'bulk_action', 'bulk_action', sprintf( /* translators: %d: Number of requests. */ _n( '%d confirmation request re-sent successfully.', '%d confirmation requests re-sent successfully.', $count ), $count ), 'success' ); } break; case 'complete': foreach ( $request_ids as $request_id ) { $result = _wp_privacy_completed_request( $request_id ); if ( $result && ! is_wp_error( $result ) ) { $count++; } } add_settings_error( 'bulk_action', 'bulk_action', sprintf( /* translators: %d: Number of requests. */ _n( '%d request marked as complete.', '%d requests marked as complete.', $count ), $count ), 'success' ); break; case 'delete': foreach ( $request_ids as $request_id ) { if ( wp_delete_post( $request_id, true ) ) { $count++; } else { $failures++; } } if ( $failures ) { add_settings_error( 'bulk_action', 'bulk_action', sprintf( /* translators: %d: Number of requests. */ _n( '%d request failed to delete.', '%d requests failed to delete.', $failures ), $failures ), 'error' ); } if ( $count ) { add_settings_error( 'bulk_action', 'bulk_action', sprintf( /* translators: %d: Number of requests. */ _n( '%d request deleted successfully.', '%d requests deleted successfully.', $count ), $count ), 'success' ); } break; } } /** * Prepare items to output. * * @since 4.9.6 * @since 5.1.0 Added support for column sorting. */ public function prepare_items() { $this->items = array(); $posts_per_page = $this->get_items_per_page( $this->request_type . '_requests_per_page' ); $args = array( 'post_type' => $this->post_type, 'post_name__in' => array( $this->request_type ), 'posts_per_page' => $posts_per_page, 'offset' => isset( $_REQUEST['paged'] ) ? max( 0, absint( $_REQUEST['paged'] ) - 1 ) * $posts_per_page : 0, 'post_status' => 'any', 's' => isset( $_REQUEST['s'] ) ? sanitize_text_field( $_REQUEST['s'] ) : '', ); $orderby_mapping = array( 'requester' => 'post_title', 'requested' => 'post_date', ); if ( isset( $_REQUEST['orderby'] ) && isset( $orderby_mapping[ $_REQUEST['orderby'] ] ) ) { $args['orderby'] = $orderby_mapping[ $_REQUEST['orderby'] ]; } if ( isset( $_REQUEST['order'] ) && in_array( strtoupper( $_REQUEST['order'] ), array( 'ASC', 'DESC' ), true ) ) { $args['order'] = strtoupper( $_REQUEST['order'] ); } if ( ! empty( $_REQUEST['filter-status'] ) ) { $filter_status = isset( $_REQUEST['filter-status'] ) ? sanitize_text_field( $_REQUEST['filter-status'] ) : ''; $args['post_status'] = $filter_status; } $requests_query = new WP_Query( $args ); $requests = $requests_query->posts; foreach ( $requests as $request ) { $this->items[] = wp_get_user_request( $request->ID ); } $this->items = array_filter( $this->items ); $this->set_pagination_args( array( 'total_items' => $requests_query->found_posts, 'per_page' => $posts_per_page, ) ); } /** * Checkbox column. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. * @return string Checkbox column markup. */ public function column_cb( $item ) { return sprintf( '<input type="checkbox" name="request_id[]" value="%1$s" /><span class="spinner"></span>', esc_attr( $item->ID ) ); } /** * Status column. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. * @return string Status column markup. */ public function column_status( $item ) { $status = get_post_status( $item->ID ); $status_object = get_post_status_object( $status ); if ( ! $status_object || empty( $status_object->label ) ) { return '-'; } $timestamp = false; switch ( $status ) { case 'request-confirmed': $timestamp = $item->confirmed_timestamp; break; case 'request-completed': $timestamp = $item->completed_timestamp; break; } echo '<span class="status-label status-' . esc_attr( $status ) . '">'; echo esc_html( $status_object->label ); if ( $timestamp ) { echo ' (' . $this->get_timestamp_as_date( $timestamp ) . ')'; } echo '</span>'; } /** * Convert timestamp for display. * * @since 4.9.6 * * @param int $timestamp Event timestamp. * @return string Human readable date. */ protected function get_timestamp_as_date( $timestamp ) { if ( empty( $timestamp ) ) { return ''; } $time_diff = time() - $timestamp; if ( $time_diff >= 0 && $time_diff < DAY_IN_SECONDS ) { /* translators: %s: Human-readable time difference. */ return sprintf( __( '%s ago' ), human_time_diff( $timestamp ) ); } return date_i18n( get_option( 'date_format' ), $timestamp ); } /** * Default column handler. * * @since 4.9.6 * @since 5.7.0 Added `manage_{$this->screen->id}_custom_column` action. * * @param WP_User_Request $item Item being shown. * @param string $column_name Name of column being shown. */ public function column_default( $item, $column_name ) { /** * Fires for each custom column of a specific request type in the Requests list table. * * Custom columns are registered using the {@see 'manage_export-personal-data_columns'} * and the {@see 'manage_erase-personal-data_columns'} filters. * * @since 5.7.0 * * @param string $column_name The name of the column to display. * @param WP_User_Request $item The item being shown. */ do_action( "manage_{$this->screen->id}_custom_column", $column_name, $item ); } /** * Created timestamp column. Overridden by children. * * @since 5.7.0 * * @param WP_User_Request $item Item being shown. * @return string Human readable date. */ public function column_created_timestamp( $item ) { return $this->get_timestamp_as_date( $item->created_timestamp ); } /** * Actions column. Overridden by children. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. * @return string Email column markup. */ public function column_email( $item ) { return sprintf( '<a href="%1$s">%2$s</a> %3$s', esc_url( 'mailto:' . $item->email ), $item->email, $this->row_actions( array() ) ); } /** * Next steps column. Overridden by children. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. */ public function column_next_steps( $item ) {} /** * Generates content for a single row of the table, * * @since 4.9.6 * * @param WP_User_Request $item The current item. */ public function single_row( $item ) { $status = $item->status; echo '<tr id="request-' . esc_attr( $item->ID ) . '" class="status-' . esc_attr( $status ) . '">'; $this->single_row_columns( $item ); echo '</tr>'; } /** * Embed scripts used to perform actions. Overridden by children. * * @since 4.9.6 */ public function embed_scripts() {} } ``` | Uses | Description | | --- | --- | | [WP\_List\_Table](wp_list_table) wp-admin/includes/class-wp-list-table.php | Base class for displaying a list of items in an ajaxified HTML table. | | Used By | Description | | --- | --- | | [WP\_Privacy\_Data\_Removal\_Requests\_List\_Table](wp_privacy_data_removal_requests_list_table) wp-admin/includes/class-wp-privacy-data-removal-requests-list-table.php | [WP\_Privacy\_Data\_Removal\_Requests\_List\_Table](wp_privacy_data_removal_requests_list_table) class. | | [WP\_Privacy\_Data\_Export\_Requests\_List\_Table](wp_privacy_data_export_requests_list_table) wp-admin/includes/class-wp-privacy-data-export-requests-list-table.php | [WP\_Privacy\_Data\_Export\_Requests\_Table](wp_privacy_data_export_requests_table) class. | | Version | Description | | --- | --- | | [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. | wordpress class WP_Network {} class WP\_Network {} ==================== Core class used for interacting with a multisite network. This class is used during load to populate the `$current_site` global and setup the current network. This class is most useful in WordPress multi-network installations where the ability to interact with any network of sites is required. * [\_\_construct](wp_network/__construct) β€” Creates a new WP\_Network object. * [\_\_get](wp_network/__get) β€” Getter. * [\_\_isset](wp_network/__isset) β€” Isset-er. * [\_\_set](wp_network/__set) β€” Setter. * [\_set\_cookie\_domain](wp_network/_set_cookie_domain) β€” Sets the cookie domain based on the network domain if one has not been populated. * [\_set\_site\_name](wp_network/_set_site_name) β€” Sets the site name assigned to the network if one has not been populated. * [get\_by\_path](wp_network/get_by_path) β€” Retrieves the closest matching network for a domain and path. * [get\_instance](wp_network/get_instance) β€” Retrieves a network from the database by its ID. * [get\_main\_site\_id](wp_network/get_main_site_id) β€” Returns the main site ID for the network. File: `wp-includes/class-wp-network.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-network.php/) ``` class WP_Network { /** * Network ID. * * @since 4.4.0 * @since 4.6.0 Converted from public to private to explicitly enable more intuitive * access via magic methods. As part of the access change, the type was * also changed from `string` to `int`. * @var int */ private $id; /** * Domain of the network. * * @since 4.4.0 * @var string */ public $domain = ''; /** * Path of the network. * * @since 4.4.0 * @var string */ public $path = ''; /** * The ID of the network's main site. * * Named "blog" vs. "site" for legacy reasons. A main site is mapped to * the network when the network is created. * * A numeric string, for compatibility reasons. * * @since 4.4.0 * @var string */ private $blog_id = '0'; /** * Domain used to set cookies for this network. * * @since 4.4.0 * @var string */ public $cookie_domain = ''; /** * Name of this network. * * Named "site" vs. "network" for legacy reasons. * * @since 4.4.0 * @var string */ public $site_name = ''; /** * Retrieves a network from the database by its ID. * * @since 4.4.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $network_id The ID of the network to retrieve. * @return WP_Network|false The network's object if found. False if not. */ 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 ); } /** * Creates a new WP_Network object. * * Will populate object properties from the object provided and assign other * default properties based on that information. * * @since 4.4.0 * * @param WP_Network|object $network A network object. */ public function __construct( $network ) { foreach ( get_object_vars( $network ) as $key => $value ) { $this->$key = $value; } $this->_set_site_name(); $this->_set_cookie_domain(); } /** * Getter. * * Allows current multisite naming conventions when getting properties. * * @since 4.6.0 * * @param string $key Property to get. * @return mixed Value of the property. Null if not available. */ 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; } /** * Isset-er. * * Allows current multisite naming conventions when checking for properties. * * @since 4.6.0 * * @param string $key Property to check if set. * @return bool Whether the property is set. */ public function __isset( $key ) { switch ( $key ) { case 'id': case 'blog_id': case 'site_id': return true; } return false; } /** * Setter. * * Allows current multisite naming conventions while setting properties. * * @since 4.6.0 * * @param string $key Property to set. * @param mixed $value Value to assign to the property. */ 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; } } /** * Returns the main site ID for the network. * * Internal method used by the magic getter for the 'blog_id' and 'site_id' * properties. * * @since 4.9.0 * * @return int The ID of the main site. */ 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; } /** * Sets the site name assigned to the network if one has not been populated. * * @since 4.4.0 */ 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 ); } /** * Sets the cookie domain based on the network domain if one has * not been populated. * * @todo What if the domain of the network doesn't match the current site? * * @since 4.4.0 */ 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 ); } } /** * 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. * * @since 4.4.0 * * @param string $domain Domain to check. * @param string $path Path to check. * @param int|null $segments Path segments to use. Defaults to null, or the full path. * @return WP_Network|false Network object if successful. False when no network is found. */ 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; } } ``` | Version | Description | | --- | --- | | [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Terms_Controller {} class WP\_REST\_Terms\_Controller {} ==================================== Core class used to managed terms associated with a taxonomy via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_terms_controller/__construct) β€” Constructor. * [check\_is\_taxonomy\_allowed](wp_rest_terms_controller/check_is_taxonomy_allowed) β€” Checks that the taxonomy is valid. * [check\_read\_terms\_permission\_for\_post](wp_rest_terms_controller/check_read_terms_permission_for_post) β€” Checks if the terms for a post can be read. * [create\_item](wp_rest_terms_controller/create_item) β€” Creates a single term in a taxonomy. * [create\_item\_permissions\_check](wp_rest_terms_controller/create_item_permissions_check) β€” Checks if a request has access to create a term. * [delete\_item](wp_rest_terms_controller/delete_item) β€” Deletes a single term from a taxonomy. * [delete\_item\_permissions\_check](wp_rest_terms_controller/delete_item_permissions_check) β€” Checks if a request has access to delete the specified term. * [get\_collection\_params](wp_rest_terms_controller/get_collection_params) β€” Retrieves the query params for collections. * [get\_item](wp_rest_terms_controller/get_item) β€” Gets a single term from a taxonomy. * [get\_item\_permissions\_check](wp_rest_terms_controller/get_item_permissions_check) β€” Checks if a request has access to read or edit the specified term. * [get\_item\_schema](wp_rest_terms_controller/get_item_schema) β€” Retrieves the term's schema, conforming to JSON Schema. * [get\_items](wp_rest_terms_controller/get_items) β€” Retrieves terms associated with a taxonomy. * [get\_items\_permissions\_check](wp_rest_terms_controller/get_items_permissions_check) β€” Checks if a request has access to read terms in the specified taxonomy. * [get\_term](wp_rest_terms_controller/get_term) β€” Get the term, if the ID is valid. * [prepare\_item\_for\_database](wp_rest_terms_controller/prepare_item_for_database) β€” Prepares a single term for create or update. * [prepare\_item\_for\_response](wp_rest_terms_controller/prepare_item_for_response) β€” Prepares a single term output for response. * [prepare\_links](wp_rest_terms_controller/prepare_links) β€” Prepares links for the request. * [register\_routes](wp_rest_terms_controller/register_routes) β€” Registers the routes for terms. * [update\_item](wp_rest_terms_controller/update_item) β€” Updates a single term from a taxonomy. * [update\_item\_permissions\_check](wp_rest_terms_controller/update_item_permissions_check) β€” Checks if a request has access to update the specified 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/) ``` class WP_REST_Terms_Controller extends WP_REST_Controller { /** * Taxonomy key. * * @since 4.7.0 * @var string */ protected $taxonomy; /** * Instance of a term meta fields object. * * @since 4.7.0 * @var WP_REST_Term_Meta_Fields */ protected $meta; /** * Column to have the terms be sorted by. * * @since 4.7.0 * @var string */ protected $sort_column; /** * Number of terms that were found. * * @since 4.7.0 * @var int */ protected $total_terms; /** * Whether the controller supports batching. * * @since 5.9.0 * @var array */ protected $allow_batch = array( 'v1' => true ); /** * Constructor. * * @since 4.7.0 * * @param string $taxonomy Taxonomy key. */ 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 ); } /** * Registers the routes for terms. * * @since 4.7.0 * * @see register_rest_route() */ 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' ), ) ); } /** * Checks if the terms for a post can be read. * * @since 6.0.3 * * @param WP_Post $post Post object. * @param WP_REST_Request $request Full details about the request. * @return bool Whether the terms for the post can be read. */ 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; } /** * Checks if a request has access to read terms in the specified taxonomy. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, otherwise false or WP_Error object. */ 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; } /** * Retrieves terms associated with a taxonomy. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ 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; } /** * Get the term, if the ID is valid. * * @since 4.7.2 * * @param int $id Supplied ID. * @return WP_Term|WP_Error Term object if ID is valid, WP_Error otherwise. */ 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; } /** * Checks if a request has access to read or edit the specified term. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, otherwise false or WP_Error object. */ 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; } /** * Gets a single term from a taxonomy. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ 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 ); } /** * Checks if a request has access to create a term. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to create items, false or WP_Error object otherwise. */ 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; } /** * Creates a single term in a taxonomy. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ 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; } /** * Checks if a request has access to update the specified term. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to update the item, false or WP_Error object otherwise. */ 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; } /** * Updates a single term from a taxonomy. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ 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 ); } /** * Checks if a request has access to delete the specified term. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to delete the item, otherwise false or WP_Error object. */ 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; } /** * Deletes a single term from a taxonomy. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ 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; } /** * Prepares a single term for create or update. * * @since 4.7.0 * * @param WP_REST_Request $request Request object. * @return object Term object. */ 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 ); } /** * Prepares a single term output for response. * * @since 4.7.0 * * @param WP_Term $item Term object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ 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 ); } /** * Prepares links for the request. * * @since 4.7.0 * * @param WP_Term $term Term object. * @return array Links for the given term. */ 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; } /** * Retrieves the term's schema, conforming to JSON Schema. * * @since 4.7.0 * * @return array Item schema data. */ 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 ); } /** * Retrieves the query params for collections. * * @since 4.7.0 * * @return array Collection parameters. */ 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 ); } /** * Checks that the taxonomy is valid. * * @since 4.7.0 * * @param string $taxonomy Taxonomy to check. * @return bool Whether the taxonomy is allowed for REST management. */ 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 | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Used By | Description | | --- | --- | | [WP\_REST\_Menus\_Controller](wp_rest_menus_controller) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Core class used to managed menu terms associated via the REST API. | | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Revisions_Controller {} class WP\_REST\_Revisions\_Controller {} ======================================== Core class used to access revisions via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_revisions_controller/__construct) β€” Constructor. * [delete\_item](wp_rest_revisions_controller/delete_item) β€” Deletes a single revision. * [delete\_item\_permissions\_check](wp_rest_revisions_controller/delete_item_permissions_check) β€” Checks if a given request has access to delete a revision. * [get\_collection\_params](wp_rest_revisions_controller/get_collection_params) β€” Retrieves the query params for collections. * [get\_item](wp_rest_revisions_controller/get_item) β€” Retrieves one revision from the collection. * [get\_item\_permissions\_check](wp_rest_revisions_controller/get_item_permissions_check) β€” Checks if a given request has access to get a specific revision. * [get\_item\_schema](wp_rest_revisions_controller/get_item_schema) β€” Retrieves the revision's schema, conforming to JSON Schema. * [get\_items](wp_rest_revisions_controller/get_items) β€” Gets a collection of revisions. * [get\_items\_permissions\_check](wp_rest_revisions_controller/get_items_permissions_check) β€” Checks if a given request has access to get revisions. * [get\_parent](wp_rest_revisions_controller/get_parent) β€” Get the parent post, if the ID is valid. * [get\_revision](wp_rest_revisions_controller/get_revision) β€” Get the revision, if the ID is valid. * [prepare\_date\_response](wp_rest_revisions_controller/prepare_date_response) β€” Checks the post\_date\_gmt or modified\_gmt and prepare any post or modified date for single post output. * [prepare\_excerpt\_response](wp_rest_revisions_controller/prepare_excerpt_response) β€” Checks the post excerpt and prepare it for single post output. * [prepare\_item\_for\_response](wp_rest_revisions_controller/prepare_item_for_response) β€” Prepares the revision for the REST response. * [prepare\_items\_query](wp_rest_revisions_controller/prepare_items_query) β€” Determines the allowed query\_vars for a get\_items() response and prepares them for WP\_Query. * [register\_routes](wp_rest_revisions_controller/register_routes) β€” Registers the routes for revisions based on post types supporting revisions. File: `wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php/) ``` class WP_REST_Revisions_Controller extends WP_REST_Controller { /** * Parent post type. * * @since 4.7.0 * @var string */ private $parent_post_type; /** * Parent controller. * * @since 4.7.0 * @var WP_REST_Controller */ private $parent_controller; /** * The base of the parent controller's route. * * @since 4.7.0 * @var string */ private $parent_base; /** * Constructor. * * @since 4.7.0 * * @param string $parent_post_type Post type of the parent. */ public function __construct( $parent_post_type ) { $this->parent_post_type = $parent_post_type; $this->rest_base = 'revisions'; $post_type_object = get_post_type_object( $parent_post_type ); $this->parent_base = ! empty( $post_type_object->rest_base ) ? $post_type_object->rest_base : $post_type_object->name; $this->namespace = ! empty( $post_type_object->rest_namespace ) ? $post_type_object->rest_namespace : 'wp/v2'; $this->parent_controller = $post_type_object->get_rest_controller(); if ( ! $this->parent_controller ) { $this->parent_controller = new WP_REST_Posts_Controller( $parent_post_type ); } } /** * Registers the routes for revisions based on post types supporting revisions. * * @since 4.7.0 * * @see register_rest_route() */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->parent_base . '/(?P<parent>[\d]+)/' . $this->rest_base, array( 'args' => array( 'parent' => array( 'description' => __( 'The ID for the parent of the revision.' ), '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(), ), '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 revision.' ), 'type' => 'integer', ), 'id' => array( 'description' => __( 'Unique identifier for the revision.' ), '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::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 revisions do not support trashing.' ), ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Get the parent post, if the ID is valid. * * @since 4.7.2 * * @param int $parent Supplied ID. * @return WP_Post|WP_Error Post object if ID is valid, WP_Error otherwise. */ protected function get_parent( $parent ) { $error = new WP_Error( 'rest_post_invalid_parent', __( 'Invalid post parent ID.' ), array( 'status' => 404 ) ); if ( (int) $parent <= 0 ) { return $error; } $parent = get_post( (int) $parent ); if ( empty( $parent ) || empty( $parent->ID ) || $this->parent_post_type !== $parent->post_type ) { return $error; } return $parent; } /** * Checks if a given request has access to get revisions. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { $parent = $this->get_parent( $request['parent'] ); 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 revisions of this post.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Get the revision, if the ID is valid. * * @since 4.7.2 * * @param int $id Supplied ID. * @return WP_Post|WP_Error Revision post object if ID is valid, WP_Error otherwise. */ protected function get_revision( $id ) { $error = new WP_Error( 'rest_post_invalid_id', __( 'Invalid revision ID.' ), array( 'status' => 404 ) ); if ( (int) $id <= 0 ) { return $error; } $revision = get_post( (int) $id ); if ( empty( $revision ) || empty( $revision->ID ) || 'revision' !== $revision->post_type ) { return $error; } return $revision; } /** * Gets a collection of revisions. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { $parent = $this->get_parent( $request['parent'] ); if ( is_wp_error( $parent ) ) { return $parent; } // Ensure a search string is set in case the orderby is set to 'relevance'. if ( ! empty( $request['orderby'] ) && 'relevance' === $request['orderby'] && empty( $request['search'] ) ) { return new WP_Error( 'rest_no_search_term_defined', __( 'You need to define a search term to order by relevance.' ), array( 'status' => 400 ) ); } // Ensure an include parameter is set in case the orderby is set to 'include'. if ( ! empty( $request['orderby'] ) && 'include' === $request['orderby'] && empty( $request['include'] ) ) { return new WP_Error( 'rest_orderby_include_missing_include', __( 'You need to define an include parameter to order by include.' ), array( 'status' => 400 ) ); } if ( wp_revisions_enabled( $parent ) ) { $registered = $this->get_collection_params(); $args = array( 'post_parent' => $parent->ID, 'post_type' => 'revision', 'post_status' => 'inherit', 'posts_per_page' => -1, 'orderby' => 'date ID', 'order' => 'DESC', 'suppress_filters' => true, ); $parameter_mappings = array( 'exclude' => 'post__not_in', 'include' => 'post__in', 'offset' => 'offset', 'order' => 'order', 'orderby' => 'orderby', 'page' => 'paged', 'per_page' => 'posts_per_page', 'search' => 's', ); foreach ( $parameter_mappings as $api_param => $wp_param ) { if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) { $args[ $wp_param ] = $request[ $api_param ]; } } // For backward-compatibility, 'date' needs to resolve to 'date ID'. if ( isset( $args['orderby'] ) && 'date' === $args['orderby'] ) { $args['orderby'] = 'date ID'; } /** This filter is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */ $args = apply_filters( 'rest_revision_query', $args, $request ); $query_args = $this->prepare_items_query( $args, $request ); $revisions_query = new WP_Query(); $revisions = $revisions_query->query( $query_args ); $offset = isset( $query_args['offset'] ) ? (int) $query_args['offset'] : 0; $page = (int) $query_args['paged']; $total_revisions = $revisions_query->found_posts; if ( $total_revisions < 1 ) { // Out-of-bounds, run the query again without LIMIT for total count. unset( $query_args['paged'], $query_args['offset'] ); $count_query = new WP_Query(); $count_query->query( $query_args ); $total_revisions = $count_query->found_posts; } if ( $revisions_query->query_vars['posts_per_page'] > 0 ) { $max_pages = ceil( $total_revisions / (int) $revisions_query->query_vars['posts_per_page'] ); } else { $max_pages = $total_revisions > 0 ? 1 : 0; } if ( $total_revisions > 0 ) { if ( $offset >= $total_revisions ) { return new WP_Error( 'rest_revision_invalid_offset_number', __( 'The offset number requested is larger than or equal to the number of available revisions.' ), array( 'status' => 400 ) ); } elseif ( ! $offset && $page > $max_pages ) { return new WP_Error( 'rest_revision_invalid_page_number', __( 'The page number requested is larger than the number of pages available.' ), array( 'status' => 400 ) ); } } } else { $revisions = array(); $total_revisions = 0; $max_pages = 0; $page = (int) $request['page']; } $response = array(); foreach ( $revisions as $revision ) { $data = $this->prepare_item_for_response( $revision, $request ); $response[] = $this->prepare_response_for_collection( $data ); } $response = rest_ensure_response( $response ); $response->header( 'X-WP-Total', (int) $total_revisions ); $response->header( 'X-WP-TotalPages', (int) $max_pages ); $request_params = $request->get_query_params(); $base_path = rest_url( sprintf( '%s/%s/%d/%s', $this->namespace, $this->parent_base, $request['parent'], $this->rest_base ) ); $base = add_query_arg( urlencode_deep( $request_params ), $base_path ); 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; } /** * Checks if a given request has access to get a specific revision. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise. */ public function get_item_permissions_check( $request ) { return $this->get_items_permissions_check( $request ); } /** * Retrieves one revision from the collection. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { $parent = $this->get_parent( $request['parent'] ); if ( is_wp_error( $parent ) ) { return $parent; } $revision = $this->get_revision( $request['id'] ); if ( is_wp_error( $revision ) ) { return $revision; } $response = $this->prepare_item_for_response( $revision, $request ); return rest_ensure_response( $response ); } /** * Checks if a given request has access to delete a revision. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise. */ public function delete_item_permissions_check( $request ) { $parent = $this->get_parent( $request['parent'] ); if ( is_wp_error( $parent ) ) { return $parent; } $parent_post_type = get_post_type_object( $parent->post_type ); if ( ! current_user_can( 'delete_post', $parent->ID ) ) { return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete revisions of this post.' ), array( 'status' => rest_authorization_required_code() ) ); } $revision = $this->get_revision( $request['id'] ); if ( is_wp_error( $revision ) ) { return $revision; } $response = $this->get_items_permissions_check( $request ); if ( ! $response || is_wp_error( $response ) ) { return $response; } if ( ! current_user_can( 'delete_post', $revision->ID ) ) { return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this revision.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Deletes a single revision. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function delete_item( $request ) { $revision = $this->get_revision( $request['id'] ); if ( is_wp_error( $revision ) ) { return $revision; } $force = isset( $request['force'] ) ? (bool) $request['force'] : false; // We don't support trashing for revisions. if ( ! $force ) { return new WP_Error( 'rest_trash_not_supported', /* translators: %s: force=true */ sprintf( __( "Revisions do not support trashing. Set '%s' to delete." ), 'force=true' ), array( 'status' => 501 ) ); } $previous = $this->prepare_item_for_response( $revision, $request ); $result = wp_delete_post( $request['id'], true ); /** * Fires after a revision is deleted via the REST API. * * @since 4.7.0 * * @param WP_Post|false|null $result The revision object (if it was deleted or moved to the Trash successfully) * or false or null (failure). If the revision was moved to the Trash, $result represents * its new state; if it was deleted, $result represents its state before deletion. * @param WP_REST_Request $request The request sent to the API. */ do_action( 'rest_delete_revision', $result, $request ); if ( ! $result ) { return new WP_Error( 'rest_cannot_delete', __( 'The post cannot be deleted.' ), array( 'status' => 500 ) ); } $response = new WP_REST_Response(); $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data(), ) ); return $response; } /** * Determines the allowed query_vars for a get_items() response and prepares * them for WP_Query. * * @since 5.0.0 * * @param array $prepared_args Optional. Prepared WP_Query arguments. Default empty array. * @param WP_REST_Request $request Optional. Full details about the request. * @return array Items query arguments. */ protected function prepare_items_query( $prepared_args = array(), $request = null ) { $query_args = array(); foreach ( $prepared_args as $key => $value ) { /** This filter is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */ $query_args[ $key ] = apply_filters( "rest_query_var-{$key}", $value ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores } // Map to proper WP_Query orderby param. if ( isset( $query_args['orderby'] ) && isset( $request['orderby'] ) ) { $orderby_mappings = array( 'id' => 'ID', 'include' => 'post__in', 'slug' => 'post_name', 'include_slugs' => 'post_name__in', ); if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) { $query_args['orderby'] = $orderby_mappings[ $request['orderby'] ]; } } return $query_args; } /** * Prepares the revision for the REST response. * * @since 4.7.0 * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Post $item Post revision object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $post = $item; $GLOBALS['post'] = $post; setup_postdata( $post ); $fields = $this->get_fields_for_response( $request ); $data = array(); if ( in_array( 'author', $fields, true ) ) { $data['author'] = (int) $post->post_author; } if ( in_array( 'date', $fields, true ) ) { $data['date'] = $this->prepare_date_response( $post->post_date_gmt, $post->post_date ); } if ( in_array( 'date_gmt', $fields, true ) ) { $data['date_gmt'] = $this->prepare_date_response( $post->post_date_gmt ); } if ( in_array( 'id', $fields, true ) ) { $data['id'] = $post->ID; } if ( in_array( 'modified', $fields, true ) ) { $data['modified'] = $this->prepare_date_response( $post->post_modified_gmt, $post->post_modified ); } if ( in_array( 'modified_gmt', $fields, true ) ) { $data['modified_gmt'] = $this->prepare_date_response( $post->post_modified_gmt ); } if ( in_array( 'parent', $fields, true ) ) { $data['parent'] = (int) $post->post_parent; } if ( in_array( 'slug', $fields, true ) ) { $data['slug'] = $post->post_name; } if ( in_array( 'guid', $fields, true ) ) { $data['guid'] = array( /** This filter is documented in wp-includes/post-template.php */ 'rendered' => apply_filters( 'get_the_guid', $post->guid, $post->ID ), 'raw' => $post->guid, ); } if ( in_array( 'title', $fields, true ) ) { $data['title'] = array( 'raw' => $post->post_title, 'rendered' => get_the_title( $post->ID ), ); } if ( in_array( 'content', $fields, true ) ) { $data['content'] = array( 'raw' => $post->post_content, /** This filter is documented in wp-includes/post-template.php */ 'rendered' => apply_filters( 'the_content', $post->post_content ), ); } if ( in_array( 'excerpt', $fields, true ) ) { $data['excerpt'] = array( 'raw' => $post->post_excerpt, 'rendered' => $this->prepare_excerpt_response( $post->post_excerpt, $post ), ); } $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 ( ! empty( $data['parent'] ) ) { $response->add_link( 'parent', rest_url( rest_get_route_for_post( $data['parent'] ) ) ); } /** * Filters a revision returned from the REST API. * * Allows modification of the revision right before it is returned. * * @since 4.7.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_revision', $response, $post, $request ); } /** * Checks the post_date_gmt or modified_gmt and prepare any post or * modified date for single post output. * * @since 4.7.0 * * @param string $date_gmt GMT publication time. * @param string|null $date Optional. Local publication time. Default null. * @return string|null ISO8601/RFC3339 formatted datetime, otherwise null. */ protected function prepare_date_response( $date_gmt, $date = null ) { if ( '0000-00-00 00:00:00' === $date_gmt ) { return null; } if ( isset( $date ) ) { return mysql_to_rfc3339( $date ); } return mysql_to_rfc3339( $date_gmt ); } /** * Retrieves the revision's schema, conforming to JSON Schema. * * @since 4.7.0 * * @return array Item schema data. */ 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->parent_post_type}-revision", 'type' => 'object', // Base properties for every Revision. 'properties' => array( 'author' => array( 'description' => __( 'The ID for the author of the revision.' ), 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), ), 'date' => array( 'description' => __( "The date the revision was published, in the site's timezone." ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'view', 'edit', 'embed' ), ), 'date_gmt' => array( 'description' => __( 'The date the revision was published, as GMT.' ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'view', 'edit' ), ), 'guid' => array( 'description' => __( 'GUID for the revision, as it exists in the database.' ), 'type' => 'string', 'context' => array( 'view', 'edit' ), ), 'id' => array( 'description' => __( 'Unique identifier for the revision.' ), 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), ), 'modified' => array( 'description' => __( "The date the revision was last modified, in the site's timezone." ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'view', 'edit' ), ), 'modified_gmt' => array( 'description' => __( 'The date the revision was last modified, as GMT.' ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'view', 'edit' ), ), 'parent' => array( 'description' => __( 'The ID for the parent of the revision.' ), 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), ), 'slug' => array( 'description' => __( 'An alphanumeric identifier for the revision unique to its type.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), ), ), ); $parent_schema = $this->parent_controller->get_item_schema(); if ( ! empty( $parent_schema['properties']['title'] ) ) { $schema['properties']['title'] = $parent_schema['properties']['title']; } if ( ! empty( $parent_schema['properties']['content'] ) ) { $schema['properties']['content'] = $parent_schema['properties']['content']; } if ( ! empty( $parent_schema['properties']['excerpt'] ) ) { $schema['properties']['excerpt'] = $parent_schema['properties']['excerpt']; } if ( ! empty( $parent_schema['properties']['guid'] ) ) { $schema['properties']['guid'] = $parent_schema['properties']['guid']; } $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the query params for collections. * * @since 4.7.0 * * @return array Collection parameters. */ public function get_collection_params() { $query_params = parent::get_collection_params(); $query_params['context']['default'] = 'view'; unset( $query_params['per_page']['default'] ); $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(), ); $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' => 'desc', 'enum' => array( 'asc', 'desc' ), ); $query_params['orderby'] = array( 'description' => __( 'Sort collection by object attribute.' ), 'type' => 'string', 'default' => 'date', 'enum' => array( 'date', 'id', 'include', 'relevance', 'slug', 'include_slugs', 'title', ), ); return $query_params; } /** * Checks the post excerpt and prepare it for single post output. * * @since 4.7.0 * * @param string $excerpt The post excerpt. * @param WP_Post $post Post revision object. * @return string Prepared excerpt or empty string. */ protected function prepare_excerpt_response( $excerpt, $post ) { /** This filter is documented in wp-includes/post-template.php */ $excerpt = apply_filters( 'the_excerpt', $excerpt, $post ); if ( empty( $excerpt ) ) { return ''; } return $excerpt; } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Used By | Description | | --- | --- | | [WP\_REST\_Autosaves\_Controller](wp_rest_autosaves_controller) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Core class used to access autosaves via the REST API. | | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
programming_docs
wordpress class WP_Sidebar_Block_Editor_Control {} class WP\_Sidebar\_Block\_Editor\_Control {} ============================================ Core class used to implement the widgets block editor control in the customizer. * [WP\_Customize\_Control](wp_customize_control) * [render\_content](wp_sidebar_block_editor_control/render_content) β€” Render the widgets block editor container. File: `wp-includes/customize/class-wp-sidebar-block-editor-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-sidebar-block-editor-control.php/) ``` class WP_Sidebar_Block_Editor_Control extends WP_Customize_Control { /** * The control type. * * @since 5.8.0 * * @var string */ public $type = 'sidebar_block_editor'; /** * Render the widgets block editor container. * * @since 5.8.0 */ public function render_content() { // Render an empty control. The JavaScript in // @wordpress/customize-widgets will do the rest. } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Control](wp_customize_control) wp-includes/class-wp-customize-control.php | Customize Control class. | | Version | Description | | --- | --- | | [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. | wordpress class WP_Widget_Media_Audio {} class WP\_Widget\_Media\_Audio {} ================================= Core class that implements an audio widget. * [WP\_Widget\_Media](wp_widget_media) * [WP\_Widget](wp_widget) * [\_\_construct](wp_widget_media_audio/__construct) β€” Constructor. * [enqueue\_admin\_scripts](wp_widget_media_audio/enqueue_admin_scripts) β€” Loads the required media files for the media manager and scripts for media widgets. * [enqueue\_preview\_scripts](wp_widget_media_audio/enqueue_preview_scripts) β€” Enqueue preview scripts. * [get\_instance\_schema](wp_widget_media_audio/get_instance_schema) β€” Get schema for properties of a widget instance (item). * [render\_control\_template\_scripts](wp_widget_media_audio/render_control_template_scripts) β€” Render form template scripts. * [render\_media](wp_widget_media_audio/render_media) β€” Render the media on the frontend. File: `wp-includes/widgets/class-wp-widget-media-audio.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-audio.php/) ``` class WP_Widget_Media_Audio extends WP_Widget_Media { /** * Constructor. * * @since 4.8.0 */ public function __construct() { parent::__construct( 'media_audio', __( 'Audio' ), array( 'description' => __( 'Displays an audio player.' ), 'mime_type' => 'audio', ) ); $this->l10n = array_merge( $this->l10n, array( 'no_media_selected' => __( 'No audio selected' ), 'add_media' => _x( 'Add Audio', 'label for button in the audio widget' ), 'replace_media' => _x( 'Replace Audio', 'label for button in the audio widget; should preferably not be longer than ~13 characters long' ), 'edit_media' => _x( 'Edit Audio', 'label for button in the audio widget; should preferably not be longer than ~13 characters long' ), 'missing_attachment' => sprintf( /* translators: %s: URL to media library. */ __( 'That audio 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( 'Audio Widget (%d)', 'Audio Widget (%d)' ), 'media_library_state_single' => __( 'Audio Widget' ), 'unsupported_file_type' => __( 'Looks like this is not the correct kind of file. Please link to an audio file instead.' ), ) ); } /** * Get schema for properties of a widget instance (item). * * @since 4.8.0 * * @see WP_REST_Controller::get_item_schema() * @see WP_REST_Controller::get_additional_fields() * @link https://core.trac.wordpress.org/ticket/35574 * * @return array Schema for properties. */ public function get_instance_schema() { $schema = array( 'preload' => array( 'type' => 'string', 'enum' => array( 'none', 'auto', 'metadata' ), 'default' => 'none', 'description' => __( 'Preload' ), ), 'loop' => array( 'type' => 'boolean', 'default' => false, 'description' => __( 'Loop' ), ), ); foreach ( wp_get_audio_extensions() as $audio_extension ) { $schema[ $audio_extension ] = array( 'type' => 'string', 'default' => '', 'format' => 'uri', /* translators: %s: Audio extension. */ 'description' => sprintf( __( 'URL to the %s audio source file' ), $audio_extension ), ); } return array_merge( $schema, parent::get_instance_schema() ); } /** * Render the media on the frontend. * * @since 4.8.0 * * @param array $instance Widget instance props. */ public function render_media( $instance ) { $instance = array_merge( wp_list_pluck( $this->get_instance_schema(), 'default' ), $instance ); $attachment = null; if ( $this->is_attachment_with_mime_type( $instance['attachment_id'], $this->widget_options['mime_type'] ) ) { $attachment = get_post( $instance['attachment_id'] ); } if ( $attachment ) { $src = wp_get_attachment_url( $attachment->ID ); } else { $src = $instance['url']; } echo wp_audio_shortcode( array_merge( $instance, compact( 'src' ) ) ); } /** * Enqueue preview scripts. * * These scripts normally are enqueued just-in-time when an audio shortcode is used. * In the customizer, however, widgets can be dynamically added and rendered via * selective refresh, and so it is important to unconditionally enqueue them in * case a widget does get added. * * @since 4.8.0 */ public function enqueue_preview_scripts() { /** This filter is documented in wp-includes/media.php */ if ( 'mediaelement' === apply_filters( 'wp_audio_shortcode_library', 'mediaelement' ) ) { wp_enqueue_style( 'wp-mediaelement' ); wp_enqueue_script( 'wp-mediaelement' ); } } /** * Loads the required media files for the media manager and scripts for media widgets. * * @since 4.8.0 */ public function enqueue_admin_scripts() { parent::enqueue_admin_scripts(); wp_enqueue_style( 'wp-mediaelement' ); wp_enqueue_script( 'wp-mediaelement' ); $handle = 'media-audio-widget'; wp_enqueue_script( $handle ); $exported_schema = array(); foreach ( $this->get_instance_schema() as $field => $field_schema ) { $exported_schema[ $field ] = wp_array_slice_assoc( $field_schema, array( 'type', 'default', 'enum', 'minimum', 'format', 'media_prop', 'should_preview_update' ) ); } wp_add_inline_script( $handle, sprintf( 'wp.mediaWidgets.modelConstructors[ %s ].prototype.schema = %s;', wp_json_encode( $this->id_base ), wp_json_encode( $exported_schema ) ) ); wp_add_inline_script( $handle, sprintf( ' wp.mediaWidgets.controlConstructors[ %1$s ].prototype.mime_type = %2$s; wp.mediaWidgets.controlConstructors[ %1$s ].prototype.l10n = _.extend( {}, wp.mediaWidgets.controlConstructors[ %1$s ].prototype.l10n, %3$s ); ', wp_json_encode( $this->id_base ), wp_json_encode( $this->widget_options['mime_type'] ), wp_json_encode( $this->l10n ) ) ); } /** * Render form template scripts. * * @since 4.8.0 */ public function render_control_template_scripts() { parent::render_control_template_scripts() ?> <script type="text/html" id="tmpl-wp-media-widget-audio-preview"> <# if ( data.error && 'missing_attachment' === data.error ) { #> <div class="notice notice-error notice-alt notice-missing-attachment"> <p><?php echo $this->l10n['missing_attachment']; ?></p> </div> <# } else if ( data.error ) { #> <div class="notice notice-error notice-alt"> <p><?php _e( 'Unable to preview media due to an unknown error.' ); ?></p> </div> <# } else if ( data.model && data.model.src ) { #> <?php wp_underscore_audio_template(); ?> <# } #> </script> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Widget\_Media](wp_widget_media) wp-includes/widgets/class-wp-widget-media.php | Core class that implements a media widget. | | Version | Description | | --- | --- | | [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. | wordpress class WP_Widget_Area_Customize_Control {} class WP\_Widget\_Area\_Customize\_Control {} ============================================= Widget Area Customize Control class. * [WP\_Customize\_Control](wp_customize_control) * [render\_content](wp_widget_area_customize_control/render_content) β€” Renders the control's content. * [to\_json](wp_widget_area_customize_control/to_json) β€” Refreshes the parameters passed to the JavaScript via JSON. File: `wp-includes/customize/class-wp-widget-area-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-widget-area-customize-control.php/) ``` class WP_Widget_Area_Customize_Control extends WP_Customize_Control { /** * Customize control type. * * @since 3.9.0 * @var string */ public $type = 'sidebar_widgets'; /** * Sidebar ID. * * @since 3.9.0 * @var int|string */ public $sidebar_id; /** * Refreshes the parameters passed to the JavaScript via JSON. * * @since 3.9.0 */ public function to_json() { parent::to_json(); $exported_properties = array( 'sidebar_id' ); foreach ( $exported_properties as $key ) { $this->json[ $key ] = $this->$key; } } /** * Renders the control's content. * * @since 3.9.0 */ public function render_content() { $id = 'reorder-widgets-desc-' . str_replace( array( '[', ']' ), array( '-', '' ), $this->id ); ?> <button type="button" class="button add-new-widget" aria-expanded="false" aria-controls="available-widgets"> <?php _e( 'Add a Widget' ); ?> </button> <button type="button" class="button-link reorder-toggle" aria-label="<?php esc_attr_e( 'Reorder widgets' ); ?>" aria-describedby="<?php echo esc_attr( $id ); ?>"> <span class="reorder"><?php _e( 'Reorder' ); ?></span> <span class="reorder-done"><?php _e( 'Done' ); ?></span> </button> <p class="screen-reader-text" id="<?php echo esc_attr( $id ); ?>"><?php _e( 'When in reorder mode, additional controls to reorder widgets will be available in the widgets list above.' ); ?></p> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Control](wp_customize_control) wp-includes/class-wp-customize-control.php | Customize Control class. | | Version | Description | | --- | --- | | [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. | wordpress class WP_Theme_Install_List_Table {} class WP\_Theme\_Install\_List\_Table {} ======================================== Core class used to implement displaying themes to install in a list table. * [WP\_Themes\_List\_Table](wp_themes_list_table) * [\_get\_theme\_status](wp_theme_install_list_table/_get_theme_status) β€” Check to see if the theme is already installed. * [\_js\_vars](wp_theme_install_list_table/_js_vars) β€” Send required variables to JavaScript land * [ajax\_user\_can](wp_theme_install_list_table/ajax_user_can) * [display](wp_theme_install_list_table/display) β€” Displays the theme install table. * [display\_rows](wp_theme_install_list_table/display_rows) * [get\_views](wp_theme_install_list_table/get_views) * [install\_theme\_info](wp_theme_install_list_table/install_theme_info) β€” Prints the info for a theme (to be used in the theme installer modal). * [no\_items](wp_theme_install_list_table/no_items) * [prepare\_items](wp_theme_install_list_table/prepare_items) * [single\_row](wp_theme_install_list_table/single_row) β€” Prints a theme from the WordPress.org API. * [theme\_installer](wp_theme_install_list_table/theme_installer) β€” Prints the wrapper for the theme installer. * [theme\_installer\_single](wp_theme_install_list_table/theme_installer_single) β€” Prints the wrapper for the theme installer with a provided theme's data. File: `wp-admin/includes/class-wp-theme-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-theme-install-list-table.php/) ``` class WP_Theme_Install_List_Table extends WP_Themes_List_Table { public $features = array(); /** * @return bool */ public function ajax_user_can() { return current_user_can( 'install_themes' ); } /** * @global array $tabs * @global string $tab * @global int $paged * @global string $type * @global array $theme_field_defaults */ public function prepare_items() { require ABSPATH . 'wp-admin/includes/theme-install.php'; global $tabs, $tab, $paged, $type, $theme_field_defaults; wp_reset_vars( array( 'tab' ) ); $search_terms = array(); $search_string = ''; if ( ! empty( $_REQUEST['s'] ) ) { $search_string = strtolower( wp_unslash( $_REQUEST['s'] ) ); $search_terms = array_unique( array_filter( array_map( 'trim', explode( ',', $search_string ) ) ) ); } if ( ! empty( $_REQUEST['features'] ) ) { $this->features = $_REQUEST['features']; } $paged = $this->get_pagenum(); $per_page = 36; // These are the tabs which are shown on the page, $tabs = array(); $tabs['dashboard'] = __( 'Search' ); if ( 'search' === $tab ) { $tabs['search'] = __( 'Search Results' ); } $tabs['upload'] = __( 'Upload' ); $tabs['featured'] = _x( 'Featured', 'themes' ); //$tabs['popular'] = _x( 'Popular', 'themes' ); $tabs['new'] = _x( 'Latest', 'themes' ); $tabs['updated'] = _x( 'Recently Updated', 'themes' ); $nonmenu_tabs = array( 'theme-information' ); // Valid actions to perform which do not have a Menu item. /** This filter is documented in wp-admin/theme-install.php */ $tabs = apply_filters( 'install_themes_tabs', $tabs ); /** * Filters tabs not associated with a menu item on the Install Themes screen. * * @since 2.8.0 * * @param string[] $nonmenu_tabs The tabs that don't have a menu item on * the Install Themes screen. */ $nonmenu_tabs = apply_filters( 'install_themes_nonmenu_tabs', $nonmenu_tabs ); // If a non-valid menu tab has been selected, And it's not a non-menu action. if ( empty( $tab ) || ( ! isset( $tabs[ $tab ] ) && ! in_array( $tab, (array) $nonmenu_tabs, true ) ) ) { $tab = key( $tabs ); } $args = array( 'page' => $paged, 'per_page' => $per_page, 'fields' => $theme_field_defaults, ); switch ( $tab ) { case 'search': $type = isset( $_REQUEST['type'] ) ? wp_unslash( $_REQUEST['type'] ) : 'term'; switch ( $type ) { case 'tag': $args['tag'] = array_map( 'sanitize_key', $search_terms ); break; case 'term': $args['search'] = $search_string; break; case 'author': $args['author'] = $search_string; break; } if ( ! empty( $this->features ) ) { $args['tag'] = $this->features; $_REQUEST['s'] = implode( ',', $this->features ); $_REQUEST['type'] = 'tag'; } add_action( 'install_themes_table_header', 'install_theme_search_form', 10, 0 ); break; case 'featured': // case 'popular': case 'new': case 'updated': $args['browse'] = $tab; break; default: $args = false; break; } /** * Filters API request arguments for each Install Themes screen tab. * * The dynamic portion of the hook name, `$tab`, refers to the theme install * tab. * * Possible hook names include: * * - `install_themes_table_api_args_dashboard` * - `install_themes_table_api_args_featured` * - `install_themes_table_api_args_new` * - `install_themes_table_api_args_search` * - `install_themes_table_api_args_updated` * - `install_themes_table_api_args_upload` * * @since 3.7.0 * * @param array|false $args Theme install API arguments. */ $args = apply_filters( "install_themes_table_api_args_{$tab}", $args ); if ( ! $args ) { return; } $api = themes_api( 'query_themes', $args ); if ( is_wp_error( $api ) ) { wp_die( '<p>' . $api->get_error_message() . '</p> <p><a href="#" onclick="document.location.reload(); return false;">' . __( 'Try Again' ) . '</a></p>' ); } $this->items = $api->themes; $this->set_pagination_args( array( 'total_items' => $api->info['results'], 'per_page' => $args['per_page'], 'infinite_scroll' => true, ) ); } /** */ public function no_items() { _e( 'No themes match your request.' ); } /** * @global array $tabs * @global string $tab * @return array */ protected function get_views() { global $tabs, $tab; $display_tabs = array(); foreach ( (array) $tabs as $action => $text ) { $display_tabs[ 'theme-install-' . $action ] = array( 'url' => self_admin_url( 'theme-install.php?tab=' . $action ), 'label' => $text, 'current' => $action === $tab, ); } return $this->get_views_links( $display_tabs ); } /** * Displays the theme install table. * * Overrides the parent display() method to provide a different container. * * @since 3.1.0 */ public function display() { wp_nonce_field( 'fetch-list-' . get_class( $this ), '_ajax_fetch_list_nonce' ); ?> <div class="tablenav top themes"> <div class="alignleft actions"> <?php /** * Fires in the Install Themes list table header. * * @since 2.8.0 */ do_action( 'install_themes_table_header' ); ?> </div> <?php $this->pagination( 'top' ); ?> <br class="clear" /> </div> <div id="availablethemes"> <?php $this->display_rows_or_placeholder(); ?> </div> <?php $this->tablenav( 'bottom' ); } /** */ public function display_rows() { $themes = $this->items; foreach ( $themes as $theme ) { ?> <div class="available-theme installable-theme"> <?php $this->single_row( $theme ); ?> </div> <?php } // End foreach $theme_names. $this->theme_installer(); } /** * Prints a theme from the WordPress.org API. * * @since 3.1.0 * * @global array $themes_allowedtags * * @param stdClass $theme { * An object that contains theme data returned by the WordPress.org API. * * @type string $name Theme name, e.g. 'Twenty Twenty-One'. * @type string $slug Theme slug, e.g. 'twentytwentyone'. * @type string $version Theme version, e.g. '1.1'. * @type string $author Theme author username, e.g. 'melchoyce'. * @type string $preview_url Preview URL, e.g. 'https://2021.wordpress.net/'. * @type string $screenshot_url Screenshot URL, e.g. 'https://wordpress.org/themes/twentytwentyone/'. * @type float $rating Rating score. * @type int $num_ratings The number of ratings. * @type string $homepage Theme homepage, e.g. 'https://wordpress.org/themes/twentytwentyone/'. * @type string $description Theme description. * @type string $download_link Theme ZIP download URL. * } */ public function single_row( $theme ) { global $themes_allowedtags; if ( empty( $theme ) ) { return; } $name = wp_kses( $theme->name, $themes_allowedtags ); $author = wp_kses( $theme->author, $themes_allowedtags ); /* translators: %s: Theme name. */ $preview_title = sprintf( __( 'Preview &#8220;%s&#8221;' ), $name ); $preview_url = add_query_arg( array( 'tab' => 'theme-information', 'theme' => $theme->slug, ), self_admin_url( 'theme-install.php' ) ); $actions = array(); $install_url = add_query_arg( array( 'action' => 'install-theme', 'theme' => $theme->slug, ), self_admin_url( 'update.php' ) ); $update_url = add_query_arg( array( 'action' => 'upgrade-theme', 'theme' => $theme->slug, ), self_admin_url( 'update.php' ) ); $status = $this->_get_theme_status( $theme ); switch ( $status ) { case 'update_available': $actions[] = sprintf( '<a class="install-now" href="%s" title="%s">%s</a>', esc_url( wp_nonce_url( $update_url, 'upgrade-theme_' . $theme->slug ) ), /* translators: %s: Theme version. */ esc_attr( sprintf( __( 'Update to version %s' ), $theme->version ) ), __( 'Update' ) ); break; case 'newer_installed': case 'latest_installed': $actions[] = sprintf( '<span class="install-now" title="%s">%s</span>', esc_attr__( 'This theme is already installed and is up to date' ), _x( 'Installed', 'theme' ) ); break; case 'install': default: $actions[] = sprintf( '<a class="install-now" href="%s" title="%s">%s</a>', esc_url( wp_nonce_url( $install_url, 'install-theme_' . $theme->slug ) ), /* translators: %s: Theme name. */ esc_attr( sprintf( _x( 'Install %s', 'theme' ), $name ) ), __( 'Install Now' ) ); break; } $actions[] = sprintf( '<a class="install-theme-preview" href="%s" title="%s">%s</a>', esc_url( $preview_url ), /* translators: %s: Theme name. */ esc_attr( sprintf( __( 'Preview %s' ), $name ) ), __( 'Preview' ) ); /** * Filters the install action links for a theme in the Install Themes list table. * * @since 3.4.0 * * @param string[] $actions An array of theme action links. Defaults are * links to Install Now, Preview, and Details. * @param stdClass $theme An object that contains theme data returned by the * WordPress.org API. */ $actions = apply_filters( 'theme_install_actions', $actions, $theme ); ?> <a class="screenshot install-theme-preview" href="<?php echo esc_url( $preview_url ); ?>" title="<?php echo esc_attr( $preview_title ); ?>"> <img src="<?php echo esc_url( $theme->screenshot_url . '?ver=' . $theme->version ); ?>" width="150" alt="" /> </a> <h3><?php echo $name; ?></h3> <div class="theme-author"> <?php /* translators: %s: Theme author. */ printf( __( 'By %s' ), $author ); ?> </div> <div class="action-links"> <ul> <?php foreach ( $actions as $action ) : ?> <li><?php echo $action; ?></li> <?php endforeach; ?> <li class="hide-if-no-js"><a href="#" class="theme-detail"><?php _e( 'Details' ); ?></a></li> </ul> </div> <?php $this->install_theme_info( $theme ); } /** * Prints the wrapper for the theme installer. */ public function theme_installer() { ?> <div id="theme-installer" class="wp-full-overlay expanded"> <div class="wp-full-overlay-sidebar"> <div class="wp-full-overlay-header"> <a href="#" class="close-full-overlay button"><?php _e( 'Close' ); ?></a> <span class="theme-install"></span> </div> <div class="wp-full-overlay-sidebar-content"> <div class="install-theme-info"></div> </div> <div class="wp-full-overlay-footer"> <button type="button" class="collapse-sidebar button" aria-expanded="true" aria-label="<?php esc_attr_e( 'Collapse Sidebar' ); ?>"> <span class="collapse-sidebar-arrow"></span> <span class="collapse-sidebar-label"><?php _e( 'Collapse' ); ?></span> </button> </div> </div> <div class="wp-full-overlay-main"></div> </div> <?php } /** * Prints the wrapper for the theme installer with a provided theme's data. * Used to make the theme installer work for no-js. * * @param stdClass $theme A WordPress.org Theme API object. */ public function theme_installer_single( $theme ) { ?> <div id="theme-installer" class="wp-full-overlay single-theme"> <div class="wp-full-overlay-sidebar"> <?php $this->install_theme_info( $theme ); ?> </div> <div class="wp-full-overlay-main"> <iframe src="<?php echo esc_url( $theme->preview_url ); ?>"></iframe> </div> </div> <?php } /** * Prints the info for a theme (to be used in the theme installer modal). * * @global array $themes_allowedtags * * @param stdClass $theme A WordPress.org Theme API object. */ public function install_theme_info( $theme ) { global $themes_allowedtags; if ( empty( $theme ) ) { return; } $name = wp_kses( $theme->name, $themes_allowedtags ); $author = wp_kses( $theme->author, $themes_allowedtags ); $install_url = add_query_arg( array( 'action' => 'install-theme', 'theme' => $theme->slug, ), self_admin_url( 'update.php' ) ); $update_url = add_query_arg( array( 'action' => 'upgrade-theme', 'theme' => $theme->slug, ), self_admin_url( 'update.php' ) ); $status = $this->_get_theme_status( $theme ); ?> <div class="install-theme-info"> <?php switch ( $status ) { case 'update_available': printf( '<a class="theme-install button button-primary" href="%s" title="%s">%s</a>', esc_url( wp_nonce_url( $update_url, 'upgrade-theme_' . $theme->slug ) ), /* translators: %s: Theme version. */ esc_attr( sprintf( __( 'Update to version %s' ), $theme->version ) ), __( 'Update' ) ); break; case 'newer_installed': case 'latest_installed': printf( '<span class="theme-install" title="%s">%s</span>', esc_attr__( 'This theme is already installed and is up to date' ), _x( 'Installed', 'theme' ) ); break; case 'install': default: printf( '<a class="theme-install button button-primary" href="%s">%s</a>', esc_url( wp_nonce_url( $install_url, 'install-theme_' . $theme->slug ) ), __( 'Install' ) ); break; } ?> <h3 class="theme-name"><?php echo $name; ?></h3> <span class="theme-by"> <?php /* translators: %s: Theme author. */ printf( __( 'By %s' ), $author ); ?> </span> <?php if ( isset( $theme->screenshot_url ) ) : ?> <img class="theme-screenshot" src="<?php echo esc_url( $theme->screenshot_url . '?ver=' . $theme->version ); ?>" alt="" /> <?php endif; ?> <div class="theme-details"> <?php wp_star_rating( array( 'rating' => $theme->rating, 'type' => 'percent', 'number' => $theme->num_ratings, ) ); ?> <div class="theme-version"> <strong><?php _e( 'Version:' ); ?> </strong> <?php echo wp_kses( $theme->version, $themes_allowedtags ); ?> </div> <div class="theme-description"> <?php echo wp_kses( $theme->description, $themes_allowedtags ); ?> </div> </div> <input class="theme-preview-url" type="hidden" value="<?php echo esc_url( $theme->preview_url ); ?>" /> </div> <?php } /** * Send required variables to JavaScript land * * @since 3.4.0 * * @global string $tab Current tab within Themes->Install screen * @global string $type Type of search. * * @param array $extra_args Unused. */ public function _js_vars( $extra_args = array() ) { global $tab, $type; parent::_js_vars( compact( 'tab', 'type' ) ); } /** * Check to see if the theme is already installed. * * @since 3.4.0 * * @param stdClass $theme A WordPress.org Theme API object. * @return string Theme status. */ private function _get_theme_status( $theme ) { $status = 'install'; $installed_theme = wp_get_theme( $theme->slug ); if ( $installed_theme->exists() ) { if ( version_compare( $installed_theme->get( 'Version' ), $theme->version, '=' ) ) { $status = 'latest_installed'; } elseif ( version_compare( $installed_theme->get( 'Version' ), $theme->version, '>' ) ) { $status = 'newer_installed'; } else { $status = 'update_available'; } } return $status; } } ``` | Uses | Description | | --- | --- | | [WP\_Themes\_List\_Table](wp_themes_list_table) wp-admin/includes/class-wp-themes-list-table.php | Core class used to implement displaying installed themes in a list table. | | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Block_Types_Controller {} class WP\_REST\_Block\_Types\_Controller {} =========================================== Core class used to access block types via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_block_types_controller/__construct) β€” Constructor. * [check\_read\_permission](wp_rest_block_types_controller/check_read_permission) β€” Checks whether a given block type should be visible. * [get\_block](wp_rest_block_types_controller/get_block) β€” Get the block, if the name is valid. * [get\_collection\_params](wp_rest_block_types_controller/get_collection_params) β€” Retrieves the query params for collections. * [get\_item](wp_rest_block_types_controller/get_item) β€” Retrieves a specific block type. * [get\_item\_permissions\_check](wp_rest_block_types_controller/get_item_permissions_check) β€” Checks if a given request has access to read a block type. * [get\_item\_schema](wp_rest_block_types_controller/get_item_schema) β€” Retrieves the block type' schema, conforming to JSON Schema. * [get\_items](wp_rest_block_types_controller/get_items) β€” Retrieves all post block types, depending on user context. * [get\_items\_permissions\_check](wp_rest_block_types_controller/get_items_permissions_check) β€” Checks whether a given request has permission to read post block types. * [prepare\_item\_for\_response](wp_rest_block_types_controller/prepare_item_for_response) β€” Prepares a block type object for serialization. * [prepare\_links](wp_rest_block_types_controller/prepare_links) β€” Prepares links for the request. * [register\_routes](wp_rest_block_types_controller/register_routes) β€” Registers the routes for block types. File: `wp-includes/rest-api/endpoints/class-wp-rest-block-types-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-types-controller.php/) ``` class WP_REST_Block_Types_Controller extends WP_REST_Controller { /** * Instance of WP_Block_Type_Registry. * * @since 5.5.0 * @var WP_Block_Type_Registry */ protected $block_registry; /** * Instance of WP_Block_Styles_Registry. * * @since 5.5.0 * @var WP_Block_Styles_Registry */ protected $style_registry; /** * Constructor. * * @since 5.5.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'block-types'; $this->block_registry = WP_Block_Type_Registry::get_instance(); $this->style_registry = WP_Block_Styles_Registry::get_instance(); } /** * Registers the routes for block types. * * @since 5.5.0 * * @see register_rest_route() */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => $this->get_collection_params(), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<namespace>[a-zA-Z0-9_-]+)', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => $this->get_collection_params(), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<namespace>[a-zA-Z0-9_-]+)/(?P<name>[a-zA-Z0-9_-]+)', array( 'args' => array( 'name' => array( 'description' => __( 'Block name.' ), 'type' => 'string', ), 'namespace' => array( 'description' => __( 'Block namespace.' ), 'type' => 'string', ), ), array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'permission_callback' => array( $this, 'get_item_permissions_check' ), 'args' => array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks whether a given request has permission to read post block types. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { return $this->check_read_permission(); } /** * Retrieves all post block types, depending on user context. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { $data = array(); $block_types = $this->block_registry->get_all_registered(); // Retrieve the list of registered collection query parameters. $registered = $this->get_collection_params(); $namespace = ''; if ( isset( $registered['namespace'] ) && ! empty( $request['namespace'] ) ) { $namespace = $request['namespace']; } foreach ( $block_types as $slug => $obj ) { if ( $namespace ) { list ( $block_namespace ) = explode( '/', $obj->name ); if ( $namespace !== $block_namespace ) { continue; } } $block_type = $this->prepare_item_for_response( $obj, $request ); $data[] = $this->prepare_response_for_collection( $block_type ); } return rest_ensure_response( $data ); } /** * Checks if a given request has access to read a block type. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise. */ public function get_item_permissions_check( $request ) { $check = $this->check_read_permission(); if ( is_wp_error( $check ) ) { return $check; } $block_name = sprintf( '%s/%s', $request['namespace'], $request['name'] ); $block_type = $this->get_block( $block_name ); if ( is_wp_error( $block_type ) ) { return $block_type; } return true; } /** * Checks whether a given block type should be visible. * * @since 5.5.0 * * @return true|WP_Error True if the block type is visible, WP_Error otherwise. */ protected function check_read_permission() { 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_block_type_cannot_view', __( 'Sorry, you are not allowed to manage block types.' ), array( 'status' => rest_authorization_required_code() ) ); } /** * Get the block, if the name is valid. * * @since 5.5.0 * * @param string $name Block name. * @return WP_Block_Type|WP_Error Block type object if name is valid, WP_Error otherwise. */ protected function get_block( $name ) { $block_type = $this->block_registry->get_registered( $name ); if ( empty( $block_type ) ) { return new WP_Error( 'rest_block_type_invalid', __( 'Invalid block type.' ), array( 'status' => 404 ) ); } return $block_type; } /** * Retrieves a specific block type. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { $block_name = sprintf( '%s/%s', $request['namespace'], $request['name'] ); $block_type = $this->get_block( $block_name ); if ( is_wp_error( $block_type ) ) { return $block_type; } $data = $this->prepare_item_for_response( $block_type, $request ); return rest_ensure_response( $data ); } /** * Prepares a block type object for serialization. * * @since 5.5.0 * @since 5.9.0 Renamed `$block_type` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Block_Type $item Block type data. * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response Block type data. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $block_type = $item; $fields = $this->get_fields_for_response( $request ); $data = array(); if ( rest_is_field_included( 'attributes', $fields ) ) { $data['attributes'] = $block_type->get_attributes(); } if ( rest_is_field_included( 'is_dynamic', $fields ) ) { $data['is_dynamic'] = $block_type->is_dynamic(); } $schema = $this->get_item_schema(); // Fields deprecated in WordPress 6.1, but left in the schema for backwards compatibility. $deprecated_fields = array( 'editor_script', 'script', 'view_script', 'editor_style', 'style', ); $extra_fields = array_merge( array( 'api_version', 'name', 'title', 'description', 'icon', 'category', 'keywords', 'parent', 'ancestor', 'provides_context', 'uses_context', 'supports', 'styles', 'textdomain', 'example', 'editor_script_handles', 'script_handles', 'view_script_handles', 'editor_style_handles', 'style_handles', 'variations', ), $deprecated_fields ); foreach ( $extra_fields as $extra_field ) { if ( rest_is_field_included( $extra_field, $fields ) ) { if ( isset( $block_type->$extra_field ) ) { $field = $block_type->$extra_field; if ( in_array( $extra_field, $deprecated_fields, true ) && is_array( $field ) ) { // Since the schema only allows strings or null (but no arrays), we return the first array item. $field = ! empty( $field ) ? array_shift( $field ) : ''; } } elseif ( array_key_exists( 'default', $schema['properties'][ $extra_field ] ) ) { $field = $schema['properties'][ $extra_field ]['default']; } else { $field = ''; } $data[ $extra_field ] = rest_sanitize_value_from_schema( $field, $schema['properties'][ $extra_field ] ); } } if ( rest_is_field_included( 'styles', $fields ) ) { $styles = $this->style_registry->get_registered_styles_for_block( $block_type->name ); $styles = array_values( $styles ); $data['styles'] = wp_parse_args( $styles, $data['styles'] ); $data['styles'] = array_filter( $data['styles'] ); } $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( $block_type ) ); } /** * Filters a block type returned from the REST API. * * Allows modification of the block type data right before it is returned. * * @since 5.5.0 * * @param WP_REST_Response $response The response object. * @param WP_Block_Type $block_type The original block type object. * @param WP_REST_Request $request Request used to generate the response. */ return apply_filters( 'rest_prepare_block_type', $response, $block_type, $request ); } /** * Prepares links for the request. * * @since 5.5.0 * * @param WP_Block_Type $block_type Block type data. * @return array Links for the given block type. */ protected function prepare_links( $block_type ) { list( $namespace ) = explode( '/', $block_type->name ); $links = array( 'collection' => array( 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ), ), 'self' => array( 'href' => rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $block_type->name ) ), ), 'up' => array( 'href' => rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $namespace ) ), ), ); if ( $block_type->is_dynamic() ) { $links['https://api.w.org/render-block'] = array( 'href' => add_query_arg( 'context', 'edit', rest_url( sprintf( '%s/%s/%s', 'wp/v2', 'block-renderer', $block_type->name ) ) ), ); } return $links; } /** * Retrieves the block type' schema, conforming to JSON Schema. * * @since 5.5.0 * * @return array Item schema data. */ public function get_item_schema() { if ( $this->schema ) { return $this->add_additional_fields_schema( $this->schema ); } // rest_validate_value_from_schema doesn't understand $refs, pull out reused definitions for readability. $inner_blocks_definition = array( 'description' => __( 'The list of inner blocks used in the example.' ), 'type' => 'array', 'items' => array( 'type' => 'object', 'properties' => array( 'name' => array( 'description' => __( 'The name of the inner block.' ), 'type' => 'string', ), 'attributes' => array( 'description' => __( 'The attributes of the inner block.' ), 'type' => 'object', ), 'innerBlocks' => array( 'description' => __( "A list of the inner block's own inner blocks. This is a recursive definition following the parent innerBlocks schema." ), 'type' => 'array', ), ), ), ); $example_definition = array( 'description' => __( 'Block example.' ), 'type' => array( 'object', 'null' ), 'default' => null, 'properties' => array( 'attributes' => array( 'description' => __( 'The attributes used in the example.' ), 'type' => 'object', ), 'innerBlocks' => $inner_blocks_definition, ), 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ); $keywords_definition = array( 'description' => __( 'Block keywords.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), 'default' => array(), 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ); $icon_definition = array( 'description' => __( 'Icon of block type.' ), 'type' => array( 'string', 'null' ), 'default' => null, 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ); $category_definition = array( 'description' => __( 'Block category.' ), 'type' => array( 'string', 'null' ), 'default' => null, 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ); $this->schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'block-type', 'type' => 'object', 'properties' => array( 'api_version' => array( 'description' => __( 'Version of block API.' ), 'type' => 'integer', 'default' => 1, 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'title' => array( 'description' => __( 'Title of block type.' ), 'type' => 'string', 'default' => '', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'name' => array( 'description' => __( 'Unique name identifying the block type.' ), 'type' => 'string', 'default' => '', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'description' => array( 'description' => __( 'Description of block type.' ), 'type' => 'string', 'default' => '', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'icon' => $icon_definition, 'attributes' => array( 'description' => __( 'Block attributes.' ), 'type' => array( 'object', 'null' ), 'properties' => array(), 'default' => null, 'additionalProperties' => array( 'type' => 'object', ), 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'provides_context' => array( 'description' => __( 'Context provided by blocks of this type.' ), 'type' => 'object', 'properties' => array(), 'additionalProperties' => array( 'type' => 'string', ), 'default' => array(), 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'uses_context' => array( 'description' => __( 'Context values inherited by blocks of this type.' ), 'type' => 'array', 'default' => array(), 'items' => array( 'type' => 'string', ), 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'supports' => array( 'description' => __( 'Block supports.' ), 'type' => 'object', 'default' => array(), 'properties' => array(), 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'category' => $category_definition, 'is_dynamic' => array( 'description' => __( 'Is the block dynamically rendered.' ), 'type' => 'boolean', 'default' => false, 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'editor_script_handles' => array( 'description' => __( 'Editor script handles.' ), 'type' => array( 'array' ), 'default' => array(), 'items' => array( 'type' => 'string', ), 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'script_handles' => array( 'description' => __( 'Public facing and editor script handles.' ), 'type' => array( 'array' ), 'default' => array(), 'items' => array( 'type' => 'string', ), 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'view_script_handles' => array( 'description' => __( 'Public facing script handles.' ), 'type' => array( 'array' ), 'default' => array(), 'items' => array( 'type' => 'string', ), 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'editor_style_handles' => array( 'description' => __( 'Editor style handles.' ), 'type' => array( 'array' ), 'default' => array(), 'items' => array( 'type' => 'string', ), 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'style_handles' => array( 'description' => __( 'Public facing and editor style handles.' ), 'type' => array( 'array' ), 'default' => array(), 'items' => array( 'type' => 'string', ), 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'styles' => array( 'description' => __( 'Block style variations.' ), 'type' => 'array', 'items' => array( 'type' => 'object', 'properties' => array( 'name' => array( 'description' => __( 'Unique name identifying the style.' ), 'type' => 'string', 'required' => true, ), 'label' => array( 'description' => __( 'The human-readable label for the style.' ), 'type' => 'string', ), 'inline_style' => array( 'description' => __( 'Inline CSS code that registers the CSS class required for the style.' ), 'type' => 'string', ), 'style_handle' => array( 'description' => __( 'Contains the handle that defines the block style.' ), 'type' => 'string', ), ), ), 'default' => array(), 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'variations' => array( 'description' => __( 'Block variations.' ), 'type' => 'array', 'items' => array( 'type' => 'object', 'properties' => array( 'name' => array( 'description' => __( 'The unique and machine-readable name.' ), 'type' => 'string', 'required' => true, ), 'title' => array( 'description' => __( 'A human-readable variation title.' ), 'type' => 'string', 'required' => true, ), 'description' => array( 'description' => __( 'A detailed variation description.' ), 'type' => 'string', 'required' => false, ), 'category' => $category_definition, 'icon' => $icon_definition, 'isDefault' => array( 'description' => __( 'Indicates whether the current variation is the default one.' ), 'type' => 'boolean', 'required' => false, 'default' => false, ), 'attributes' => array( 'description' => __( 'The initial values for attributes.' ), 'type' => 'object', ), 'innerBlocks' => $inner_blocks_definition, 'example' => $example_definition, 'scope' => array( 'description' => __( 'The list of scopes where the variation is applicable. When not provided, it assumes all available scopes.' ), 'type' => array( 'array', 'null' ), 'default' => null, 'items' => array( 'type' => 'string', 'enum' => array( 'block', 'inserter', 'transform' ), ), 'readonly' => true, ), 'keywords' => $keywords_definition, ), ), 'readonly' => true, 'context' => array( 'embed', 'view', 'edit' ), 'default' => null, ), 'textdomain' => array( 'description' => __( 'Public text domain.' ), 'type' => array( 'string', 'null' ), 'default' => null, 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'parent' => array( 'description' => __( 'Parent blocks.' ), 'type' => array( 'array', 'null' ), 'items' => array( 'type' => 'string', ), 'default' => null, 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'ancestor' => array( 'description' => __( 'Ancestor blocks.' ), 'type' => array( 'array', 'null' ), 'items' => array( 'type' => 'string', ), 'default' => null, 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'keywords' => $keywords_definition, 'example' => $example_definition, ), ); // Properties deprecated in WordPress 6.1, but left in the schema for backwards compatibility. $deprecated_properties = array( 'editor_script' => array( 'description' => __( 'Editor script handle. DEPRECATED: Use `editor_script_handles` instead.' ), 'type' => array( 'string', 'null' ), 'default' => null, 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'script' => array( 'description' => __( 'Public facing and editor script handle. DEPRECATED: Use `script_handles` instead.' ), 'type' => array( 'string', 'null' ), 'default' => null, 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'view_script' => array( 'description' => __( 'Public facing script handle. DEPRECATED: Use `view_script_handles` instead.' ), 'type' => array( 'string', 'null' ), 'default' => null, 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'editor_style' => array( 'description' => __( 'Editor style handle. DEPRECATED: Use `editor_style_handles` instead.' ), 'type' => array( 'string', 'null' ), 'default' => null, 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'style' => array( 'description' => __( 'Public facing and editor style handle. DEPRECATED: Use `style_handles` instead.' ), 'type' => array( 'string', 'null' ), 'default' => null, 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), ); $this->schema['properties'] = array_merge( $this->schema['properties'], $deprecated_properties ); return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the query params for collections. * * @since 5.5.0 * * @return array Collection parameters. */ public function get_collection_params() { return array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), 'namespace' => array( 'description' => __( 'Block namespace.' ), 'type' => 'string', ), ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
programming_docs
wordpress class WP_oEmbed {} class WP\_oEmbed {} =================== Core class used to implement oEmbed functionality. * [\_\_call](wp_oembed/__call) β€” Exposes private/protected methods for backward compatibility. * [\_\_construct](wp_oembed/__construct) β€” Constructor. * [\_add\_provider\_early](wp_oembed/_add_provider_early) β€” Adds an oEmbed provider. * [\_fetch\_with\_format](wp_oembed/_fetch_with_format) β€” Fetches result from an oEmbed provider for a specific format and complete provider URL * [\_parse\_json](wp_oembed/_parse_json) β€” Parses a json response body. * [\_parse\_xml](wp_oembed/_parse_xml) β€” Parses an XML response body. * [\_parse\_xml\_body](wp_oembed/_parse_xml_body) β€” Serves as a helper function for parsing an XML response body. * [\_remove\_provider\_early](wp_oembed/_remove_provider_early) β€” Removes an oEmbed provider. * [\_strip\_newlines](wp_oembed/_strip_newlines) β€” Strips any new lines from the HTML. * [data2html](wp_oembed/data2html) β€” Converts a data object from WP\_oEmbed::fetch() and returns the HTML. * [discover](wp_oembed/discover) β€” Attempts to discover link tags at the given URL for an oEmbed provider. * [fetch](wp_oembed/fetch) β€” Connects to a oEmbed provider and returns the result. * [get\_data](wp_oembed/get_data) β€” Takes a URL and attempts to return the oEmbed data. * [get\_html](wp_oembed/get_html) β€” The do-it-all function that takes a URL and attempts to return the HTML. * [get\_provider](wp_oembed/get_provider) β€” Takes a URL and returns the corresponding oEmbed provider's URL, if there is one. File: `wp-includes/class-wp-oembed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-oembed.php/) ``` class WP_oEmbed { /** * A list of oEmbed providers. * * @since 2.9.0 * @var array */ public $providers = array(); /** * A list of an early oEmbed providers. * * @since 4.0.0 * @var array */ public static $early_providers = array(); /** * A list of private/protected methods, used for backward compatibility. * * @since 4.2.0 * @var array */ private $compat_methods = array( '_fetch_with_format', '_parse_json', '_parse_xml', '_parse_xml_body' ); /** * Constructor. * * @since 2.9.0 */ public function __construct() { $host = urlencode( home_url() ); $providers = array( '#https?://((m|www)\.)?youtube\.com/watch.*#i' => array( 'https://www.youtube.com/oembed', true ), '#https?://((m|www)\.)?youtube\.com/playlist.*#i' => array( 'https://www.youtube.com/oembed', true ), '#https?://((m|www)\.)?youtube\.com/shorts/*#i' => array( 'https://www.youtube.com/oembed', true ), '#https?://youtu\.be/.*#i' => array( 'https://www.youtube.com/oembed', true ), '#https?://(.+\.)?vimeo\.com/.*#i' => array( 'https://vimeo.com/api/oembed.{format}', true ), '#https?://(www\.)?dailymotion\.com/.*#i' => array( 'https://www.dailymotion.com/services/oembed', true ), '#https?://dai\.ly/.*#i' => array( 'https://www.dailymotion.com/services/oembed', true ), '#https?://(www\.)?flickr\.com/.*#i' => array( 'https://www.flickr.com/services/oembed/', true ), '#https?://flic\.kr/.*#i' => array( 'https://www.flickr.com/services/oembed/', true ), '#https?://(.+\.)?smugmug\.com/.*#i' => array( 'https://api.smugmug.com/services/oembed/', true ), '#https?://(www\.)?scribd\.com/(doc|document)/.*#i' => array( 'https://www.scribd.com/services/oembed', true ), '#https?://wordpress\.tv/.*#i' => array( 'https://wordpress.tv/oembed/', true ), '#https?://(.+\.)?polldaddy\.com/.*#i' => array( 'https://api.crowdsignal.com/oembed', true ), '#https?://poll\.fm/.*#i' => array( 'https://api.crowdsignal.com/oembed', true ), '#https?://(.+\.)?survey\.fm/.*#i' => array( 'https://api.crowdsignal.com/oembed', true ), '#https?://(www\.)?twitter\.com/\w{1,15}/status(es)?/.*#i' => array( 'https://publish.twitter.com/oembed', true ), '#https?://(www\.)?twitter\.com/\w{1,15}$#i' => array( 'https://publish.twitter.com/oembed', true ), '#https?://(www\.)?twitter\.com/\w{1,15}/likes$#i' => array( 'https://publish.twitter.com/oembed', true ), '#https?://(www\.)?twitter\.com/\w{1,15}/lists/.*#i' => array( 'https://publish.twitter.com/oembed', true ), '#https?://(www\.)?twitter\.com/\w{1,15}/timelines/.*#i' => array( 'https://publish.twitter.com/oembed', true ), '#https?://(www\.)?twitter\.com/i/moments/.*#i' => array( 'https://publish.twitter.com/oembed', true ), '#https?://(www\.)?soundcloud\.com/.*#i' => array( 'https://soundcloud.com/oembed', true ), '#https?://(.+?\.)?slideshare\.net/.*#i' => array( 'https://www.slideshare.net/api/oembed/2', true ), '#https?://(open|play)\.spotify\.com/.*#i' => array( 'https://embed.spotify.com/oembed/', true ), '#https?://(.+\.)?imgur\.com/.*#i' => array( 'https://api.imgur.com/oembed', true ), '#https?://(www\.)?issuu\.com/.+/docs/.+#i' => array( 'https://issuu.com/oembed_wp', true ), '#https?://(www\.)?mixcloud\.com/.*#i' => array( 'https://www.mixcloud.com/oembed', true ), '#https?://(www\.|embed\.)?ted\.com/talks/.*#i' => array( 'https://www.ted.com/services/v1/oembed.{format}', true ), '#https?://(www\.)?(animoto|video214)\.com/play/.*#i' => array( 'https://animoto.com/oembeds/create', true ), '#https?://(.+)\.tumblr\.com/.*#i' => array( 'https://www.tumblr.com/oembed/1.0', true ), '#https?://(www\.)?kickstarter\.com/projects/.*#i' => array( 'https://www.kickstarter.com/services/oembed', true ), '#https?://kck\.st/.*#i' => array( 'https://www.kickstarter.com/services/oembed', true ), '#https?://cloudup\.com/.*#i' => array( 'https://cloudup.com/oembed', true ), '#https?://(www\.)?reverbnation\.com/.*#i' => array( 'https://www.reverbnation.com/oembed', true ), '#https?://videopress\.com/v/.*#' => array( 'https://public-api.wordpress.com/oembed/?for=' . $host, true ), '#https?://(www\.)?reddit\.com/r/[^/]+/comments/.*#i' => array( 'https://www.reddit.com/oembed', true ), '#https?://(www\.)?speakerdeck\.com/.*#i' => array( 'https://speakerdeck.com/oembed.{format}', true ), '#https?://(www\.)?screencast\.com/.*#i' => array( 'https://api.screencast.com/external/oembed', true ), '#https?://([a-z0-9-]+\.)?amazon\.(com|com\.mx|com\.br|ca)/.*#i' => array( 'https://read.amazon.com/kp/api/oembed', true ), '#https?://([a-z0-9-]+\.)?amazon\.(co\.uk|de|fr|it|es|in|nl|ru)/.*#i' => array( 'https://read.amazon.co.uk/kp/api/oembed', true ), '#https?://([a-z0-9-]+\.)?amazon\.(co\.jp|com\.au)/.*#i' => array( 'https://read.amazon.com.au/kp/api/oembed', true ), '#https?://([a-z0-9-]+\.)?amazon\.cn/.*#i' => array( 'https://read.amazon.cn/kp/api/oembed', true ), '#https?://(www\.)?a\.co/.*#i' => array( 'https://read.amazon.com/kp/api/oembed', true ), '#https?://(www\.)?amzn\.to/.*#i' => array( 'https://read.amazon.com/kp/api/oembed', true ), '#https?://(www\.)?amzn\.eu/.*#i' => array( 'https://read.amazon.co.uk/kp/api/oembed', true ), '#https?://(www\.)?amzn\.in/.*#i' => array( 'https://read.amazon.in/kp/api/oembed', true ), '#https?://(www\.)?amzn\.asia/.*#i' => array( 'https://read.amazon.com.au/kp/api/oembed', true ), '#https?://(www\.)?z\.cn/.*#i' => array( 'https://read.amazon.cn/kp/api/oembed', true ), '#https?://www\.someecards\.com/.+-cards/.+#i' => array( 'https://www.someecards.com/v2/oembed/', true ), '#https?://www\.someecards\.com/usercards/viewcard/.+#i' => array( 'https://www.someecards.com/v2/oembed/', true ), '#https?://some\.ly\/.+#i' => array( 'https://www.someecards.com/v2/oembed/', true ), '#https?://(www\.)?tiktok\.com/.*/video/.*#i' => array( 'https://www.tiktok.com/oembed', true ), '#https?://([a-z]{2}|www)\.pinterest\.com(\.(au|mx))?/.*#i' => array( 'https://www.pinterest.com/oembed.json', true ), '#https?://(www\.)?wolframcloud\.com/obj/.+#i' => array( 'https://www.wolframcloud.com/oembed', true ), '#https?://pca\.st/.+#i' => array( 'https://pca.st/oembed.json', true ), ); if ( ! empty( self::$early_providers['add'] ) ) { foreach ( self::$early_providers['add'] as $format => $data ) { $providers[ $format ] = $data; } } if ( ! empty( self::$early_providers['remove'] ) ) { foreach ( self::$early_providers['remove'] as $format ) { unset( $providers[ $format ] ); } } self::$early_providers = array(); /** * Filters the list of sanctioned oEmbed providers. * * Since WordPress 4.4, oEmbed discovery is enabled for all users and allows embedding of sanitized * iframes. The providers in this list are sanctioned, meaning they are trusted and allowed to * embed any content, such as iframes, videos, JavaScript, and arbitrary HTML. * * Supported providers: * * | Provider | Flavor | Since | * | ------------ | ----------------------------------------- | ------- | * | Dailymotion | dailymotion.com | 2.9.0 | * | Flickr | flickr.com | 2.9.0 | * | Scribd | scribd.com | 2.9.0 | * | Vimeo | vimeo.com | 2.9.0 | * | WordPress.tv | wordpress.tv | 2.9.0 | * | YouTube | youtube.com/watch | 2.9.0 | * | Crowdsignal | polldaddy.com | 3.0.0 | * | SmugMug | smugmug.com | 3.0.0 | * | YouTube | youtu.be | 3.0.0 | * | Twitter | twitter.com | 3.4.0 | * | Slideshare | slideshare.net | 3.5.0 | * | SoundCloud | soundcloud.com | 3.5.0 | * | Dailymotion | dai.ly | 3.6.0 | * | Flickr | flic.kr | 3.6.0 | * | Spotify | spotify.com | 3.6.0 | * | Imgur | imgur.com | 3.9.0 | * | Animoto | animoto.com | 4.0.0 | * | Animoto | video214.com | 4.0.0 | * | Issuu | issuu.com | 4.0.0 | * | Mixcloud | mixcloud.com | 4.0.0 | * | Crowdsignal | poll.fm | 4.0.0 | * | TED | ted.com | 4.0.0 | * | YouTube | youtube.com/playlist | 4.0.0 | * | Tumblr | tumblr.com | 4.2.0 | * | Kickstarter | kickstarter.com | 4.2.0 | * | Kickstarter | kck.st | 4.2.0 | * | Cloudup | cloudup.com | 4.3.0 | * | ReverbNation | reverbnation.com | 4.4.0 | * | VideoPress | videopress.com | 4.4.0 | * | Reddit | reddit.com | 4.4.0 | * | Speaker Deck | speakerdeck.com | 4.4.0 | * | Twitter | twitter.com/timelines | 4.5.0 | * | Twitter | twitter.com/moments | 4.5.0 | * | Twitter | twitter.com/user | 4.7.0 | * | Twitter | twitter.com/likes | 4.7.0 | * | Twitter | twitter.com/lists | 4.7.0 | * | Screencast | screencast.com | 4.8.0 | * | Amazon | amazon.com (com.mx, com.br, ca) | 4.9.0 | * | Amazon | amazon.de (fr, it, es, in, nl, ru, co.uk) | 4.9.0 | * | Amazon | amazon.co.jp (com.au) | 4.9.0 | * | Amazon | amazon.cn | 4.9.0 | * | Amazon | a.co | 4.9.0 | * | Amazon | amzn.to (eu, in, asia) | 4.9.0 | * | Amazon | z.cn | 4.9.0 | * | Someecards | someecards.com | 4.9.0 | * | Someecards | some.ly | 4.9.0 | * | Crowdsignal | survey.fm | 5.1.0 | * | TikTok | tiktok.com | 5.4.0 | * | Pinterest | pinterest.com | 5.9.0 | * | WolframCloud | wolframcloud.com | 5.9.0 | * | Pocket Casts | pocketcasts.com | 6.1.0 | * * No longer supported providers: * * | Provider | Flavor | Since | Removed | * | ------------ | -------------------- | --------- | --------- | * | Qik | qik.com | 2.9.0 | 3.9.0 | * | Viddler | viddler.com | 2.9.0 | 4.0.0 | * | Revision3 | revision3.com | 2.9.0 | 4.2.0 | * | Blip | blip.tv | 2.9.0 | 4.4.0 | * | Rdio | rdio.com | 3.6.0 | 4.4.1 | * | Rdio | rd.io | 3.6.0 | 4.4.1 | * | Vine | vine.co | 4.1.0 | 4.9.0 | * | Photobucket | photobucket.com | 2.9.0 | 5.1.0 | * | Funny or Die | funnyordie.com | 3.0.0 | 5.1.0 | * | CollegeHumor | collegehumor.com | 4.0.0 | 5.3.1 | * | Hulu | hulu.com | 2.9.0 | 5.5.0 | * | Instagram | instagram.com | 3.5.0 | 5.5.2 | * | Instagram | instagr.am | 3.5.0 | 5.5.2 | * | Instagram TV | instagram.com | 5.1.0 | 5.5.2 | * | Instagram TV | instagr.am | 5.1.0 | 5.5.2 | * | Facebook | facebook.com | 4.7.0 | 5.5.2 | * | Meetup.com | meetup.com | 3.9.0 | 6.0.1 | * | Meetup.com | meetu.ps | 3.9.0 | 6.0.1 | * * @see wp_oembed_add_provider() * * @since 2.9.0 * * @param array[] $providers An array of arrays containing data about popular oEmbed providers. */ $this->providers = apply_filters( 'oembed_providers', $providers ); // Fix any embeds that contain new lines in the middle of the HTML which breaks wpautop(). add_filter( 'oembed_dataparse', array( $this, '_strip_newlines' ), 10, 3 ); } /** * Exposes private/protected methods for backward compatibility. * * @since 4.0.0 * * @param string $name Method to call. * @param array $arguments Arguments to pass when calling. * @return mixed|false Return value of the callback, false otherwise. */ public function __call( $name, $arguments ) { if ( in_array( $name, $this->compat_methods, true ) ) { return $this->$name( ...$arguments ); } return false; } /** * Takes a URL and returns the corresponding oEmbed provider's URL, if there is one. * * @since 4.0.0 * * @see WP_oEmbed::discover() * * @param string $url The URL to the content. * @param string|array $args { * Optional. Additional provider arguments. Default empty. * * @type bool $discover Optional. Determines whether to attempt to discover link tags * at the given URL for an oEmbed provider when the provider URL * is not found in the built-in providers list. Default true. * } * @return string|false The oEmbed provider URL on success, false on failure. */ public function get_provider( $url, $args = '' ) { $args = wp_parse_args( $args ); $provider = false; if ( ! isset( $args['discover'] ) ) { $args['discover'] = true; } foreach ( $this->providers as $matchmask => $data ) { list( $providerurl, $regex ) = $data; // Turn the asterisk-type provider URLs into regex. if ( ! $regex ) { $matchmask = '#' . str_replace( '___wildcard___', '(.+)', preg_quote( str_replace( '*', '___wildcard___', $matchmask ), '#' ) ) . '#i'; $matchmask = preg_replace( '|^#http\\\://|', '#https?\://', $matchmask ); } if ( preg_match( $matchmask, $url ) ) { $provider = str_replace( '{format}', 'json', $providerurl ); // JSON is easier to deal with than XML. break; } } if ( ! $provider && $args['discover'] ) { $provider = $this->discover( $url ); } return $provider; } /** * Adds an oEmbed provider. * * The provider is added just-in-time when wp_oembed_add_provider() is called before * the {@see 'plugins_loaded'} hook. * * The just-in-time addition is for the benefit of the {@see 'oembed_providers'} filter. * * @since 4.0.0 * * @see wp_oembed_add_provider() * * @param string $format Format of URL that this provider can handle. You can use * asterisks as wildcards. * @param string $provider The URL to the oEmbed provider.. * @param bool $regex Optional. Whether the $format parameter is in a regex format. * Default false. */ public static function _add_provider_early( $format, $provider, $regex = false ) { if ( empty( self::$early_providers['add'] ) ) { self::$early_providers['add'] = array(); } self::$early_providers['add'][ $format ] = array( $provider, $regex ); } /** * Removes an oEmbed provider. * * The provider is removed just-in-time when wp_oembed_remove_provider() is called before * the {@see 'plugins_loaded'} hook. * * The just-in-time removal is for the benefit of the {@see 'oembed_providers'} filter. * * @since 4.0.0 * * @see wp_oembed_remove_provider() * * @param string $format The format of URL that this provider can handle. You can use * asterisks as wildcards. */ public static function _remove_provider_early( $format ) { if ( empty( self::$early_providers['remove'] ) ) { self::$early_providers['remove'] = array(); } self::$early_providers['remove'][] = $format; } /** * Takes a URL and attempts to return the oEmbed data. * * @see WP_oEmbed::fetch() * * @since 4.8.0 * * @param string $url The URL to the content that should be attempted to be embedded. * @param string|array $args Optional. Additional arguments for retrieving embed HTML. * See wp_oembed_get() for accepted arguments. Default empty. * @return object|false The result in the form of an object on success, false on failure. */ public function get_data( $url, $args = '' ) { $args = wp_parse_args( $args ); $provider = $this->get_provider( $url, $args ); if ( ! $provider ) { return false; } $data = $this->fetch( $provider, $url, $args ); if ( false === $data ) { return false; } return $data; } /** * The do-it-all function that takes a URL and attempts to return the HTML. * * @see WP_oEmbed::fetch() * @see WP_oEmbed::data2html() * * @since 2.9.0 * * @param string $url The URL to the content that should be attempted to be embedded. * @param string|array $args Optional. Additional arguments for retrieving embed HTML. * See wp_oembed_get() for accepted arguments. Default empty. * @return string|false The UNSANITIZED (and potentially unsafe) HTML that should be used to embed * on success, false on failure. */ public function get_html( $url, $args = '' ) { /** * Filters the oEmbed result before any HTTP requests are made. * * This allows one to short-circuit the default logic, perhaps by * replacing it with a routine that is more optimal for your setup. * * Returning a non-null value from the filter will effectively short-circuit retrieval * and return the passed value instead. * * @since 4.5.3 * * @param null|string $result The UNSANITIZED (and potentially unsafe) HTML that should be used to embed. * Default null to continue retrieving the result. * @param string $url The URL to the content that should be attempted to be embedded. * @param string|array $args Optional. Additional arguments for retrieving embed HTML. * See wp_oembed_get() for accepted arguments. Default empty. */ $pre = apply_filters( 'pre_oembed_result', null, $url, $args ); if ( null !== $pre ) { return $pre; } $data = $this->get_data( $url, $args ); if ( false === $data ) { return false; } /** * Filters the HTML returned by the oEmbed provider. * * @since 2.9.0 * * @param string|false $data The returned oEmbed HTML (false if unsafe). * @param string $url URL of the content to be embedded. * @param string|array $args Optional. Additional arguments for retrieving embed HTML. * See wp_oembed_get() for accepted arguments. Default empty. */ return apply_filters( 'oembed_result', $this->data2html( $data, $url ), $url, $args ); } /** * Attempts to discover link tags at the given URL for an oEmbed provider. * * @since 2.9.0 * * @param string $url The URL that should be inspected for discovery `<link>` tags. * @return string|false The oEmbed provider URL on success, false on failure. */ public function discover( $url ) { $providers = array(); $args = array( 'limit_response_size' => 153600, // 150 KB ); /** * Filters oEmbed remote get arguments. * * @since 4.0.0 * * @see WP_Http::request() * * @param array $args oEmbed remote get arguments. * @param string $url URL to be inspected. */ $args = apply_filters( 'oembed_remote_get_args', $args, $url ); // Fetch URL content. $request = wp_safe_remote_get( $url, $args ); $html = wp_remote_retrieve_body( $request ); if ( $html ) { /** * Filters the link types that contain oEmbed provider URLs. * * @since 2.9.0 * * @param string[] $format Array of oEmbed link types. Accepts 'application/json+oembed', * 'text/xml+oembed', and 'application/xml+oembed' (incorrect, * used by at least Vimeo). */ $linktypes = apply_filters( 'oembed_linktypes', array( 'application/json+oembed' => 'json', 'text/xml+oembed' => 'xml', 'application/xml+oembed' => 'xml', ) ); // Strip <body>. $html_head_end = stripos( $html, '</head>' ); if ( $html_head_end ) { $html = substr( $html, 0, $html_head_end ); } // Do a quick check. $tagfound = false; foreach ( $linktypes as $linktype => $format ) { if ( stripos( $html, $linktype ) ) { $tagfound = true; break; } } if ( $tagfound && preg_match_all( '#<link([^<>]+)/?>#iU', $html, $links ) ) { foreach ( $links[1] as $link ) { $atts = shortcode_parse_atts( $link ); if ( ! empty( $atts['type'] ) && ! empty( $linktypes[ $atts['type'] ] ) && ! empty( $atts['href'] ) ) { $providers[ $linktypes[ $atts['type'] ] ] = htmlspecialchars_decode( $atts['href'] ); // Stop here if it's JSON (that's all we need). if ( 'json' === $linktypes[ $atts['type'] ] ) { break; } } } } } // JSON is preferred to XML. if ( ! empty( $providers['json'] ) ) { return $providers['json']; } elseif ( ! empty( $providers['xml'] ) ) { return $providers['xml']; } else { return false; } } /** * Connects to a oEmbed provider and returns the result. * * @since 2.9.0 * * @param string $provider The URL to the oEmbed provider. * @param string $url The URL to the content that is desired to be embedded. * @param string|array $args Optional. Additional arguments for retrieving embed HTML. * See wp_oembed_get() for accepted arguments. Default empty. * @return object|false The result in the form of an object on success, false on failure. */ public function fetch( $provider, $url, $args = '' ) { $args = wp_parse_args( $args, wp_embed_defaults( $url ) ); $provider = add_query_arg( 'maxwidth', (int) $args['width'], $provider ); $provider = add_query_arg( 'maxheight', (int) $args['height'], $provider ); $provider = add_query_arg( 'url', urlencode( $url ), $provider ); $provider = add_query_arg( 'dnt', 1, $provider ); /** * Filters the oEmbed URL to be fetched. * * @since 2.9.0 * @since 4.9.0 The `dnt` (Do Not Track) query parameter was added to all oEmbed provider URLs. * * @param string $provider URL of the oEmbed provider. * @param string $url URL of the content to be embedded. * @param array $args Optional. Additional arguments for retrieving embed HTML. * See wp_oembed_get() for accepted arguments. Default empty. */ $provider = apply_filters( 'oembed_fetch_url', $provider, $url, $args ); foreach ( array( 'json', 'xml' ) as $format ) { $result = $this->_fetch_with_format( $provider, $format ); if ( is_wp_error( $result ) && 'not-implemented' === $result->get_error_code() ) { continue; } return ( $result && ! is_wp_error( $result ) ) ? $result : false; } return false; } /** * Fetches result from an oEmbed provider for a specific format and complete provider URL * * @since 3.0.0 * * @param string $provider_url_with_args URL to the provider with full arguments list (url, maxheight, etc.) * @param string $format Format to use. * @return object|false|WP_Error The result in the form of an object on success, false on failure. */ private function _fetch_with_format( $provider_url_with_args, $format ) { $provider_url_with_args = add_query_arg( 'format', $format, $provider_url_with_args ); /** This filter is documented in wp-includes/class-wp-oembed.php */ $args = apply_filters( 'oembed_remote_get_args', array(), $provider_url_with_args ); $response = wp_safe_remote_get( $provider_url_with_args, $args ); if ( 501 == wp_remote_retrieve_response_code( $response ) ) { return new WP_Error( 'not-implemented' ); } $body = wp_remote_retrieve_body( $response ); if ( ! $body ) { return false; } $parse_method = "_parse_$format"; return $this->$parse_method( $body ); } /** * Parses a json response body. * * @since 3.0.0 * * @param string $response_body * @return object|false */ private function _parse_json( $response_body ) { $data = json_decode( trim( $response_body ) ); return ( $data && is_object( $data ) ) ? $data : false; } /** * Parses an XML response body. * * @since 3.0.0 * * @param string $response_body * @return object|false */ private function _parse_xml( $response_body ) { if ( ! function_exists( 'libxml_disable_entity_loader' ) ) { return false; } if ( PHP_VERSION_ID < 80000 ) { // This function has been deprecated in PHP 8.0 because in libxml 2.9.0, external entity loading // is disabled by default, so this function is no longer needed to protect against XXE attacks. // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.libxml_disable_entity_loaderDeprecated $loader = libxml_disable_entity_loader( true ); } $errors = libxml_use_internal_errors( true ); $return = $this->_parse_xml_body( $response_body ); libxml_use_internal_errors( $errors ); if ( PHP_VERSION_ID < 80000 && isset( $loader ) ) { // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.libxml_disable_entity_loaderDeprecated libxml_disable_entity_loader( $loader ); } return $return; } /** * Serves as a helper function for parsing an XML response body. * * @since 3.6.0 * * @param string $response_body * @return stdClass|false */ private function _parse_xml_body( $response_body ) { if ( ! function_exists( 'simplexml_import_dom' ) || ! class_exists( 'DOMDocument', false ) ) { return false; } $dom = new DOMDocument; $success = $dom->loadXML( $response_body ); if ( ! $success ) { return false; } if ( isset( $dom->doctype ) ) { return false; } foreach ( $dom->childNodes as $child ) { if ( XML_DOCUMENT_TYPE_NODE === $child->nodeType ) { return false; } } $xml = simplexml_import_dom( $dom ); if ( ! $xml ) { return false; } $return = new stdClass; foreach ( $xml as $key => $value ) { $return->$key = (string) $value; } return $return; } /** * Converts a data object from WP_oEmbed::fetch() and returns the HTML. * * @since 2.9.0 * * @param object $data A data object result from an oEmbed provider. * @param string $url The URL to the content that is desired to be embedded. * @return string|false The HTML needed to embed on success, false on failure. */ public function data2html( $data, $url ) { if ( ! is_object( $data ) || empty( $data->type ) ) { return false; } $return = false; switch ( $data->type ) { case 'photo': if ( empty( $data->url ) || empty( $data->width ) || empty( $data->height ) ) { break; } if ( ! is_string( $data->url ) || ! is_numeric( $data->width ) || ! is_numeric( $data->height ) ) { break; } $title = ! empty( $data->title ) && is_string( $data->title ) ? $data->title : ''; $return = '<a href="' . esc_url( $url ) . '"><img src="' . esc_url( $data->url ) . '" alt="' . esc_attr( $title ) . '" width="' . esc_attr( $data->width ) . '" height="' . esc_attr( $data->height ) . '" /></a>'; break; case 'video': case 'rich': if ( ! empty( $data->html ) && is_string( $data->html ) ) { $return = $data->html; } break; case 'link': if ( ! empty( $data->title ) && is_string( $data->title ) ) { $return = '<a href="' . esc_url( $url ) . '">' . esc_html( $data->title ) . '</a>'; } break; default: $return = false; } /** * Filters the returned oEmbed HTML. * * Use this filter to add support for custom data types, or to filter the result. * * @since 2.9.0 * * @param string $return The returned oEmbed HTML. * @param object $data A data object result from an oEmbed provider. * @param string $url The URL of the content to be embedded. */ return apply_filters( 'oembed_dataparse', $return, $data, $url ); } /** * Strips any new lines from the HTML. * * @since 2.9.0 as strip_scribd_newlines() * @since 3.0.0 * * @param string $html Existing HTML. * @param object $data Data object from WP_oEmbed::data2html() * @param string $url The original URL passed to oEmbed. * @return string Possibly modified $html */ public function _strip_newlines( $html, $data, $url ) { if ( false === strpos( $html, "\n" ) ) { return $html; } $count = 1; $found = array(); $token = '__PRE__'; $search = array( "\t", "\n", "\r", ' ' ); $replace = array( '__TAB__', '__NL__', '__CR__', '__SPACE__' ); $tokenized = str_replace( $search, $replace, $html ); preg_match_all( '#(<pre[^>]*>.+?</pre>)#i', $tokenized, $matches, PREG_SET_ORDER ); foreach ( $matches as $i => $match ) { $tag_html = str_replace( $replace, $search, $match[0] ); $tag_token = $token . $i; $found[ $tag_token ] = $tag_html; $html = str_replace( $tag_html, $tag_token, $html, $count ); } $replaced = str_replace( $replace, $search, $html ); $stripped = str_replace( array( "\r\n", "\n" ), '', $replaced ); $pre = array_values( $found ); $tokens = array_keys( $found ); return str_replace( $tokens, $pre, $stripped ); } } ``` | Version | Description | | --- | --- | | [2.9.0](https://developer.wordpress.org/reference/since/2.9.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Term_Search_Handler {} class WP\_REST\_Term\_Search\_Handler {} ======================================== Core class representing a search handler for terms in the REST API. * [WP\_REST\_Search\_Handler](wp_rest_search_handler) * [\_\_construct](wp_rest_term_search_handler/__construct) β€” Constructor. * [prepare\_item](wp_rest_term_search_handler/prepare_item) β€” Prepares the search result for a given ID. * [prepare\_item\_links](wp_rest_term_search_handler/prepare_item_links) β€” Prepares links for the search result of a given ID. * [search\_items](wp_rest_term_search_handler/search_items) β€” Searches the object type content for a given search request. File: `wp-includes/rest-api/search/class-wp-rest-term-search-handler.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/search/class-wp-rest-term-search-handler.php/) ``` class WP_REST_Term_Search_Handler extends WP_REST_Search_Handler { /** * Constructor. * * @since 5.6.0 */ public function __construct() { $this->type = 'term'; $this->subtypes = array_values( get_taxonomies( array( 'public' => true, 'show_in_rest' => true, ), 'names' ) ); } /** * Searches the object type content for a given search request. * * @since 5.6.0 * * @param WP_REST_Request $request Full REST request. * @return array { * Associative array containing found IDs and total count for the matching search results. * * @type int[] $ids Found IDs. * @type string|int|WP_Error $total Numeric string containing the number of terms in that * taxonomy, 0 if there are no results, or WP_Error if * the requested taxonomy does not exist. * } */ public function search_items( WP_REST_Request $request ) { $taxonomies = $request[ WP_REST_Search_Controller::PROP_SUBTYPE ]; if ( in_array( WP_REST_Search_Controller::TYPE_ANY, $taxonomies, true ) ) { $taxonomies = $this->subtypes; } $page = (int) $request['page']; $per_page = (int) $request['per_page']; $query_args = array( 'taxonomy' => $taxonomies, 'hide_empty' => false, 'offset' => ( $page - 1 ) * $per_page, 'number' => $per_page, ); if ( ! empty( $request['search'] ) ) { $query_args['search'] = $request['search']; } if ( ! empty( $request['exclude'] ) ) { $query_args['exclude'] = $request['exclude']; } if ( ! empty( $request['include'] ) ) { $query_args['include'] = $request['include']; } /** * Filters the query arguments for a REST API search request. * * Enables adding extra arguments or setting defaults for a term search request. * * @since 5.6.0 * * @param array $query_args Key value array of query var to query value. * @param WP_REST_Request $request The request used. */ $query_args = apply_filters( 'rest_term_search_query', $query_args, $request ); $query = new WP_Term_Query(); $found_terms = $query->query( $query_args ); $found_ids = wp_list_pluck( $found_terms, 'term_id' ); unset( $query_args['offset'], $query_args['number'] ); $total = wp_count_terms( $query_args ); // wp_count_terms() can return a falsey value when the term has no children. if ( ! $total ) { $total = 0; } return array( self::RESULT_IDS => $found_ids, self::RESULT_TOTAL => $total, ); } /** * Prepares the search result for a given ID. * * @since 5.6.0 * * @param int $id Item ID. * @param array $fields Fields to include for the item. * @return array Associative array containing all fields for the item. */ public function prepare_item( $id, array $fields ) { $term = get_term( $id ); $data = array(); if ( in_array( WP_REST_Search_Controller::PROP_ID, $fields, true ) ) { $data[ WP_REST_Search_Controller::PROP_ID ] = (int) $id; } if ( in_array( WP_REST_Search_Controller::PROP_TITLE, $fields, true ) ) { $data[ WP_REST_Search_Controller::PROP_TITLE ] = $term->name; } if ( in_array( WP_REST_Search_Controller::PROP_URL, $fields, true ) ) { $data[ WP_REST_Search_Controller::PROP_URL ] = get_term_link( $id ); } if ( in_array( WP_REST_Search_Controller::PROP_TYPE, $fields, true ) ) { $data[ WP_REST_Search_Controller::PROP_TYPE ] = $term->taxonomy; } return $data; } /** * Prepares links for the search result of a given ID. * * @since 5.6.0 * * @param int $id Item ID. * @return array[] Array of link arrays for the given item. */ public function prepare_item_links( $id ) { $term = get_term( $id ); $links = array(); $item_route = rest_get_route_for_term( $term ); if ( $item_route ) { $links['self'] = array( 'href' => rest_url( $item_route ), 'embeddable' => true, ); } $links['about'] = array( 'href' => rest_url( sprintf( 'wp/v2/taxonomies/%s', $term->taxonomy ) ), ); return $links; } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Search\_Handler](wp_rest_search_handler) wp-includes/rest-api/search/class-wp-rest-search-handler.php | Core base class representing a search handler for an object type in the REST API. | | Version | Description | | --- | --- | | [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. | wordpress class WP_Privacy_Data_Export_Requests_Table {} class WP\_Privacy\_Data\_Export\_Requests\_Table {} =================================================== This class has been deprecated. Previous class for list table for privacy data export requests. * [\_\_construct](wp_privacy_data_export_requests_table/__construct) * [column\_email](wp_privacy_data_export_requests_table/column_email) β€” Actions column. * [column\_next\_steps](wp_privacy_data_export_requests_table/column_next_steps) β€” Displays the next steps column. File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/) ``` class WP_Privacy_Data_Export_Requests_Table extends WP_Privacy_Data_Export_Requests_List_Table { function __construct( $args ) { _deprecated_function( __CLASS__, '5.3.0', 'WP_Privacy_Data_Export_Requests_List_Table' ); if ( ! isset( $args['screen'] ) || $args['screen'] === 'export_personal_data' ) { $args['screen'] = 'export-personal-data'; } parent::__construct( $args ); } } ``` | Uses | Description | | --- | --- | | [WP\_Privacy\_Data\_Export\_Requests\_List\_Table](wp_privacy_data_export_requests_list_table) wp-admin/includes/class-wp-privacy-data-export-requests-list-table.php | [WP\_Privacy\_Data\_Export\_Requests\_Table](wp_privacy_data_export_requests_table) class. | | Version | Description | | --- | --- | | [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | This class has been deprecated. | | [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. | wordpress class Language_Pack_Upgrader_Skin {} class Language\_Pack\_Upgrader\_Skin {} ======================================= Translation Upgrader Skin for WordPress Translation Upgrades. * [WP\_Upgrader\_Skin](wp_upgrader_skin) * [\_\_construct](language_pack_upgrader_skin/__construct) * [after](language_pack_upgrader_skin/after) * [before](language_pack_upgrader_skin/before) * [bulk\_footer](language_pack_upgrader_skin/bulk_footer) * [error](language_pack_upgrader_skin/error) File: `wp-admin/includes/class-language-pack-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-language-pack-upgrader-skin.php/) ``` class Language_Pack_Upgrader_Skin extends WP_Upgrader_Skin { public $language_update = null; public $done_header = false; public $done_footer = false; public $display_footer_actions = true; /** * @param array $args */ public function __construct( $args = array() ) { $defaults = array( 'url' => '', 'nonce' => '', 'title' => __( 'Update Translations' ), 'skip_header_footer' => false, ); $args = wp_parse_args( $args, $defaults ); if ( $args['skip_header_footer'] ) { $this->done_header = true; $this->done_footer = true; $this->display_footer_actions = false; } parent::__construct( $args ); } /** */ public function before() { $name = $this->upgrader->get_name_for_update( $this->language_update ); echo '<div class="update-messages lp-show-latest">'; /* translators: 1: Project name (plugin, theme, or WordPress), 2: Language. */ printf( '<h2>' . __( 'Updating translations for %1$s (%2$s)&#8230;' ) . '</h2>', $name, $this->language_update->language ); } /** * @since 5.9.0 Renamed `$error` to `$errors` for PHP 8 named parameter support. * * @param string|WP_Error $errors Errors. */ public function error( $errors ) { echo '<div class="lp-error">'; parent::error( $errors ); echo '</div>'; } /** */ public function after() { echo '</div>'; } /** */ public function bulk_footer() { $this->decrement_update_count( 'translation' ); $update_actions = array( 'updates_page' => sprintf( '<a href="%s" target="_parent">%s</a>', self_admin_url( 'update-core.php' ), __( 'Go to WordPress Updates page' ) ), ); /** * Filters the list of action links available following a translations update. * * @since 3.7.0 * * @param string[] $update_actions Array of translations update links. */ $update_actions = apply_filters( 'update_translations_complete_actions', $update_actions ); if ( $update_actions && $this->display_footer_actions ) { $this->feedback( implode( ' | ', $update_actions ) ); } } } ``` | Uses | Description | | --- | --- | | [WP\_Upgrader\_Skin](wp_upgrader_skin) wp-admin/includes/class-wp-upgrader-skin.php | Generic Skin for the WordPress Upgrader classes. This skin is designed to be extended for specific purposes. | | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php. | | [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. | wordpress class WP_Customize_Nav_Menu_Setting {} class WP\_Customize\_Nav\_Menu\_Setting {} ========================================== Customize Setting to represent a nav\_menu. Subclass of [WP\_Customize\_Setting](wp_customize_setting) to represent a nav\_menu taxonomy term, and the IDs for the nav\_menu\_items associated with the nav menu. * [wp\_get\_nav\_menu\_object()](../functions/wp_get_nav_menu_object) * [WP\_Customize\_Setting](wp_customize_setting) * [\_\_construct](wp_customize_nav_menu_setting/__construct) β€” Constructor. * [\_sort\_menus\_by\_orderby](wp_customize_nav_menu_setting/_sort_menus_by_orderby) β€” Sort menu objects by the class-supplied orderby property. β€” deprecated * [amend\_customize\_save\_response](wp_customize_nav_menu_setting/amend_customize_save_response) β€” Export data for the JS client. * [filter\_nav\_menu\_options](wp_customize_nav_menu_setting/filter_nav_menu_options) β€” Filters the nav\_menu\_options option to include this menu's auto\_add preference. * [filter\_nav\_menu\_options\_value](wp_customize_nav_menu_setting/filter_nav_menu_options_value) β€” Updates a nav\_menu\_options array. * [filter\_wp\_get\_nav\_menu\_object](wp_customize_nav_menu_setting/filter_wp_get_nav_menu_object) β€” Filters the wp\_get\_nav\_menu\_object() result to supply the previewed menu object. * [filter\_wp\_get\_nav\_menus](wp_customize_nav_menu_setting/filter_wp_get_nav_menus) β€” Filters the wp\_get\_nav\_menus() result to ensure the inserted menu object is included, and the deleted one is removed. * [preview](wp_customize_nav_menu_setting/preview) β€” Handle previewing the setting. * [sanitize](wp_customize_nav_menu_setting/sanitize) β€” Sanitize an input. * [update](wp_customize_nav_menu_setting/update) β€” Create/update the nav\_menu term for this setting. * [value](wp_customize_nav_menu_setting/value) β€” Get the instance data for a given widget setting. File: `wp-includes/customize/class-wp-customize-nav-menu-setting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-setting.php/) ``` class WP_Customize_Nav_Menu_Setting extends WP_Customize_Setting { const ID_PATTERN = '/^nav_menu\[(?P<id>-?\d+)\]$/'; const TAXONOMY = 'nav_menu'; const TYPE = 'nav_menu'; /** * Setting type. * * @since 4.3.0 * @var string */ public $type = self::TYPE; /** * Default setting value. * * @since 4.3.0 * @var array * * @see wp_get_nav_menu_object() */ public $default = array( 'name' => '', 'description' => '', 'parent' => 0, 'auto_add' => false, ); /** * Default transport. * * @since 4.3.0 * @var string */ public $transport = 'postMessage'; /** * The term ID represented by this setting instance. * * A negative value represents a placeholder ID for a new menu not yet saved. * * @since 4.3.0 * @var int */ public $term_id; /** * Previous (placeholder) term ID used before creating a new menu. * * This value will be exported to JS via the {@see 'customize_save_response'} filter * so that JavaScript can update the settings to refer to the newly-assigned * term ID. This value is always negative to indicate it does not refer to * a real term. * * @since 4.3.0 * @var int * * @see WP_Customize_Nav_Menu_Setting::update() * @see WP_Customize_Nav_Menu_Setting::amend_customize_save_response() */ public $previous_term_id; /** * Whether or not update() was called. * * @since 4.3.0 * @var bool */ protected $is_updated = false; /** * Status for calling the update method, used in customize_save_response filter. * * See {@see 'customize_save_response'}. * * When status is inserted, the placeholder term ID is stored in `$previous_term_id`. * When status is error, the error is stored in `$update_error`. * * @since 4.3.0 * @var string updated|inserted|deleted|error * * @see WP_Customize_Nav_Menu_Setting::update() * @see WP_Customize_Nav_Menu_Setting::amend_customize_save_response() */ public $update_status; /** * Any error object returned by wp_update_nav_menu_object() when setting is updated. * * @since 4.3.0 * @var WP_Error * * @see WP_Customize_Nav_Menu_Setting::update() * @see WP_Customize_Nav_Menu_Setting::amend_customize_save_response() */ public $update_error; /** * Constructor. * * Any supplied $args override class property defaults. * * @since 4.3.0 * * @throws Exception If $id is not valid for this setting type. * * @param WP_Customize_Manager $manager Customizer bootstrap instance. * @param string $id A specific ID of the setting. * Can be a theme mod or option name. * @param array $args Optional. Setting arguments. */ public function __construct( WP_Customize_Manager $manager, $id, array $args = array() ) { if ( empty( $manager->nav_menus ) ) { throw new Exception( 'Expected WP_Customize_Manager::$nav_menus to be set.' ); } if ( ! preg_match( self::ID_PATTERN, $id, $matches ) ) { throw new Exception( "Illegal widget setting ID: $id" ); } $this->term_id = (int) $matches['id']; parent::__construct( $manager, $id, $args ); } /** * Get the instance data for a given widget setting. * * @since 4.3.0 * * @see wp_get_nav_menu_object() * * @return array Instance data. */ public function value() { if ( $this->is_previewed && get_current_blog_id() === $this->_previewed_blog_id ) { $undefined = new stdClass(); // Symbol. $post_value = $this->post_value( $undefined ); if ( $undefined === $post_value ) { $value = $this->_original_value; } else { $value = $post_value; } } else { $value = false; // Note that a term_id of less than one indicates a nav_menu not yet inserted. if ( $this->term_id > 0 ) { $term = wp_get_nav_menu_object( $this->term_id ); if ( $term ) { $value = wp_array_slice_assoc( (array) $term, array_keys( $this->default ) ); $nav_menu_options = (array) get_option( 'nav_menu_options', array() ); $value['auto_add'] = false; if ( isset( $nav_menu_options['auto_add'] ) && is_array( $nav_menu_options['auto_add'] ) ) { $value['auto_add'] = in_array( $term->term_id, $nav_menu_options['auto_add'], true ); } } } if ( ! is_array( $value ) ) { $value = $this->default; } } return $value; } /** * Handle previewing the setting. * * @since 4.3.0 * @since 4.4.0 Added boolean return value * * @see WP_Customize_Manager::post_value() * * @return bool False if method short-circuited due to no-op. */ public function preview() { if ( $this->is_previewed ) { return false; } $undefined = new stdClass(); $is_placeholder = ( $this->term_id < 0 ); $is_dirty = ( $undefined !== $this->post_value( $undefined ) ); if ( ! $is_placeholder && ! $is_dirty ) { return false; } $this->is_previewed = true; $this->_original_value = $this->value(); $this->_previewed_blog_id = get_current_blog_id(); add_filter( 'wp_get_nav_menus', array( $this, 'filter_wp_get_nav_menus' ), 10, 2 ); add_filter( 'wp_get_nav_menu_object', array( $this, 'filter_wp_get_nav_menu_object' ), 10, 2 ); add_filter( 'default_option_nav_menu_options', array( $this, 'filter_nav_menu_options' ) ); add_filter( 'option_nav_menu_options', array( $this, 'filter_nav_menu_options' ) ); return true; } /** * Filters the wp_get_nav_menus() result to ensure the inserted menu object is included, and the deleted one is removed. * * @since 4.3.0 * * @see wp_get_nav_menus() * * @param WP_Term[] $menus An array of menu objects. * @param array $args An array of arguments used to retrieve menu objects. * @return WP_Term[] Array of menu objects. */ public function filter_wp_get_nav_menus( $menus, $args ) { if ( get_current_blog_id() !== $this->_previewed_blog_id ) { return $menus; } $setting_value = $this->value(); $is_delete = ( false === $setting_value ); $index = -1; // Find the existing menu item's position in the list. foreach ( $menus as $i => $menu ) { if ( (int) $this->term_id === (int) $menu->term_id || (int) $this->previous_term_id === (int) $menu->term_id ) { $index = $i; break; } } if ( $is_delete ) { // Handle deleted menu by removing it from the list. if ( -1 !== $index ) { array_splice( $menus, $index, 1 ); } } else { // Handle menus being updated or inserted. $menu_obj = (object) array_merge( array( 'term_id' => $this->term_id, 'term_taxonomy_id' => $this->term_id, 'slug' => sanitize_title( $setting_value['name'] ), 'count' => 0, 'term_group' => 0, 'taxonomy' => self::TAXONOMY, 'filter' => 'raw', ), $setting_value ); array_splice( $menus, $index, ( -1 === $index ? 0 : 1 ), array( $menu_obj ) ); } // Make sure the menu objects get re-sorted after an update/insert. if ( ! $is_delete && ! empty( $args['orderby'] ) ) { $menus = wp_list_sort( $menus, array( $args['orderby'] => 'ASC', ) ); } // @todo Add support for $args['hide_empty'] === true. return $menus; } /** * Temporary non-closure passing of orderby value to function. * * @since 4.3.0 * @var string * * @see WP_Customize_Nav_Menu_Setting::filter_wp_get_nav_menus() * @see WP_Customize_Nav_Menu_Setting::_sort_menus_by_orderby() */ protected $_current_menus_sort_orderby; /** * Sort menu objects by the class-supplied orderby property. * * This is a workaround for a lack of closures. * * @since 4.3.0 * @deprecated 4.7.0 Use wp_list_sort() * * @param object $menu1 * @param object $menu2 * @return int * * @see WP_Customize_Nav_Menu_Setting::filter_wp_get_nav_menus() */ protected function _sort_menus_by_orderby( $menu1, $menu2 ) { _deprecated_function( __METHOD__, '4.7.0', 'wp_list_sort' ); $key = $this->_current_menus_sort_orderby; return strcmp( $menu1->$key, $menu2->$key ); } /** * Filters the wp_get_nav_menu_object() result to supply the previewed menu object. * * Requesting a nav_menu object by anything but ID is not supported. * * @since 4.3.0 * * @see wp_get_nav_menu_object() * * @param object|null $menu_obj Object returned by wp_get_nav_menu_object(). * @param string $menu_id ID of the nav_menu term. Requests by slug or name will be ignored. * @return object|null */ public function filter_wp_get_nav_menu_object( $menu_obj, $menu_id ) { $ok = ( get_current_blog_id() === $this->_previewed_blog_id && is_int( $menu_id ) && $menu_id === $this->term_id ); if ( ! $ok ) { return $menu_obj; } $setting_value = $this->value(); // Handle deleted menus. if ( false === $setting_value ) { return false; } // Handle sanitization failure by preventing short-circuiting. if ( null === $setting_value ) { return $menu_obj; } $menu_obj = (object) array_merge( array( 'term_id' => $this->term_id, 'term_taxonomy_id' => $this->term_id, 'slug' => sanitize_title( $setting_value['name'] ), 'count' => 0, 'term_group' => 0, 'taxonomy' => self::TAXONOMY, 'filter' => 'raw', ), $setting_value ); return $menu_obj; } /** * Filters the nav_menu_options option to include this menu's auto_add preference. * * @since 4.3.0 * * @param array $nav_menu_options Nav menu options including auto_add. * @return array (Maybe) modified nav menu options. */ public function filter_nav_menu_options( $nav_menu_options ) { if ( get_current_blog_id() !== $this->_previewed_blog_id ) { return $nav_menu_options; } $menu = $this->value(); $nav_menu_options = $this->filter_nav_menu_options_value( $nav_menu_options, $this->term_id, false === $menu ? false : $menu['auto_add'] ); return $nav_menu_options; } /** * Sanitize an input. * * Note that parent::sanitize() erroneously does wp_unslash() on $value, but * we remove that in this override. * * @since 4.3.0 * * @param array $value The menu value to sanitize. * @return array|false|null Null if an input isn't valid. False if it is marked for deletion. * Otherwise the sanitized value. */ public function sanitize( $value ) { // Menu is marked for deletion. if ( false === $value ) { return $value; } // Invalid. if ( ! is_array( $value ) ) { return null; } $default = array( 'name' => '', 'description' => '', 'parent' => 0, 'auto_add' => false, ); $value = array_merge( $default, $value ); $value = wp_array_slice_assoc( $value, array_keys( $default ) ); $value['name'] = trim( esc_html( $value['name'] ) ); // This sanitization code is used in wp-admin/nav-menus.php. $value['description'] = sanitize_text_field( $value['description'] ); $value['parent'] = max( 0, (int) $value['parent'] ); $value['auto_add'] = ! empty( $value['auto_add'] ); if ( '' === $value['name'] ) { $value['name'] = _x( '(unnamed)', 'Missing menu name.' ); } /** This filter is documented in wp-includes/class-wp-customize-setting.php */ return apply_filters( "customize_sanitize_{$this->id}", $value, $this ); } /** * Storage for data to be sent back to client in customize_save_response filter. * * See {@see 'customize_save_response'}. * * @since 4.3.0 * @var array * * @see WP_Customize_Nav_Menu_Setting::amend_customize_save_response() */ protected $_widget_nav_menu_updates = array(); /** * Create/update the nav_menu term for this setting. * * Any created menus will have their assigned term IDs exported to the client * via the {@see 'customize_save_response'} filter. Likewise, any errors will be exported * to the client via the customize_save_response() filter. * * To delete a menu, the client can send false as the value. * * @since 4.3.0 * * @see wp_update_nav_menu_object() * * @param array|false $value { * The value to update. Note that slug cannot be updated via wp_update_nav_menu_object(). * If false, then the menu will be deleted entirely. * * @type string $name The name of the menu to save. * @type string $description The term description. Default empty string. * @type int $parent The id of the parent term. Default 0. * @type bool $auto_add Whether pages will auto_add to this menu. Default false. * } * @return null|void */ protected function update( $value ) { if ( $this->is_updated ) { return; } $this->is_updated = true; $is_placeholder = ( $this->term_id < 0 ); $is_delete = ( false === $value ); add_filter( 'customize_save_response', array( $this, 'amend_customize_save_response' ) ); $auto_add = null; if ( $is_delete ) { // If the current setting term is a placeholder, a delete request is a no-op. if ( $is_placeholder ) { $this->update_status = 'deleted'; } else { $r = wp_delete_nav_menu( $this->term_id ); if ( is_wp_error( $r ) ) { $this->update_status = 'error'; $this->update_error = $r; } else { $this->update_status = 'deleted'; $auto_add = false; } } } else { // Insert or update menu. $menu_data = wp_array_slice_assoc( $value, array( 'description', 'parent' ) ); $menu_data['menu-name'] = $value['name']; $menu_id = $is_placeholder ? 0 : $this->term_id; $r = wp_update_nav_menu_object( $menu_id, wp_slash( $menu_data ) ); $original_name = $menu_data['menu-name']; $name_conflict_suffix = 1; while ( is_wp_error( $r ) && 'menu_exists' === $r->get_error_code() ) { $name_conflict_suffix += 1; /* translators: 1: Original menu name, 2: Duplicate count. */ $menu_data['menu-name'] = sprintf( __( '%1$s (%2$d)' ), $original_name, $name_conflict_suffix ); $r = wp_update_nav_menu_object( $menu_id, wp_slash( $menu_data ) ); } if ( is_wp_error( $r ) ) { $this->update_status = 'error'; $this->update_error = $r; } else { if ( $is_placeholder ) { $this->previous_term_id = $this->term_id; $this->term_id = $r; $this->update_status = 'inserted'; } else { $this->update_status = 'updated'; } $auto_add = $value['auto_add']; } } if ( null !== $auto_add ) { $nav_menu_options = $this->filter_nav_menu_options_value( (array) get_option( 'nav_menu_options', array() ), $this->term_id, $auto_add ); update_option( 'nav_menu_options', $nav_menu_options ); } if ( 'inserted' === $this->update_status ) { // Make sure that new menus assigned to nav menu locations use their new IDs. foreach ( $this->manager->settings() as $setting ) { if ( ! preg_match( '/^nav_menu_locations\[/', $setting->id ) ) { continue; } $post_value = $setting->post_value( null ); if ( ! is_null( $post_value ) && (int) $post_value === $this->previous_term_id ) { $this->manager->set_post_value( $setting->id, $this->term_id ); $setting->save(); } } // Make sure that any nav_menu widgets referencing the placeholder nav menu get updated and sent back to client. foreach ( array_keys( $this->manager->unsanitized_post_values() ) as $setting_id ) { $nav_menu_widget_setting = $this->manager->get_setting( $setting_id ); if ( ! $nav_menu_widget_setting || ! preg_match( '/^widget_nav_menu\[/', $nav_menu_widget_setting->id ) ) { continue; } $widget_instance = $nav_menu_widget_setting->post_value(); // Note that this calls WP_Customize_Widgets::sanitize_widget_instance(). if ( empty( $widget_instance['nav_menu'] ) || (int) $widget_instance['nav_menu'] !== $this->previous_term_id ) { continue; } $widget_instance['nav_menu'] = $this->term_id; $updated_widget_instance = $this->manager->widgets->sanitize_widget_js_instance( $widget_instance ); $this->manager->set_post_value( $nav_menu_widget_setting->id, $updated_widget_instance ); $nav_menu_widget_setting->save(); $this->_widget_nav_menu_updates[ $nav_menu_widget_setting->id ] = $updated_widget_instance; } } } /** * Updates a nav_menu_options array. * * @since 4.3.0 * * @see WP_Customize_Nav_Menu_Setting::filter_nav_menu_options() * @see WP_Customize_Nav_Menu_Setting::update() * * @param array $nav_menu_options Array as returned by get_option( 'nav_menu_options' ). * @param int $menu_id The term ID for the given menu. * @param bool $auto_add Whether to auto-add or not. * @return array (Maybe) modified nav_menu_options array. */ protected function filter_nav_menu_options_value( $nav_menu_options, $menu_id, $auto_add ) { $nav_menu_options = (array) $nav_menu_options; if ( ! isset( $nav_menu_options['auto_add'] ) ) { $nav_menu_options['auto_add'] = array(); } $i = array_search( $menu_id, $nav_menu_options['auto_add'], true ); if ( $auto_add && false === $i ) { array_push( $nav_menu_options['auto_add'], $this->term_id ); } elseif ( ! $auto_add && false !== $i ) { array_splice( $nav_menu_options['auto_add'], $i, 1 ); } return $nav_menu_options; } /** * Export data for the JS client. * * @since 4.3.0 * * @see WP_Customize_Nav_Menu_Setting::update() * * @param array $data Additional information passed back to the 'saved' event on `wp.customize`. * @return array Export data. */ public function amend_customize_save_response( $data ) { if ( ! isset( $data['nav_menu_updates'] ) ) { $data['nav_menu_updates'] = array(); } if ( ! isset( $data['widget_nav_menu_updates'] ) ) { $data['widget_nav_menu_updates'] = array(); } $data['nav_menu_updates'][] = array( 'term_id' => $this->term_id, 'previous_term_id' => $this->previous_term_id, 'error' => $this->update_error ? $this->update_error->get_error_code() : null, 'status' => $this->update_status, 'saved_value' => 'deleted' === $this->update_status ? null : $this->value(), ); $data['widget_nav_menu_updates'] = array_merge( $data['widget_nav_menu_updates'], $this->_widget_nav_menu_updates ); $this->_widget_nav_menu_updates = array(); return $data; } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Setting](wp_customize_setting) wp-includes/class-wp-customize-setting.php | Customize Setting class. | | Version | Description | | --- | --- | | [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
programming_docs
wordpress class WP_Hook {} class WP\_Hook {} ================= Core class used to implement action and filter hook functionality. * [Iterator](../functions/iterator) * [ArrayAccess](../functions/arrayaccess) * [add\_filter](wp_hook/add_filter) β€” Adds a callback function to a filter hook. * [apply\_filters](wp_hook/apply_filters) β€” Calls the callback functions that have been added to a filter hook. * [build\_preinitialized\_hooks](wp_hook/build_preinitialized_hooks) β€” Normalizes filters set up before WordPress has initialized to WP\_Hook objects. * [current](wp_hook/current) * [current\_priority](wp_hook/current_priority) β€” Return the current priority level of the currently running iteration of the hook. * [do\_action](wp_hook/do_action) β€” Calls the callback functions that have been added to an action hook. * [do\_all\_hook](wp_hook/do_all_hook) β€” Processes the functions hooked into the 'all' hook. * [has\_filter](wp_hook/has_filter) β€” Checks if a specific callback has been registered for this hook. * [has\_filters](wp_hook/has_filters) β€” Checks if any callbacks have been registered for this hook. * [key](wp_hook/key) * [next](wp_hook/next) * [offsetExists](wp_hook/offsetexists) * [offsetGet](wp_hook/offsetget) * [offsetSet](wp_hook/offsetset) * [offsetUnset](wp_hook/offsetunset) * [remove\_all\_filters](wp_hook/remove_all_filters) β€” Removes all callbacks from the current filter. * [remove\_filter](wp_hook/remove_filter) β€” Removes a callback function from a filter hook. * [resort\_active\_iterations](wp_hook/resort_active_iterations) β€” Handles resetting callback priority keys mid-iteration. * [rewind](wp_hook/rewind) * [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/) ``` final class WP_Hook implements Iterator, ArrayAccess { /** * Hook callbacks. * * @since 4.7.0 * @var array */ public $callbacks = array(); /** * The priority keys of actively running iterations of a hook. * * @since 4.7.0 * @var array */ private $iterations = array(); /** * The current priority of actively running iterations of a hook. * * @since 4.7.0 * @var array */ private $current_priority = array(); /** * Number of levels this hook can be recursively called. * * @since 4.7.0 * @var int */ private $nesting_level = 0; /** * Flag for if we're currently doing an action, rather than a filter. * * @since 4.7.0 * @var bool */ private $doing_action = false; /** * Adds a callback function to a filter hook. * * @since 4.7.0 * * @param string $hook_name The name of the filter to add the callback to. * @param callable $callback The callback to be run when the filter is applied. * @param int $priority 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. * @param int $accepted_args The number of arguments the function accepts. */ 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 ); } } /** * Handles resetting callback priority keys mid-iteration. * * @since 4.7.0 * * @param false|int $new_priority Optional. The priority of the new filter being added. Default false, * for no priority being added. * @param bool $priority_existed Optional. Flag for whether the priority already existed before the new * filter was added. Default false. */ 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 ); } /** * Removes a callback function from a filter hook. * * @since 4.7.0 * * @param string $hook_name The filter hook to which the function to be removed is hooked. * @param callable|string|array $callback 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. * @param int $priority The exact priority used when adding the original filter callback. * @return bool Whether the callback existed before it was removed. */ 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; } /** * 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. * * @since 4.7.0 * * @param string $hook_name Optional. The name of the filter hook. Default empty. * @param callable|string|array|false $callback 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. * @return 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. */ 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; } /** * Checks if any callbacks have been registered for this hook. * * @since 4.7.0 * * @return bool True if callbacks have been registered for the current hook, otherwise false. */ public function has_filters() { foreach ( $this->callbacks as $callbacks ) { if ( $callbacks ) { return true; } } return false; } /** * Removes all callbacks from the current filter. * * @since 4.7.0 * * @param int|false $priority Optional. The priority number to remove. Default false. */ 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(); } } /** * Calls the callback functions that have been added to a filter hook. * * @since 4.7.0 * * @param mixed $value The value to filter. * @param array $args Additional parameters to pass to the callback functions. * This array is expected to include $value at index 0. * @return mixed The filtered value after all hooked functions are applied to it. */ 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; } /** * Calls the callback functions that have been added to an action hook. * * @since 4.7.0 * * @param array $args Parameters to pass to the callback functions. */ 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; } } /** * Processes the functions hooked into the 'all' hook. * * @since 4.7.0 * * @param array $args Arguments to pass to the hook callbacks. Passed by reference. */ 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--; } /** * Return the current priority level of the currently running iteration of the hook. * * @since 4.7.0 * * @return int|false If the hook is running, return the current priority level. * If it isn't running, return false. */ public function current_priority() { if ( false === current( $this->iterations ) ) { return false; } return current( current( $this->iterations ) ); } /** * Normalizes filters set up before WordPress has initialized to 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; * }, * ), * ), * ), * ); * * @since 4.7.0 * * @param array $filters Filters to normalize. See documentation above for details. * @return WP_Hook[] Array of normalized filters. */ 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; } /** * Determines whether an offset value exists. * * @since 4.7.0 * * @link https://www.php.net/manual/en/arrayaccess.offsetexists.php * * @param mixed $offset An offset to check for. * @return bool True if the offset exists, false otherwise. */ #[ReturnTypeWillChange] public function offsetExists( $offset ) { return isset( $this->callbacks[ $offset ] ); } /** * Retrieves a value at a specified offset. * * @since 4.7.0 * * @link https://www.php.net/manual/en/arrayaccess.offsetget.php * * @param mixed $offset The offset to retrieve. * @return mixed If set, the value at the specified offset, null otherwise. */ #[ReturnTypeWillChange] public function offsetGet( $offset ) { return isset( $this->callbacks[ $offset ] ) ? $this->callbacks[ $offset ] : null; } /** * Sets a value at a specified offset. * * @since 4.7.0 * * @link https://www.php.net/manual/en/arrayaccess.offsetset.php * * @param mixed $offset The offset to assign the value to. * @param mixed $value The value to set. */ #[ReturnTypeWillChange] public function offsetSet( $offset, $value ) { if ( is_null( $offset ) ) { $this->callbacks[] = $value; } else { $this->callbacks[ $offset ] = $value; } } /** * Unsets a specified offset. * * @since 4.7.0 * * @link https://www.php.net/manual/en/arrayaccess.offsetunset.php * * @param mixed $offset The offset to unset. */ #[ReturnTypeWillChange] public function offsetUnset( $offset ) { unset( $this->callbacks[ $offset ] ); } /** * Returns the current element. * * @since 4.7.0 * * @link https://www.php.net/manual/en/iterator.current.php * * @return array Of callbacks at current priority. */ #[ReturnTypeWillChange] public function current() { return current( $this->callbacks ); } /** * Moves forward to the next element. * * @since 4.7.0 * * @link https://www.php.net/manual/en/iterator.next.php * * @return array Of callbacks at next priority. */ #[ReturnTypeWillChange] public function next() { return next( $this->callbacks ); } /** * Returns the key of the current element. * * @since 4.7.0 * * @link https://www.php.net/manual/en/iterator.key.php * * @return mixed Returns current priority on success, or NULL on failure */ #[ReturnTypeWillChange] public function key() { return key( $this->callbacks ); } /** * Checks if current position is valid. * * @since 4.7.0 * * @link https://www.php.net/manual/en/iterator.valid.php * * @return bool Whether the current position is valid. */ #[ReturnTypeWillChange] public function valid() { return key( $this->callbacks ) !== null; } /** * Rewinds the Iterator to the first element. * * @since 4.7.0 * * @link https://www.php.net/manual/en/iterator.rewind.php */ #[ReturnTypeWillChange] public function rewind() { reset( $this->callbacks ); } } ``` | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. | wordpress class WP_REST_Plugins_Controller {} class WP\_REST\_Plugins\_Controller {} ====================================== Core class to access plugins via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_plugins_controller/__construct) β€” Plugins controller constructor. * [check\_read\_permission](wp_rest_plugins_controller/check_read_permission) β€” Checks if the given plugin can be viewed by the current user. * [create\_item](wp_rest_plugins_controller/create_item) β€” Uploads a plugin and optionally activates it. * [create\_item\_permissions\_check](wp_rest_plugins_controller/create_item_permissions_check) β€” Checks if a given request has access to upload plugins. * [delete\_item](wp_rest_plugins_controller/delete_item) β€” Deletes one plugin from the site. * [delete\_item\_permissions\_check](wp_rest_plugins_controller/delete_item_permissions_check) β€” Checks if a given request has access to delete a specific plugin. * [does\_plugin\_match\_request](wp_rest_plugins_controller/does_plugin_match_request) β€” Checks if the plugin matches the requested parameters. * [get\_collection\_params](wp_rest_plugins_controller/get_collection_params) β€” Retrieves the query params for the collections. * [get\_item](wp_rest_plugins_controller/get_item) β€” Retrieves one plugin from the site. * [get\_item\_permissions\_check](wp_rest_plugins_controller/get_item_permissions_check) β€” Checks if a given request has access to get a specific plugin. * [get\_item\_schema](wp_rest_plugins_controller/get_item_schema) β€” Retrieves the plugin's schema, conforming to JSON Schema. * [get\_items](wp_rest_plugins_controller/get_items) β€” Retrieves a collection of plugins. * [get\_items\_permissions\_check](wp_rest_plugins_controller/get_items_permissions_check) β€” Checks if a given request has access to get plugins. * [get\_plugin\_data](wp_rest_plugins_controller/get_plugin_data) β€” Gets the plugin header data for a plugin. * [get\_plugin\_status](wp_rest_plugins_controller/get_plugin_status) β€” Get's the activation status for a plugin. * [handle\_plugin\_status](wp_rest_plugins_controller/handle_plugin_status) β€” Handle updating a plugin's status. * [is\_filesystem\_available](wp_rest_plugins_controller/is_filesystem_available) β€” Determine if the endpoints are available. * [is\_plugin\_installed](wp_rest_plugins_controller/is_plugin_installed) β€” Checks if the plugin is installed. * [plugin\_status\_permission\_check](wp_rest_plugins_controller/plugin_status_permission_check) β€” Handle updating a plugin's status. * [prepare\_item\_for\_response](wp_rest_plugins_controller/prepare_item_for_response) β€” Prepares the plugin for the REST response. * [prepare\_links](wp_rest_plugins_controller/prepare_links) β€” Prepares links for the request. * [register\_routes](wp_rest_plugins_controller/register_routes) β€” Registers the routes for the plugins controller. * [sanitize\_plugin\_param](wp_rest_plugins_controller/sanitize_plugin_param) β€” Sanitizes the "plugin" parameter to be a proper plugin file with ".php" appended. * [update\_item](wp_rest_plugins_controller/update_item) β€” Updates one plugin. * [update\_item\_permissions\_check](wp_rest_plugins_controller/update_item_permissions_check) β€” Checks if a given request has access to update a specific plugin. * [validate\_plugin\_param](wp_rest_plugins_controller/validate_plugin_param) β€” Checks that the "plugin" parameter is a valid path. File: `wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php/) ``` class WP_REST_Plugins_Controller extends WP_REST_Controller { const PATTERN = '[^.\/]+(?:\/[^.\/]+)?'; /** * Plugins controller constructor. * * @since 5.5.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'plugins'; } /** * Registers the routes for the plugins controller. * * @since 5.5.0 */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => $this->get_collection_params(), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'create_item' ), 'permission_callback' => array( $this, 'create_item_permissions_check' ), 'args' => array( 'slug' => array( 'type' => 'string', 'required' => true, 'description' => __( 'WordPress.org plugin directory slug.' ), 'pattern' => '[\w\-]+', ), 'status' => array( 'description' => __( 'The plugin activation status.' ), 'type' => 'string', 'enum' => is_multisite() ? array( 'inactive', 'active', 'network-active' ) : array( 'inactive', 'active' ), 'default' => 'inactive', ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<plugin>' . self::PATTERN . ')', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'permission_callback' => array( $this, 'get_item_permissions_check' ), ), array( 'methods' => WP_REST_Server::EDITABLE, 'callback' => array( $this, 'update_item' ), 'permission_callback' => array( $this, 'update_item_permissions_check' ), 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ), ), array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => array( $this, 'delete_item' ), 'permission_callback' => array( $this, 'delete_item_permissions_check' ), ), 'args' => array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), 'plugin' => array( 'type' => 'string', 'pattern' => self::PATTERN, 'validate_callback' => array( $this, 'validate_plugin_param' ), 'sanitize_callback' => array( $this, 'sanitize_plugin_param' ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks if a given request has access to get plugins. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { if ( ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( 'rest_cannot_view_plugins', __( 'Sorry, you are not allowed to manage plugins for this site.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Retrieves a collection of plugins. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; $plugins = array(); foreach ( get_plugins() as $file => $data ) { if ( is_wp_error( $this->check_read_permission( $file ) ) ) { continue; } $data['_file'] = $file; if ( ! $this->does_plugin_match_request( $request, $data ) ) { continue; } $plugins[] = $this->prepare_response_for_collection( $this->prepare_item_for_response( $data, $request ) ); } return new WP_REST_Response( $plugins ); } /** * Checks if a given request has access to get a specific plugin. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise. */ public function get_item_permissions_check( $request ) { if ( ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( 'rest_cannot_view_plugin', __( 'Sorry, you are not allowed to manage plugins for this site.' ), array( 'status' => rest_authorization_required_code() ) ); } $can_read = $this->check_read_permission( $request['plugin'] ); if ( is_wp_error( $can_read ) ) { return $can_read; } return true; } /** * Retrieves one plugin from the site. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; $data = $this->get_plugin_data( $request['plugin'] ); if ( is_wp_error( $data ) ) { return $data; } return $this->prepare_item_for_response( $data, $request ); } /** * Checks if the given plugin can be viewed by the current user. * * On multisite, this hides non-active network only plugins if the user does not have permission * to manage network plugins. * * @since 5.5.0 * * @param string $plugin The plugin file to check. * @return true|WP_Error True if can read, a WP_Error instance otherwise. */ protected function check_read_permission( $plugin ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; if ( ! $this->is_plugin_installed( $plugin ) ) { return new WP_Error( 'rest_plugin_not_found', __( 'Plugin not found.' ), array( 'status' => 404 ) ); } if ( ! is_multisite() ) { return true; } if ( ! is_network_only_plugin( $plugin ) || is_plugin_active( $plugin ) || current_user_can( 'manage_network_plugins' ) ) { return true; } return new WP_Error( 'rest_cannot_view_plugin', __( 'Sorry, you are not allowed to manage this plugin.' ), array( 'status' => rest_authorization_required_code() ) ); } /** * Checks if a given request has access to upload plugins. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise. */ public function create_item_permissions_check( $request ) { if ( ! current_user_can( 'install_plugins' ) ) { return new WP_Error( 'rest_cannot_install_plugin', __( 'Sorry, you are not allowed to install plugins on this site.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( 'inactive' !== $request['status'] && ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( 'rest_cannot_activate_plugin', __( 'Sorry, you are not allowed to activate plugins.' ), array( 'status' => rest_authorization_required_code(), ) ); } return true; } /** * Uploads a plugin and optionally activates it. * * @since 5.5.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function create_item( $request ) { global $wp_filesystem; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/plugin.php'; require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; require_once ABSPATH . 'wp-admin/includes/plugin-install.php'; $slug = $request['slug']; // Verify filesystem is accessible first. $filesystem_available = $this->is_filesystem_available(); if ( is_wp_error( $filesystem_available ) ) { return $filesystem_available; } $api = plugins_api( 'plugin_information', array( 'slug' => $slug, 'fields' => array( 'sections' => false, 'language_packs' => true, ), ) ); if ( is_wp_error( $api ) ) { if ( false !== strpos( $api->get_error_message(), 'Plugin not found.' ) ) { $api->add_data( array( 'status' => 404 ) ); } else { $api->add_data( array( 'status' => 500 ) ); } return $api; } $skin = new WP_Ajax_Upgrader_Skin(); $upgrader = new Plugin_Upgrader( $skin ); $result = $upgrader->install( $api->download_link ); if ( is_wp_error( $result ) ) { $result->add_data( array( 'status' => 500 ) ); return $result; } // This should be the same as $result above. if ( is_wp_error( $skin->result ) ) { $skin->result->add_data( array( 'status' => 500 ) ); return $skin->result; } if ( $skin->get_errors()->has_errors() ) { $error = $skin->get_errors(); $error->add_data( array( 'status' => 500 ) ); return $error; } if ( is_null( $result ) ) { // Pass through the error from WP_Filesystem if one was raised. if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) { return new WP_Error( 'unable_to_connect_to_filesystem', $wp_filesystem->errors->get_error_message(), array( 'status' => 500 ) ); } return new WP_Error( 'unable_to_connect_to_filesystem', __( 'Unable to connect to the filesystem. Please confirm your credentials.' ), array( 'status' => 500 ) ); } $file = $upgrader->plugin_info(); if ( ! $file ) { return new WP_Error( 'unable_to_determine_installed_plugin', __( 'Unable to determine what plugin was installed.' ), array( 'status' => 500 ) ); } if ( 'inactive' !== $request['status'] ) { $can_change_status = $this->plugin_status_permission_check( $file, $request['status'], 'inactive' ); if ( is_wp_error( $can_change_status ) ) { return $can_change_status; } $changed_status = $this->handle_plugin_status( $file, $request['status'], 'inactive' ); if ( is_wp_error( $changed_status ) ) { return $changed_status; } } // Install translations. $installed_locales = array_values( get_available_languages() ); /** This filter is documented in wp-includes/update.php */ $installed_locales = apply_filters( 'plugins_update_check_locales', $installed_locales ); $language_packs = array_map( static function( $item ) { return (object) $item; }, $api->language_packs ); $language_packs = array_filter( $language_packs, static function( $pack ) use ( $installed_locales ) { return in_array( $pack->language, $installed_locales, true ); } ); if ( $language_packs ) { $lp_upgrader = new Language_Pack_Upgrader( $skin ); // Install all applicable language packs for the plugin. $lp_upgrader->bulk_upgrade( $language_packs ); } $path = WP_PLUGIN_DIR . '/' . $file; $data = get_plugin_data( $path, false, false ); $data['_file'] = $file; $response = $this->prepare_item_for_response( $data, $request ); $response->set_status( 201 ); $response->header( 'Location', rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, substr( $file, 0, - 4 ) ) ) ); return $response; } /** * Checks if a given request has access to update a specific plugin. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise. */ public function update_item_permissions_check( $request ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; if ( ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( 'rest_cannot_manage_plugins', __( 'Sorry, you are not allowed to manage plugins for this site.' ), array( 'status' => rest_authorization_required_code() ) ); } $can_read = $this->check_read_permission( $request['plugin'] ); if ( is_wp_error( $can_read ) ) { return $can_read; } $status = $this->get_plugin_status( $request['plugin'] ); if ( $request['status'] && $status !== $request['status'] ) { $can_change_status = $this->plugin_status_permission_check( $request['plugin'], $request['status'], $status ); if ( is_wp_error( $can_change_status ) ) { return $can_change_status; } } return true; } /** * Updates one plugin. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function update_item( $request ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; $data = $this->get_plugin_data( $request['plugin'] ); if ( is_wp_error( $data ) ) { return $data; } $status = $this->get_plugin_status( $request['plugin'] ); if ( $request['status'] && $status !== $request['status'] ) { $handled = $this->handle_plugin_status( $request['plugin'], $request['status'], $status ); if ( is_wp_error( $handled ) ) { return $handled; } } $this->update_additional_fields_for_object( $data, $request ); $request['context'] = 'edit'; return $this->prepare_item_for_response( $data, $request ); } /** * Checks if a given request has access to delete a specific plugin. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise. */ public function delete_item_permissions_check( $request ) { if ( ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( 'rest_cannot_manage_plugins', __( 'Sorry, you are not allowed to manage plugins for this site.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( ! current_user_can( 'delete_plugins' ) ) { return new WP_Error( 'rest_cannot_manage_plugins', __( 'Sorry, you are not allowed to delete plugins for this site.' ), array( 'status' => rest_authorization_required_code() ) ); } $can_read = $this->check_read_permission( $request['plugin'] ); if ( is_wp_error( $can_read ) ) { return $can_read; } return true; } /** * Deletes one plugin from the site. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function delete_item( $request ) { require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/plugin.php'; $data = $this->get_plugin_data( $request['plugin'] ); if ( is_wp_error( $data ) ) { return $data; } if ( is_plugin_active( $request['plugin'] ) ) { return new WP_Error( 'rest_cannot_delete_active_plugin', __( 'Cannot delete an active plugin. Please deactivate it first.' ), array( 'status' => 400 ) ); } $filesystem_available = $this->is_filesystem_available(); if ( is_wp_error( $filesystem_available ) ) { return $filesystem_available; } $prepared = $this->prepare_item_for_response( $data, $request ); $deleted = delete_plugins( array( $request['plugin'] ) ); if ( is_wp_error( $deleted ) ) { $deleted->add_data( array( 'status' => 500 ) ); return $deleted; } return new WP_REST_Response( array( 'deleted' => true, 'previous' => $prepared->get_data(), ) ); } /** * Prepares the plugin for the REST response. * * @since 5.5.0 * * @param array $item Unmarked up and untranslated plugin data from {@see get_plugin_data()}. * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function prepare_item_for_response( $item, $request ) { $fields = $this->get_fields_for_response( $request ); $item = _get_plugin_data_markup_translate( $item['_file'], $item, false ); $marked = _get_plugin_data_markup_translate( $item['_file'], $item, true ); $data = array( 'plugin' => substr( $item['_file'], 0, - 4 ), 'status' => $this->get_plugin_status( $item['_file'] ), 'name' => $item['Name'], 'plugin_uri' => $item['PluginURI'], 'author' => $item['Author'], 'author_uri' => $item['AuthorURI'], 'description' => array( 'raw' => $item['Description'], 'rendered' => $marked['Description'], ), 'version' => $item['Version'], 'network_only' => $item['Network'], 'requires_wp' => $item['RequiresWP'], 'requires_php' => $item['RequiresPHP'], 'textdomain' => $item['TextDomain'], ); $data = $this->add_additional_fields_to_object( $data, $request ); $response = new WP_REST_Response( $data ); if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { $response->add_links( $this->prepare_links( $item ) ); } /** * Filters plugin data for a REST API response. * * @since 5.5.0 * * @param WP_REST_Response $response The response object. * @param array $item The plugin item from {@see get_plugin_data()}. * @param WP_REST_Request $request The request object. */ return apply_filters( 'rest_prepare_plugin', $response, $item, $request ); } /** * Prepares links for the request. * * @since 5.5.0 * * @param array $item The plugin item. * @return array[] */ protected function prepare_links( $item ) { return array( 'self' => array( 'href' => rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, substr( $item['_file'], 0, - 4 ) ) ), ), ); } /** * Gets the plugin header data for a plugin. * * @since 5.5.0 * * @param string $plugin The plugin file to get data for. * @return array|WP_Error The plugin data, or a WP_Error if the plugin is not installed. */ protected function get_plugin_data( $plugin ) { $plugins = get_plugins(); if ( ! isset( $plugins[ $plugin ] ) ) { return new WP_Error( 'rest_plugin_not_found', __( 'Plugin not found.' ), array( 'status' => 404 ) ); } $data = $plugins[ $plugin ]; $data['_file'] = $plugin; return $data; } /** * Get's the activation status for a plugin. * * @since 5.5.0 * * @param string $plugin The plugin file to check. * @return string Either 'network-active', 'active' or 'inactive'. */ protected function get_plugin_status( $plugin ) { if ( is_plugin_active_for_network( $plugin ) ) { return 'network-active'; } if ( is_plugin_active( $plugin ) ) { return 'active'; } return 'inactive'; } /** * Handle updating a plugin's status. * * @since 5.5.0 * * @param string $plugin The plugin file to update. * @param string $new_status The plugin's new status. * @param string $current_status The plugin's current status. * @return true|WP_Error */ protected function plugin_status_permission_check( $plugin, $new_status, $current_status ) { if ( is_multisite() && ( 'network-active' === $current_status || 'network-active' === $new_status ) && ! current_user_can( 'manage_network_plugins' ) ) { return new WP_Error( 'rest_cannot_manage_network_plugins', __( 'Sorry, you are not allowed to manage network plugins.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( ( 'active' === $new_status || 'network-active' === $new_status ) && ! current_user_can( 'activate_plugin', $plugin ) ) { return new WP_Error( 'rest_cannot_activate_plugin', __( 'Sorry, you are not allowed to activate this plugin.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( 'inactive' === $new_status && ! current_user_can( 'deactivate_plugin', $plugin ) ) { return new WP_Error( 'rest_cannot_deactivate_plugin', __( 'Sorry, you are not allowed to deactivate this plugin.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Handle updating a plugin's status. * * @since 5.5.0 * * @param string $plugin The plugin file to update. * @param string $new_status The plugin's new status. * @param string $current_status The plugin's current status. * @return true|WP_Error */ protected function handle_plugin_status( $plugin, $new_status, $current_status ) { if ( 'inactive' === $new_status ) { deactivate_plugins( $plugin, false, 'network-active' === $current_status ); return true; } if ( 'active' === $new_status && 'network-active' === $current_status ) { return true; } $network_activate = 'network-active' === $new_status; if ( is_multisite() && ! $network_activate && is_network_only_plugin( $plugin ) ) { return new WP_Error( 'rest_network_only_plugin', __( 'Network only plugin must be network activated.' ), array( 'status' => 400 ) ); } $activated = activate_plugin( $plugin, '', $network_activate ); if ( is_wp_error( $activated ) ) { $activated->add_data( array( 'status' => 500 ) ); return $activated; } return true; } /** * Checks that the "plugin" parameter is a valid path. * * @since 5.5.0 * * @param string $file The plugin file parameter. * @return bool */ public function validate_plugin_param( $file ) { if ( ! is_string( $file ) || ! preg_match( '/' . self::PATTERN . '/u', $file ) ) { return false; } $validated = validate_file( plugin_basename( $file ) ); return 0 === $validated; } /** * Sanitizes the "plugin" parameter to be a proper plugin file with ".php" appended. * * @since 5.5.0 * * @param string $file The plugin file parameter. * @return string */ public function sanitize_plugin_param( $file ) { return plugin_basename( sanitize_text_field( $file . '.php' ) ); } /** * Checks if the plugin matches the requested parameters. * * @since 5.5.0 * * @param WP_REST_Request $request The request to require the plugin matches against. * @param array $item The plugin item. * @return bool */ protected function does_plugin_match_request( $request, $item ) { $search = $request['search']; if ( $search ) { $matched_search = false; foreach ( $item as $field ) { if ( is_string( $field ) && false !== strpos( strip_tags( $field ), $search ) ) { $matched_search = true; break; } } if ( ! $matched_search ) { return false; } } $status = $request['status']; if ( $status && ! in_array( $this->get_plugin_status( $item['_file'] ), $status, true ) ) { return false; } return true; } /** * Checks if the plugin is installed. * * @since 5.5.0 * * @param string $plugin The plugin file. * @return bool */ protected function is_plugin_installed( $plugin ) { return file_exists( WP_PLUGIN_DIR . '/' . $plugin ); } /** * Determine if the endpoints are available. * * Only the 'Direct' filesystem transport, and SSH/FTP when credentials are stored are supported at present. * * @since 5.5.0 * * @return true|WP_Error True if filesystem is available, WP_Error otherwise. */ protected function is_filesystem_available() { $filesystem_method = get_filesystem_method(); if ( 'direct' === $filesystem_method ) { return true; } ob_start(); $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() ); ob_end_clean(); if ( $filesystem_credentials_are_stored ) { return true; } return new WP_Error( 'fs_unavailable', __( 'The filesystem is currently unavailable for managing plugins.' ), array( 'status' => 500 ) ); } /** * Retrieves the plugin's schema, conforming to JSON Schema. * * @since 5.5.0 * * @return array Item schema data. */ public function get_item_schema() { if ( $this->schema ) { return $this->add_additional_fields_schema( $this->schema ); } $this->schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'plugin', 'type' => 'object', 'properties' => array( 'plugin' => array( 'description' => __( 'The plugin file.' ), 'type' => 'string', 'pattern' => self::PATTERN, 'readonly' => true, 'context' => array( 'view', 'edit', 'embed' ), ), 'status' => array( 'description' => __( 'The plugin activation status.' ), 'type' => 'string', 'enum' => is_multisite() ? array( 'inactive', 'active', 'network-active' ) : array( 'inactive', 'active' ), 'context' => array( 'view', 'edit', 'embed' ), ), 'name' => array( 'description' => __( 'The plugin name.' ), 'type' => 'string', 'readonly' => true, 'context' => array( 'view', 'edit', 'embed' ), ), 'plugin_uri' => array( 'description' => __( 'The plugin\'s website address.' ), 'type' => 'string', 'format' => 'uri', 'readonly' => true, 'context' => array( 'view', 'edit' ), ), 'author' => array( 'description' => __( 'The plugin author.' ), 'type' => 'object', 'readonly' => true, 'context' => array( 'view', 'edit' ), ), 'author_uri' => array( 'description' => __( 'Plugin author\'s website address.' ), 'type' => 'string', 'format' => 'uri', 'readonly' => true, 'context' => array( 'view', 'edit' ), ), 'description' => array( 'description' => __( 'The plugin description.' ), 'type' => 'object', 'readonly' => true, 'context' => array( 'view', 'edit' ), 'properties' => array( 'raw' => array( 'description' => __( 'The raw plugin description.' ), 'type' => 'string', ), 'rendered' => array( 'description' => __( 'The plugin description formatted for display.' ), 'type' => 'string', ), ), ), 'version' => array( 'description' => __( 'The plugin version number.' ), 'type' => 'string', 'readonly' => true, 'context' => array( 'view', 'edit' ), ), 'network_only' => array( 'description' => __( 'Whether the plugin can only be activated network-wide.' ), 'type' => 'boolean', 'readonly' => true, 'context' => array( 'view', 'edit', 'embed' ), ), 'requires_wp' => array( 'description' => __( 'Minimum required version of WordPress.' ), 'type' => 'string', 'readonly' => true, 'context' => array( 'view', 'edit', 'embed' ), ), 'requires_php' => array( 'description' => __( 'Minimum required version of PHP.' ), 'type' => 'string', 'readonly' => true, 'context' => array( 'view', 'edit', 'embed' ), ), 'textdomain' => array( 'description' => __( 'The plugin\'s text domain.' ), 'type' => 'string', 'readonly' => true, 'context' => array( 'view', 'edit' ), ), ), ); return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the query params for the collections. * * @since 5.5.0 * * @return array Query parameters for the collection. */ public function get_collection_params() { $query_params = parent::get_collection_params(); $query_params['context']['default'] = 'view'; $query_params['status'] = array( 'description' => __( 'Limits results to plugins with the given status.' ), 'type' => 'array', 'items' => array( 'type' => 'string', 'enum' => is_multisite() ? array( 'inactive', 'active', 'network-active' ) : array( 'inactive', 'active' ), ), ); unset( $query_params['page'], $query_params['per_page'] ); return $query_params; } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
programming_docs
wordpress class Requests_Exception_HTTP_416 {} class Requests\_Exception\_HTTP\_416 {} ======================================= Exception for 416 Requested Range Not Satisfiable responses File: `wp-includes/Requests/Exception/HTTP/416.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/416.php/) ``` class Requests_Exception_HTTP_416 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 416; /** * Reason phrase * * @var string */ protected $reason = 'Requested Range Not Satisfiable'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_HTTP_Proxy {} class WP\_HTTP\_Proxy {} ======================== Core class used to implement HTTP API proxy support. There are caveats to proxy support. It requires that defines be made in the wp-config.php file to enable proxy support. There are also a few filters that plugins can hook into for some of the constants. Please note that only BASIC authentication is supported by most transports. cURL MAY support more methods (such as NTLM authentication) depending on your environment. The constants are as follows: 1. WP\_PROXY\_HOST – Enable proxy support and host for connecting. 2. WP\_PROXY\_PORT – Proxy port for connection. No default, must be defined. 3. WP\_PROXY\_USERNAME – Proxy username, if it requires authentication. 4. WP\_PROXY\_PASSWORD – Proxy password, if it requires authentication. 5. WP\_PROXY\_BYPASS\_HOSTS – Will prevent the hosts in this list from going through the proxy. You do not need to have localhost and the site host in this list, because they will not be passed through the proxy. The list should be presented in a comma separated list, wildcards using \* are supported. Example: \*.wordpress.org An example can be as seen below. ``` define('WP_PROXY_HOST', '192.168.84.101'); define('WP_PROXY_PORT', '8080'); define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com, *.wordpress.org'); ``` * [authentication](wp_http_proxy/authentication) β€” Retrieve authentication string for proxy authentication. * [authentication\_header](wp_http_proxy/authentication_header) β€” Retrieve header string for proxy authentication. * [host](wp_http_proxy/host) β€” Retrieve the host for the proxy server. * [is\_enabled](wp_http_proxy/is_enabled) β€” Whether proxy connection should be used. * [password](wp_http_proxy/password) β€” Retrieve the password for proxy authentication. * [port](wp_http_proxy/port) β€” Retrieve the port for the proxy server. * [send\_through\_proxy](wp_http_proxy/send_through_proxy) β€” Determines whether the request should be sent through a proxy. * [use\_authentication](wp_http_proxy/use_authentication) β€” Whether authentication should be used. * [username](wp_http_proxy/username) β€” Retrieve the username for proxy authentication. File: `wp-includes/class-wp-http-proxy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-proxy.php/) ``` class WP_HTTP_Proxy { /** * Whether proxy connection should be used. * * Constants which control this behaviour: * * - `WP_PROXY_HOST` * - `WP_PROXY_PORT` * * @since 2.8.0 * * @return bool */ public function is_enabled() { return defined( 'WP_PROXY_HOST' ) && defined( 'WP_PROXY_PORT' ); } /** * Whether authentication should be used. * * Constants which control this behaviour: * * - `WP_PROXY_USERNAME` * - `WP_PROXY_PASSWORD` * * @since 2.8.0 * * @return bool */ public function use_authentication() { return defined( 'WP_PROXY_USERNAME' ) && defined( 'WP_PROXY_PASSWORD' ); } /** * Retrieve the host for the proxy server. * * @since 2.8.0 * * @return string */ public function host() { if ( defined( 'WP_PROXY_HOST' ) ) { return WP_PROXY_HOST; } return ''; } /** * Retrieve the port for the proxy server. * * @since 2.8.0 * * @return string */ public function port() { if ( defined( 'WP_PROXY_PORT' ) ) { return WP_PROXY_PORT; } return ''; } /** * Retrieve the username for proxy authentication. * * @since 2.8.0 * * @return string */ public function username() { if ( defined( 'WP_PROXY_USERNAME' ) ) { return WP_PROXY_USERNAME; } return ''; } /** * Retrieve the password for proxy authentication. * * @since 2.8.0 * * @return string */ public function password() { if ( defined( 'WP_PROXY_PASSWORD' ) ) { return WP_PROXY_PASSWORD; } return ''; } /** * Retrieve authentication string for proxy authentication. * * @since 2.8.0 * * @return string */ public function authentication() { return $this->username() . ':' . $this->password(); } /** * Retrieve header string for proxy authentication. * * @since 2.8.0 * * @return string */ public function authentication_header() { return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() ); } /** * Determines whether the request should be sent through a proxy. * * We want to keep localhost and the site URL from being sent through the proxy, because * some proxies can not handle this. We also have the constant available for defining other * hosts that won't be sent through the proxy. * * @since 2.8.0 * * @param string $uri URL of the request. * @return bool Whether to send the request through the proxy. */ public function send_through_proxy( $uri ) { $check = parse_url( $uri ); // Malformed URL, can not process, but this could mean ssl, so let through anyway. if ( false === $check ) { return true; } $home = parse_url( get_option( 'siteurl' ) ); /** * Filters whether to preempt sending the request through the proxy. * * Returning false will bypass the proxy; returning true will send * the request through the proxy. Returning null bypasses the filter. * * @since 3.5.0 * * @param bool|null $override Whether to send the request through the proxy. Default null. * @param string $uri URL of the request. * @param array $check Associative array result of parsing the request URL with `parse_url()`. * @param array $home Associative array result of parsing the site URL with `parse_url()`. */ $result = apply_filters( 'pre_http_send_through_proxy', null, $uri, $check, $home ); if ( ! is_null( $result ) ) { return $result; } if ( 'localhost' === $check['host'] || ( isset( $home['host'] ) && $home['host'] === $check['host'] ) ) { return false; } if ( ! defined( 'WP_PROXY_BYPASS_HOSTS' ) ) { return true; } static $bypass_hosts = null; static $wildcard_regex = array(); if ( null === $bypass_hosts ) { $bypass_hosts = preg_split( '|,\s*|', WP_PROXY_BYPASS_HOSTS ); if ( false !== strpos( WP_PROXY_BYPASS_HOSTS, '*' ) ) { $wildcard_regex = array(); foreach ( $bypass_hosts as $host ) { $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) ); } $wildcard_regex = '/^(' . implode( '|', $wildcard_regex ) . ')$/i'; } } if ( ! empty( $wildcard_regex ) ) { return ! preg_match( $wildcard_regex, $check['host'] ); } else { return ! in_array( $check['host'], $bypass_hosts, true ); } } } ``` | Version | Description | | --- | --- | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. | wordpress class WP_Screen {} class WP\_Screen {} =================== Core class used to implement an admin screen API. This is a concrete class that is instantiated in the WordPress $screen global. It is primarily used to create and customize WordPress admin screens (as of WordPress 3.3). Note: Please refer source code for the complete list of properties. The following properties are built into the [WP\_Screen](wp_screen) class. $action Any action associated with the screen. 'add' for \*-add.php and \*-new.php screens. Empty otherwise. $base The base type of the screen. This is typically the same as $id but with any post types and taxonomies stripped. For example, for an $id of 'edit-post' the base is 'edit'. $id The unique ID of the screen. $is\_network Whether the screen is in the network admin. $is\_user Whether the screen is in the user admin. $parent\_base The base menu parent. This is derived from $parent\_file by removing the query string and any .php extension. $parent\_file values of 'edit.php?post\_type=page' and 'edit.php?post\_type=post' have a $parent\_base of 'edit'. $parent\_file The $parent\_file for the screen per the admin menu system. Some $parent\_file values are 'edit.php?post\_type=page', 'edit.php', and 'options-general.php'. $post\_type The post type associated with the screen, if any. The 'edit.php?post\_type=page' screen has a post type of 'page'. The 'edit-tags.php?taxonomy=$taxonomy&post\_type=page' screen has a post type of 'page'. $taxonomy The taxonomy associated with the screen, if any. The 'edit-tags.php?taxonomy=category' screen has a taxonomy of 'category'. The following properties are built into the [WP\_Screen](wp_screen) class. $\_help\_tabs Private. The help tab data associated with the screen, if any. $\_help\_sidebar Private. The help sidebar data associated with screen, if any. $\_old\_compat\_help Private. Stores old string-based help. $\_options Private. The screen options associated with screen, if any. $\_registry Private. The screen object registry. $\_show\_screen\_options Private. Stores the result of the public show\_screen\_options() function. $\_screen\_settings Private. Stores the 'screen\_settings' section of screen options. * [\_\_construct](wp_screen/__construct) β€” Constructor * [add\_help\_tab](wp_screen/add_help_tab) β€” Adds a help tab to the contextual help for the screen. * [add\_old\_compat\_help](wp_screen/add_old_compat_help) β€” Sets the old string-based contextual help for the screen for backward compatibility. * [add\_option](wp_screen/add_option) β€” Adds an option for the screen. * [get](wp_screen/get) β€” Fetches a screen object. * [get\_columns](wp_screen/get_columns) β€” Gets the number of layout columns the user has selected. * [get\_help\_sidebar](wp_screen/get_help_sidebar) β€” Gets the content from a contextual help sidebar. * [get\_help\_tab](wp_screen/get_help_tab) β€” Gets the arguments for a help tab. * [get\_help\_tabs](wp_screen/get_help_tabs) β€” Gets the help tabs registered for the screen. * [get\_option](wp_screen/get_option) β€” Gets the arguments for an option for the screen. * [get\_options](wp_screen/get_options) β€” Gets the options registered for the screen. * [get\_screen\_reader\_content](wp_screen/get_screen_reader_content) β€” Gets the accessible hidden headings and text used in the screen. * [get\_screen\_reader\_text](wp_screen/get_screen_reader_text) β€” Gets a screen reader text string. * [in\_admin](wp_screen/in_admin) β€” Indicates whether the screen is in a particular admin. * [is\_block\_editor](wp_screen/is_block_editor) β€” Sets or returns whether the block editor is loading on the current screen. * [remove\_help\_tab](wp_screen/remove_help_tab) β€” Removes a help tab from the contextual help for the screen. * [remove\_help\_tabs](wp_screen/remove_help_tabs) β€” Removes all help tabs from the contextual help for the screen. * [remove\_option](wp_screen/remove_option) β€” Removes an option from the screen. * [remove\_options](wp_screen/remove_options) β€” Removes all options from the screen. * [remove\_screen\_reader\_content](wp_screen/remove_screen_reader_content) β€” Removes all the accessible hidden headings and text for the screen. * [render\_list\_table\_columns\_preferences](wp_screen/render_list_table_columns_preferences) β€” Renders the list table columns preferences. * [render\_meta\_boxes\_preferences](wp_screen/render_meta_boxes_preferences) β€” Renders the meta boxes preferences. * [render\_per\_page\_options](wp_screen/render_per_page_options) β€” Renders the items per page option. * [render\_screen\_layout](wp_screen/render_screen_layout) β€” Renders the option for number of columns on the page. * [render\_screen\_meta](wp_screen/render_screen_meta) β€” Renders the screen's help section. * [render\_screen\_options](wp_screen/render_screen_options) β€” Renders the screen options tab. * [render\_screen\_reader\_content](wp_screen/render_screen_reader_content) β€” Renders screen reader text. * [render\_view\_mode](wp_screen/render_view_mode) β€” Renders the list table view mode preferences. * [set\_current\_screen](wp_screen/set_current_screen) β€” Makes the screen object the current screen. * [set\_help\_sidebar](wp_screen/set_help_sidebar) β€” Adds a sidebar to the contextual help for the screen. * [set\_parentage](wp_screen/set_parentage) β€” Sets the parent information for the screen. * [set\_screen\_reader\_content](wp_screen/set_screen_reader_content) β€” Adds accessible hidden headings and text for the screen. * [show\_screen\_options](wp_screen/show_screen_options) File: `wp-admin/includes/class-wp-screen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-screen.php/) ``` final class WP_Screen { /** * Any action associated with the screen. * * 'add' for *-add.php and *-new.php screens. Empty otherwise. * * @since 3.3.0 * @var string */ public $action; /** * The base type of the screen. * * This is typically the same as `$id` but with any post types and taxonomies stripped. * For example, for an `$id` of 'edit-post' the base is 'edit'. * * @since 3.3.0 * @var string */ public $base; /** * The number of columns to display. Access with get_columns(). * * @since 3.4.0 * @var int */ private $columns = 0; /** * The unique ID of the screen. * * @since 3.3.0 * @var string */ public $id; /** * Which admin the screen is in. network | user | site | false * * @since 3.5.0 * @var string */ protected $in_admin; /** * Whether the screen is in the network admin. * * Deprecated. Use in_admin() instead. * * @since 3.3.0 * @deprecated 3.5.0 * @var bool */ public $is_network; /** * Whether the screen is in the user admin. * * Deprecated. Use in_admin() instead. * * @since 3.3.0 * @deprecated 3.5.0 * @var bool */ public $is_user; /** * The base menu parent. * * This is derived from `$parent_file` by removing the query string and any .php extension. * `$parent_file` values of 'edit.php?post_type=page' and 'edit.php?post_type=post' * have a `$parent_base` of 'edit'. * * @since 3.3.0 * @var string */ public $parent_base; /** * The parent_file for the screen per the admin menu system. * * Some `$parent_file` values are 'edit.php?post_type=page', 'edit.php', and 'options-general.php'. * * @since 3.3.0 * @var string */ public $parent_file; /** * The post type associated with the screen, if any. * * The 'edit.php?post_type=page' screen has a post type of 'page'. * The 'edit-tags.php?taxonomy=$taxonomy&post_type=page' screen has a post type of 'page'. * * @since 3.3.0 * @var string */ public $post_type; /** * The taxonomy associated with the screen, if any. * * The 'edit-tags.php?taxonomy=category' screen has a taxonomy of 'category'. * * @since 3.3.0 * @var string */ public $taxonomy; /** * The help tab data associated with the screen, if any. * * @since 3.3.0 * @var array */ private $_help_tabs = array(); /** * The help sidebar data associated with screen, if any. * * @since 3.3.0 * @var string */ private $_help_sidebar = ''; /** * The accessible hidden headings and text associated with the screen, if any. * * @since 4.4.0 * @var array */ private $_screen_reader_content = array(); /** * Stores old string-based help. * * @var array */ private static $_old_compat_help = array(); /** * The screen options associated with screen, if any. * * @since 3.3.0 * @var array */ private $_options = array(); /** * The screen object registry. * * @since 3.3.0 * * @var array */ private static $_registry = array(); /** * Stores the result of the public show_screen_options function. * * @since 3.3.0 * @var bool */ private $_show_screen_options; /** * Stores the 'screen_settings' section of screen options. * * @since 3.3.0 * @var string */ private $_screen_settings; /** * Whether the screen is using the block editor. * * @since 5.0.0 * @var bool */ public $is_block_editor = false; /** * Fetches a screen object. * * @since 3.3.0 * * @global string $hook_suffix * * @param string|WP_Screen $hook_name Optional. The hook name (also known as the hook suffix) used to determine the screen. * Defaults to the current $hook_suffix global. * @return WP_Screen Screen object. */ public static function get( $hook_name = '' ) { if ( $hook_name instanceof WP_Screen ) { return $hook_name; } $id = ''; $post_type = null; $taxonomy = null; $in_admin = false; $action = ''; $is_block_editor = false; if ( $hook_name ) { $id = $hook_name; } elseif ( ! empty( $GLOBALS['hook_suffix'] ) ) { $id = $GLOBALS['hook_suffix']; } // For those pesky meta boxes. if ( $hook_name && post_type_exists( $hook_name ) ) { $post_type = $id; $id = 'post'; // Changes later. Ends up being $base. } else { if ( '.php' === substr( $id, -4 ) ) { $id = substr( $id, 0, -4 ); } if ( in_array( $id, array( 'post-new', 'link-add', 'media-new', 'user-new' ), true ) ) { $id = substr( $id, 0, -4 ); $action = 'add'; } } if ( ! $post_type && $hook_name ) { if ( '-network' === substr( $id, -8 ) ) { $id = substr( $id, 0, -8 ); $in_admin = 'network'; } elseif ( '-user' === substr( $id, -5 ) ) { $id = substr( $id, 0, -5 ); $in_admin = 'user'; } $id = sanitize_key( $id ); if ( 'edit-comments' !== $id && 'edit-tags' !== $id && 'edit-' === substr( $id, 0, 5 ) ) { $maybe = substr( $id, 5 ); if ( taxonomy_exists( $maybe ) ) { $id = 'edit-tags'; $taxonomy = $maybe; } elseif ( post_type_exists( $maybe ) ) { $id = 'edit'; $post_type = $maybe; } } if ( ! $in_admin ) { $in_admin = 'site'; } } else { if ( defined( 'WP_NETWORK_ADMIN' ) && WP_NETWORK_ADMIN ) { $in_admin = 'network'; } elseif ( defined( 'WP_USER_ADMIN' ) && WP_USER_ADMIN ) { $in_admin = 'user'; } else { $in_admin = 'site'; } } if ( 'index' === $id ) { $id = 'dashboard'; } elseif ( 'front' === $id ) { $in_admin = false; } $base = $id; // If this is the current screen, see if we can be more accurate for post types and taxonomies. if ( ! $hook_name ) { if ( isset( $_REQUEST['post_type'] ) ) { $post_type = post_type_exists( $_REQUEST['post_type'] ) ? $_REQUEST['post_type'] : false; } if ( isset( $_REQUEST['taxonomy'] ) ) { $taxonomy = taxonomy_exists( $_REQUEST['taxonomy'] ) ? $_REQUEST['taxonomy'] : false; } switch ( $base ) { case 'post': if ( isset( $_GET['post'] ) && isset( $_POST['post_ID'] ) && (int) $_GET['post'] !== (int) $_POST['post_ID'] ) { wp_die( __( 'A post ID mismatch has been detected.' ), __( 'Sorry, you are not allowed to edit this item.' ), 400 ); } elseif ( isset( $_GET['post'] ) ) { $post_id = (int) $_GET['post']; } elseif ( isset( $_POST['post_ID'] ) ) { $post_id = (int) $_POST['post_ID']; } else { $post_id = 0; } if ( $post_id ) { $post = get_post( $post_id ); if ( $post ) { $post_type = $post->post_type; /** This filter is documented in wp-admin/post.php */ $replace_editor = apply_filters( 'replace_editor', false, $post ); if ( ! $replace_editor ) { $is_block_editor = use_block_editor_for_post( $post ); } } } break; case 'edit-tags': case 'term': if ( null === $post_type && is_object_in_taxonomy( 'post', $taxonomy ? $taxonomy : 'post_tag' ) ) { $post_type = 'post'; } break; case 'upload': $post_type = 'attachment'; break; } } switch ( $base ) { case 'post': if ( null === $post_type ) { $post_type = 'post'; } // When creating a new post, use the default block editor support value for the post type. if ( empty( $post_id ) ) { $is_block_editor = use_block_editor_for_post_type( $post_type ); } $id = $post_type; break; case 'edit': if ( null === $post_type ) { $post_type = 'post'; } $id .= '-' . $post_type; break; case 'edit-tags': case 'term': if ( null === $taxonomy ) { $taxonomy = 'post_tag'; } // The edit-tags ID does not contain the post type. Look for it in the request. if ( null === $post_type ) { $post_type = 'post'; if ( isset( $_REQUEST['post_type'] ) && post_type_exists( $_REQUEST['post_type'] ) ) { $post_type = $_REQUEST['post_type']; } } $id = 'edit-' . $taxonomy; break; } if ( 'network' === $in_admin ) { $id .= '-network'; $base .= '-network'; } elseif ( 'user' === $in_admin ) { $id .= '-user'; $base .= '-user'; } if ( isset( self::$_registry[ $id ] ) ) { $screen = self::$_registry[ $id ]; if ( get_current_screen() === $screen ) { return $screen; } } else { $screen = new self(); $screen->id = $id; } $screen->base = $base; $screen->action = $action; $screen->post_type = (string) $post_type; $screen->taxonomy = (string) $taxonomy; $screen->is_user = ( 'user' === $in_admin ); $screen->is_network = ( 'network' === $in_admin ); $screen->in_admin = $in_admin; $screen->is_block_editor = $is_block_editor; self::$_registry[ $id ] = $screen; return $screen; } /** * Makes the screen object the current screen. * * @see set_current_screen() * @since 3.3.0 * * @global WP_Screen $current_screen WordPress current screen object. * @global string $typenow The post type of the current screen. * @global string $taxnow The taxonomy of the current screen. */ public function set_current_screen() { global $current_screen, $taxnow, $typenow; $current_screen = $this; $typenow = $this->post_type; $taxnow = $this->taxonomy; /** * Fires after the current screen has been set. * * @since 3.0.0 * * @param WP_Screen $current_screen Current WP_Screen object. */ do_action( 'current_screen', $current_screen ); } /** * Constructor * * @since 3.3.0 */ private function __construct() {} /** * Indicates whether the screen is in a particular admin. * * @since 3.5.0 * * @param string $admin The admin to check against (network | user | site). * If empty any of the three admins will result in true. * @return bool True if the screen is in the indicated admin, false otherwise. */ public function in_admin( $admin = null ) { if ( empty( $admin ) ) { return (bool) $this->in_admin; } return ( $admin === $this->in_admin ); } /** * Sets or returns whether the block editor is loading on the current screen. * * @since 5.0.0 * * @param bool $set Optional. Sets whether the block editor is loading on the current screen or not. * @return bool True if the block editor is being loaded, false otherwise. */ public function is_block_editor( $set = null ) { if ( null !== $set ) { $this->is_block_editor = (bool) $set; } return $this->is_block_editor; } /** * Sets the old string-based contextual help for the screen for backward compatibility. * * @since 3.3.0 * * @param WP_Screen $screen A screen object. * @param string $help Help text. */ public static function add_old_compat_help( $screen, $help ) { self::$_old_compat_help[ $screen->id ] = $help; } /** * Sets the parent information for the screen. * * This is called in admin-header.php after the menu parent for the screen has been determined. * * @since 3.3.0 * * @param string $parent_file The parent file of the screen. Typically the $parent_file global. */ public function set_parentage( $parent_file ) { $this->parent_file = $parent_file; list( $this->parent_base ) = explode( '?', $parent_file ); $this->parent_base = str_replace( '.php', '', $this->parent_base ); } /** * Adds an option for the screen. * * Call this in template files after admin.php is loaded and before admin-header.php is loaded * to add screen options. * * @since 3.3.0 * * @param string $option Option ID. * @param mixed $args Option-dependent arguments. */ public function add_option( $option, $args = array() ) { $this->_options[ $option ] = $args; } /** * Removes an option from the screen. * * @since 3.8.0 * * @param string $option Option ID. */ public function remove_option( $option ) { unset( $this->_options[ $option ] ); } /** * Removes all options from the screen. * * @since 3.8.0 */ public function remove_options() { $this->_options = array(); } /** * Gets the options registered for the screen. * * @since 3.8.0 * * @return array Options with arguments. */ public function get_options() { return $this->_options; } /** * Gets the arguments for an option for the screen. * * @since 3.3.0 * * @param string $option Option name. * @param string|false $key Optional. Specific array key for when the option is an array. * Default false. * @return string The option value if set, null otherwise. */ public function get_option( $option, $key = false ) { if ( ! isset( $this->_options[ $option ] ) ) { return null; } if ( $key ) { if ( isset( $this->_options[ $option ][ $key ] ) ) { return $this->_options[ $option ][ $key ]; } return null; } return $this->_options[ $option ]; } /** * Gets the help tabs registered for the screen. * * @since 3.4.0 * @since 4.4.0 Help tabs are ordered by their priority. * * @return array Help tabs with arguments. */ public function get_help_tabs() { $help_tabs = $this->_help_tabs; $priorities = array(); foreach ( $help_tabs as $help_tab ) { if ( isset( $priorities[ $help_tab['priority'] ] ) ) { $priorities[ $help_tab['priority'] ][] = $help_tab; } else { $priorities[ $help_tab['priority'] ] = array( $help_tab ); } } ksort( $priorities ); $sorted = array(); foreach ( $priorities as $list ) { foreach ( $list as $tab ) { $sorted[ $tab['id'] ] = $tab; } } return $sorted; } /** * Gets the arguments for a help tab. * * @since 3.4.0 * * @param string $id Help Tab ID. * @return array Help tab arguments. */ public function get_help_tab( $id ) { if ( ! isset( $this->_help_tabs[ $id ] ) ) { return null; } return $this->_help_tabs[ $id ]; } /** * Adds a help tab to the contextual help for the screen. * * Call this on the `load-$pagenow` hook for the relevant screen, * or fetch the `$current_screen` object, or use get_current_screen() * and then call the method from the object. * * You may need to filter `$current_screen` using an if or switch statement * to prevent new help tabs from being added to ALL admin screens. * * @since 3.3.0 * @since 4.4.0 The `$priority` argument was added. * * @param array $args { * Array of arguments used to display the help tab. * * @type string $title Title for the tab. Default false. * @type string $id Tab ID. Must be HTML-safe and should be unique for this menu. * It is NOT allowed to contain any empty spaces. Default false. * @type string $content Optional. Help tab content in plain text or HTML. Default empty string. * @type callable $callback Optional. A callback to generate the tab content. Default false. * @type int $priority Optional. The priority of the tab, used for ordering. Default 10. * } */ public function add_help_tab( $args ) { $defaults = array( 'title' => false, 'id' => false, 'content' => '', 'callback' => false, 'priority' => 10, ); $args = wp_parse_args( $args, $defaults ); $args['id'] = sanitize_html_class( $args['id'] ); // Ensure we have an ID and title. if ( ! $args['id'] || ! $args['title'] ) { return; } // Allows for overriding an existing tab with that ID. $this->_help_tabs[ $args['id'] ] = $args; } /** * Removes a help tab from the contextual help for the screen. * * @since 3.3.0 * * @param string $id The help tab ID. */ public function remove_help_tab( $id ) { unset( $this->_help_tabs[ $id ] ); } /** * Removes all help tabs from the contextual help for the screen. * * @since 3.3.0 */ public function remove_help_tabs() { $this->_help_tabs = array(); } /** * Gets the content from a contextual help sidebar. * * @since 3.4.0 * * @return string Contents of the help sidebar. */ public function get_help_sidebar() { return $this->_help_sidebar; } /** * Adds a sidebar to the contextual help for the screen. * * Call this in template files after admin.php is loaded and before admin-header.php is loaded * to add a sidebar to the contextual help. * * @since 3.3.0 * * @param string $content Sidebar content in plain text or HTML. */ public function set_help_sidebar( $content ) { $this->_help_sidebar = $content; } /** * Gets the number of layout columns the user has selected. * * The layout_columns option controls the max number and default number of * columns. This method returns the number of columns within that range selected * by the user via Screen Options. If no selection has been made, the default * provisioned in layout_columns is returned. If the screen does not support * selecting the number of layout columns, 0 is returned. * * @since 3.4.0 * * @return int Number of columns to display. */ public function get_columns() { return $this->columns; } /** * Gets the accessible hidden headings and text used in the screen. * * @since 4.4.0 * * @see set_screen_reader_content() For more information on the array format. * * @return array An associative array of screen reader text strings. */ public function get_screen_reader_content() { return $this->_screen_reader_content; } /** * Gets a screen reader text string. * * @since 4.4.0 * * @param string $key Screen reader text array named key. * @return string Screen reader text string. */ public function get_screen_reader_text( $key ) { if ( ! isset( $this->_screen_reader_content[ $key ] ) ) { return null; } return $this->_screen_reader_content[ $key ]; } /** * Adds accessible hidden headings and text for the screen. * * @since 4.4.0 * * @param array $content { * An associative array of screen reader text strings. * * @type string $heading_views Screen reader text for the filter links heading. * Default 'Filter items list'. * @type string $heading_pagination Screen reader text for the pagination heading. * Default 'Items list navigation'. * @type string $heading_list Screen reader text for the items list heading. * Default 'Items list'. * } */ public function set_screen_reader_content( $content = array() ) { $defaults = array( 'heading_views' => __( 'Filter items list' ), 'heading_pagination' => __( 'Items list navigation' ), 'heading_list' => __( 'Items list' ), ); $content = wp_parse_args( $content, $defaults ); $this->_screen_reader_content = $content; } /** * Removes all the accessible hidden headings and text for the screen. * * @since 4.4.0 */ public function remove_screen_reader_content() { $this->_screen_reader_content = array(); } /** * Renders the screen's help section. * * This will trigger the deprecated filters for backward compatibility. * * @since 3.3.0 * * @global string $screen_layout_columns */ public function render_screen_meta() { /** * Filters the legacy contextual help list. * * @since 2.7.0 * @deprecated 3.3.0 Use {@see get_current_screen()->add_help_tab()} or * {@see get_current_screen()->remove_help_tab()} instead. * * @param array $old_compat_help Old contextual help. * @param WP_Screen $screen Current WP_Screen instance. */ self::$_old_compat_help = apply_filters_deprecated( 'contextual_help_list', array( self::$_old_compat_help, $this ), '3.3.0', 'get_current_screen()->add_help_tab(), get_current_screen()->remove_help_tab()' ); $old_help = isset( self::$_old_compat_help[ $this->id ] ) ? self::$_old_compat_help[ $this->id ] : ''; /** * Filters the legacy contextual help text. * * @since 2.7.0 * @deprecated 3.3.0 Use {@see get_current_screen()->add_help_tab()} or * {@see get_current_screen()->remove_help_tab()} instead. * * @param string $old_help Help text that appears on the screen. * @param string $screen_id Screen ID. * @param WP_Screen $screen Current WP_Screen instance. */ $old_help = apply_filters_deprecated( 'contextual_help', array( $old_help, $this->id, $this ), '3.3.0', 'get_current_screen()->add_help_tab(), get_current_screen()->remove_help_tab()' ); // Default help only if there is no old-style block of text and no new-style help tabs. if ( empty( $old_help ) && ! $this->get_help_tabs() ) { /** * Filters the default legacy contextual help text. * * @since 2.8.0 * @deprecated 3.3.0 Use {@see get_current_screen()->add_help_tab()} or * {@see get_current_screen()->remove_help_tab()} instead. * * @param string $old_help_default Default contextual help text. */ $default_help = apply_filters_deprecated( 'default_contextual_help', array( '' ), '3.3.0', 'get_current_screen()->add_help_tab(), get_current_screen()->remove_help_tab()' ); if ( $default_help ) { $old_help = '<p>' . $default_help . '</p>'; } } if ( $old_help ) { $this->add_help_tab( array( 'id' => 'old-contextual-help', 'title' => __( 'Overview' ), 'content' => $old_help, ) ); } $help_sidebar = $this->get_help_sidebar(); $help_class = 'hidden'; if ( ! $help_sidebar ) { $help_class .= ' no-sidebar'; } // Time to render! ?> <div id="screen-meta" class="metabox-prefs"> <div id="contextual-help-wrap" class="<?php echo esc_attr( $help_class ); ?>" tabindex="-1" aria-label="<?php esc_attr_e( 'Contextual Help Tab' ); ?>"> <div id="contextual-help-back"></div> <div id="contextual-help-columns"> <div class="contextual-help-tabs"> <ul> <?php $class = ' class="active"'; foreach ( $this->get_help_tabs() as $tab ) : $link_id = "tab-link-{$tab['id']}"; $panel_id = "tab-panel-{$tab['id']}"; ?> <li id="<?php echo esc_attr( $link_id ); ?>"<?php echo $class; ?>> <a href="<?php echo esc_url( "#$panel_id" ); ?>" aria-controls="<?php echo esc_attr( $panel_id ); ?>"> <?php echo esc_html( $tab['title'] ); ?> </a> </li> <?php $class = ''; endforeach; ?> </ul> </div> <?php if ( $help_sidebar ) : ?> <div class="contextual-help-sidebar"> <?php echo $help_sidebar; ?> </div> <?php endif; ?> <div class="contextual-help-tabs-wrap"> <?php $classes = 'help-tab-content active'; foreach ( $this->get_help_tabs() as $tab ) : $panel_id = "tab-panel-{$tab['id']}"; ?> <div id="<?php echo esc_attr( $panel_id ); ?>" class="<?php echo $classes; ?>"> <?php // Print tab content. echo $tab['content']; // If it exists, fire tab callback. if ( ! empty( $tab['callback'] ) ) { call_user_func_array( $tab['callback'], array( $this, $tab ) ); } ?> </div> <?php $classes = 'help-tab-content'; endforeach; ?> </div> </div> </div> <?php // Setup layout columns. /** * Filters the array of screen layout columns. * * This hook provides back-compat for plugins using the back-compat * Filters instead of add_screen_option(). * * @since 2.8.0 * * @param array $empty_columns Empty array. * @param string $screen_id Screen ID. * @param WP_Screen $screen Current WP_Screen instance. */ $columns = apply_filters( 'screen_layout_columns', array(), $this->id, $this ); if ( ! empty( $columns ) && isset( $columns[ $this->id ] ) ) { $this->add_option( 'layout_columns', array( 'max' => $columns[ $this->id ] ) ); } if ( $this->get_option( 'layout_columns' ) ) { $this->columns = (int) get_user_option( "screen_layout_$this->id" ); if ( ! $this->columns && $this->get_option( 'layout_columns', 'default' ) ) { $this->columns = $this->get_option( 'layout_columns', 'default' ); } } $GLOBALS['screen_layout_columns'] = $this->columns; // Set the global for back-compat. // Add screen options. if ( $this->show_screen_options() ) { $this->render_screen_options(); } ?> </div> <?php if ( ! $this->get_help_tabs() && ! $this->show_screen_options() ) { return; } ?> <div id="screen-meta-links"> <?php if ( $this->show_screen_options() ) : ?> <div id="screen-options-link-wrap" class="hide-if-no-js screen-meta-toggle"> <button type="button" id="show-settings-link" class="button show-settings" aria-controls="screen-options-wrap" aria-expanded="false"><?php _e( 'Screen Options' ); ?></button> </div> <?php endif; if ( $this->get_help_tabs() ) : ?> <div id="contextual-help-link-wrap" class="hide-if-no-js screen-meta-toggle"> <button type="button" id="contextual-help-link" class="button show-settings" aria-controls="contextual-help-wrap" aria-expanded="false"><?php _e( 'Help' ); ?></button> </div> <?php endif; ?> </div> <?php } /** * @global array $wp_meta_boxes * * @return bool */ public function show_screen_options() { global $wp_meta_boxes; if ( is_bool( $this->_show_screen_options ) ) { return $this->_show_screen_options; } $columns = get_column_headers( $this ); $show_screen = ! empty( $wp_meta_boxes[ $this->id ] ) || $columns || $this->get_option( 'per_page' ); $this->_screen_settings = ''; if ( 'post' === $this->base ) { $expand = '<fieldset class="editor-expand hidden"><legend>' . __( 'Additional settings' ) . '</legend><label for="editor-expand-toggle">'; $expand .= '<input type="checkbox" id="editor-expand-toggle"' . checked( get_user_setting( 'editor_expand', 'on' ), 'on', false ) . ' />'; $expand .= __( 'Enable full-height editor and distraction-free functionality.' ) . '</label></fieldset>'; $this->_screen_settings = $expand; } /** * Filters the screen settings text displayed in the Screen Options tab. * * @since 3.0.0 * * @param string $screen_settings Screen settings. * @param WP_Screen $screen WP_Screen object. */ $this->_screen_settings = apply_filters( 'screen_settings', $this->_screen_settings, $this ); if ( $this->_screen_settings || $this->_options ) { $show_screen = true; } /** * Filters whether to show the Screen Options tab. * * @since 3.2.0 * * @param bool $show_screen Whether to show Screen Options tab. * Default true. * @param WP_Screen $screen Current WP_Screen instance. */ $this->_show_screen_options = apply_filters( 'screen_options_show_screen', $show_screen, $this ); return $this->_show_screen_options; } /** * Renders the screen options tab. * * @since 3.3.0 * * @param array $options { * Options for the tab. * * @type bool $wrap Whether the screen-options-wrap div will be included. Defaults to true. * } */ public function render_screen_options( $options = array() ) { $options = wp_parse_args( $options, array( 'wrap' => true, ) ); $wrapper_start = ''; $wrapper_end = ''; $form_start = ''; $form_end = ''; // Output optional wrapper. if ( $options['wrap'] ) { $wrapper_start = '<div id="screen-options-wrap" class="hidden" tabindex="-1" aria-label="' . esc_attr__( 'Screen Options Tab' ) . '">'; $wrapper_end = '</div>'; } // Don't output the form and nonce for the widgets accessibility mode links. if ( 'widgets' !== $this->base ) { $form_start = "\n<form id='adv-settings' method='post'>\n"; $form_end = "\n" . wp_nonce_field( 'screen-options-nonce', 'screenoptionnonce', false, false ) . "\n</form>\n"; } echo $wrapper_start . $form_start; $this->render_meta_boxes_preferences(); $this->render_list_table_columns_preferences(); $this->render_screen_layout(); $this->render_per_page_options(); $this->render_view_mode(); echo $this->_screen_settings; /** * Filters whether to show the Screen Options submit button. * * @since 4.4.0 * * @param bool $show_button Whether to show Screen Options submit button. * Default false. * @param WP_Screen $screen Current WP_Screen instance. */ $show_button = apply_filters( 'screen_options_show_submit', false, $this ); if ( $show_button ) { submit_button( __( 'Apply' ), 'primary', 'screen-options-apply', true ); } echo $form_end . $wrapper_end; } /** * Renders the meta boxes preferences. * * @since 4.4.0 * * @global array $wp_meta_boxes */ public function render_meta_boxes_preferences() { global $wp_meta_boxes; if ( ! isset( $wp_meta_boxes[ $this->id ] ) ) { return; } ?> <fieldset class="metabox-prefs"> <legend><?php _e( 'Screen elements' ); ?></legend> <p> <?php _e( 'Some screen elements can be shown or hidden by using the checkboxes.' ); ?> <?php _e( 'They can be expanded and collapsed by clickling on their headings, and arranged by dragging their headings or by clicking on the up and down arrows.' ); ?> </p> <?php meta_box_prefs( $this ); if ( 'dashboard' === $this->id && has_action( 'welcome_panel' ) && current_user_can( 'edit_theme_options' ) ) { if ( isset( $_GET['welcome'] ) ) { $welcome_checked = empty( $_GET['welcome'] ) ? 0 : 1; update_user_meta( get_current_user_id(), 'show_welcome_panel', $welcome_checked ); } else { $welcome_checked = (int) get_user_meta( get_current_user_id(), 'show_welcome_panel', true ); if ( 2 === $welcome_checked && wp_get_current_user()->user_email !== get_option( 'admin_email' ) ) { $welcome_checked = false; } } echo '<label for="wp_welcome_panel-hide">'; echo '<input type="checkbox" id="wp_welcome_panel-hide"' . checked( (bool) $welcome_checked, true, false ) . ' />'; echo _x( 'Welcome', 'Welcome panel' ) . "</label>\n"; } ?> </fieldset> <?php } /** * Renders the list table columns preferences. * * @since 4.4.0 */ public function render_list_table_columns_preferences() { $columns = get_column_headers( $this ); $hidden = get_hidden_columns( $this ); if ( ! $columns ) { return; } $legend = ! empty( $columns['_title'] ) ? $columns['_title'] : __( 'Columns' ); ?> <fieldset class="metabox-prefs"> <legend><?php echo $legend; ?></legend> <?php $special = array( '_title', 'cb', 'comment', 'media', 'name', 'title', 'username', 'blogname' ); foreach ( $columns as $column => $title ) { // Can't hide these for they are special. if ( in_array( $column, $special, true ) ) { continue; } if ( empty( $title ) ) { continue; } /* * The Comments column uses HTML in the display name with some screen * reader text. Make sure to strip tags from the Comments column * title and any other custom column title plugins might add. */ $title = wp_strip_all_tags( $title ); $id = "$column-hide"; echo '<label>'; echo '<input class="hide-column-tog" name="' . $id . '" type="checkbox" id="' . $id . '" value="' . $column . '"' . checked( ! in_array( $column, $hidden, true ), true, false ) . ' />'; echo "$title</label>\n"; } ?> </fieldset> <?php } /** * Renders the option for number of columns on the page. * * @since 3.3.0 */ public function render_screen_layout() { if ( ! $this->get_option( 'layout_columns' ) ) { return; } $screen_layout_columns = $this->get_columns(); $num = $this->get_option( 'layout_columns', 'max' ); ?> <fieldset class='columns-prefs'> <legend class="screen-layout"><?php _e( 'Layout' ); ?></legend> <?php for ( $i = 1; $i <= $num; ++$i ) : ?> <label class="columns-prefs-<?php echo $i; ?>"> <input type='radio' name='screen_columns' value='<?php echo esc_attr( $i ); ?>' <?php checked( $screen_layout_columns, $i ); ?> /> <?php printf( /* translators: %s: Number of columns on the page. */ _n( '%s column', '%s columns', $i ), number_format_i18n( $i ) ); ?> </label> <?php endfor; ?> </fieldset> <?php } /** * Renders the items per page option. * * @since 3.3.0 */ public function render_per_page_options() { if ( null === $this->get_option( 'per_page' ) ) { return; } $per_page_label = $this->get_option( 'per_page', 'label' ); if ( null === $per_page_label ) { $per_page_label = __( 'Number of items per page:' ); } $option = $this->get_option( 'per_page', 'option' ); if ( ! $option ) { $option = str_replace( '-', '_', "{$this->id}_per_page" ); } $per_page = (int) get_user_option( $option ); if ( empty( $per_page ) || $per_page < 1 ) { $per_page = $this->get_option( 'per_page', 'default' ); if ( ! $per_page ) { $per_page = 20; } } if ( 'edit_comments_per_page' === $option ) { $comment_status = isset( $_REQUEST['comment_status'] ) ? $_REQUEST['comment_status'] : 'all'; /** This filter is documented in wp-admin/includes/class-wp-comments-list-table.php */ $per_page = apply_filters( 'comments_per_page', $per_page, $comment_status ); } elseif ( 'categories_per_page' === $option ) { /** This filter is documented in wp-admin/includes/class-wp-terms-list-table.php */ $per_page = apply_filters( 'edit_categories_per_page', $per_page ); } else { /** This filter is documented in wp-admin/includes/class-wp-list-table.php */ $per_page = apply_filters( "{$option}", $per_page ); } // Back compat. if ( isset( $this->post_type ) ) { /** This filter is documented in wp-admin/includes/post.php */ $per_page = apply_filters( 'edit_posts_per_page', $per_page, $this->post_type ); } // This needs a submit button. add_filter( 'screen_options_show_submit', '__return_true' ); ?> <fieldset class="screen-options"> <legend><?php _e( 'Pagination' ); ?></legend> <?php if ( $per_page_label ) : ?> <label for="<?php echo esc_attr( $option ); ?>"><?php echo $per_page_label; ?></label> <input type="number" step="1" min="1" max="999" class="screen-per-page" name="wp_screen_options[value]" id="<?php echo esc_attr( $option ); ?>" maxlength="3" value="<?php echo esc_attr( $per_page ); ?>" /> <?php endif; ?> <input type="hidden" name="wp_screen_options[option]" value="<?php echo esc_attr( $option ); ?>" /> </fieldset> <?php } /** * Renders the list table view mode preferences. * * @since 4.4.0 * * @global string $mode List table view mode. */ public function render_view_mode() { global $mode; $screen = get_current_screen(); // Currently only enabled for posts and comments lists. if ( 'edit' !== $screen->base && 'edit-comments' !== $screen->base ) { return; } $view_mode_post_types = get_post_types( array( 'show_ui' => true ) ); /** * Filters the post types that have different view mode options. * * @since 4.4.0 * * @param string[] $view_mode_post_types Array of post types that can change view modes. * Default post types with show_ui on. */ $view_mode_post_types = apply_filters( 'view_mode_post_types', $view_mode_post_types ); if ( 'edit' === $screen->base && ! in_array( $this->post_type, $view_mode_post_types, true ) ) { return; } if ( ! isset( $mode ) ) { $mode = get_user_setting( 'posts_list_mode', 'list' ); } // This needs a submit button. add_filter( 'screen_options_show_submit', '__return_true' ); ?> <fieldset class="metabox-prefs view-mode"> <legend><?php _e( 'View mode' ); ?></legend> <label for="list-view-mode"> <input id="list-view-mode" type="radio" name="mode" value="list" <?php checked( 'list', $mode ); ?> /> <?php _e( 'Compact view' ); ?> </label> <label for="excerpt-view-mode"> <input id="excerpt-view-mode" type="radio" name="mode" value="excerpt" <?php checked( 'excerpt', $mode ); ?> /> <?php _e( 'Extended view' ); ?> </label> </fieldset> <?php } /** * Renders screen reader text. * * @since 4.4.0 * * @param string $key The screen reader text array named key. * @param string $tag Optional. The HTML tag to wrap the screen reader text. Default h2. */ public function render_screen_reader_content( $key = '', $tag = 'h2' ) { if ( ! isset( $this->_screen_reader_content[ $key ] ) ) { return; } echo "<$tag class='screen-reader-text'>" . $this->_screen_reader_content[ $key ] . "</$tag>"; } } ``` | Version | Description | | --- | --- | | [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
programming_docs
wordpress class Theme_Installer_Skin {} class Theme\_Installer\_Skin {} =============================== Theme Installer Skin for the WordPress Theme Installer. * [WP\_Upgrader\_Skin](wp_upgrader_skin) * [\_\_construct](theme_installer_skin/__construct) * [after](theme_installer_skin/after) β€” Action to perform following a single theme install. * [before](theme_installer_skin/before) β€” Action to perform before installing a theme. * [do\_overwrite](theme_installer_skin/do_overwrite) β€” Check if the theme can be overwritten and output the HTML for overwriting a theme on upload. * [hide\_process\_failed](theme_installer_skin/hide_process_failed) β€” Hides the `process\_failed` error when updating a theme by uploading a zip file. File: `wp-admin/includes/class-theme-installer-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-theme-installer-skin.php/) ``` class Theme_Installer_Skin extends WP_Upgrader_Skin { public $api; public $type; public $url; public $overwrite; private $is_downgrading = false; /** * @param array $args */ public function __construct( $args = array() ) { $defaults = array( 'type' => 'web', 'url' => '', 'theme' => '', 'nonce' => '', 'title' => '', 'overwrite' => '', ); $args = wp_parse_args( $args, $defaults ); $this->type = $args['type']; $this->url = $args['url']; $this->api = isset( $args['api'] ) ? $args['api'] : array(); $this->overwrite = $args['overwrite']; parent::__construct( $args ); } /** * Action to perform before installing a theme. * * @since 2.8.0 */ public function before() { if ( ! empty( $this->api ) ) { $this->upgrader->strings['process_success'] = sprintf( $this->upgrader->strings['process_success_specific'], $this->api->name, $this->api->version ); } } /** * Hides the `process_failed` error when updating a theme by uploading a zip file. * * @since 5.5.0 * * @param WP_Error $wp_error WP_Error object. * @return bool */ public function hide_process_failed( $wp_error ) { if ( 'upload' === $this->type && '' === $this->overwrite && $wp_error->get_error_code() === 'folder_exists' ) { return true; } return false; } /** * Action to perform following a single theme install. * * @since 2.8.0 */ public function after() { if ( $this->do_overwrite() ) { return; } if ( empty( $this->upgrader->result['destination_name'] ) ) { return; } $theme_info = $this->upgrader->theme_info(); if ( empty( $theme_info ) ) { return; } $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 ); $install_actions = array(); if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) && ! $theme_info->is_block_theme() ) { $customize_url = add_query_arg( array( 'theme' => urlencode( $stylesheet ), 'return' => urlencode( admin_url( 'web' === $this->type ? 'theme-install.php' : 'themes.php' ) ), ), admin_url( 'customize.php' ) ); $install_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 &#8220;%s&#8221;' ), $name ) ); } $install_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 &#8220;%s&#8221;', 'theme' ), $name ) ); if ( is_network_admin() && current_user_can( 'manage_network_themes' ) ) { $install_actions['network_enable'] = sprintf( '<a href="%s" target="_parent">%s</a>', esc_url( wp_nonce_url( 'themes.php?action=enable&amp;theme=' . urlencode( $stylesheet ), 'enable-theme_' . $stylesheet ) ), __( 'Network Enable' ) ); } if ( 'web' === $this->type ) { $install_actions['themes_page'] = sprintf( '<a href="%s" target="_parent">%s</a>', self_admin_url( 'theme-install.php' ), __( 'Go to Theme Installer' ) ); } elseif ( current_user_can( 'switch_themes' ) || current_user_can( 'edit_theme_options' ) ) { $install_actions['themes_page'] = sprintf( '<a href="%s" target="_parent">%s</a>', self_admin_url( 'themes.php' ), __( 'Go to Themes page' ) ); } if ( ! $this->result || is_wp_error( $this->result ) || is_network_admin() || ! current_user_can( 'switch_themes' ) ) { unset( $install_actions['activate'], $install_actions['preview'] ); } elseif ( get_option( 'template' ) === $stylesheet ) { unset( $install_actions['activate'] ); } /** * Filters the list of action links available following a single theme installation. * * @since 2.8.0 * * @param string[] $install_actions Array of theme action links. * @param object $api Object containing WordPress.org API theme data. * @param string $stylesheet Theme directory name. * @param WP_Theme $theme_info Theme object. */ $install_actions = apply_filters( 'install_theme_complete_actions', $install_actions, $this->api, $stylesheet, $theme_info ); if ( ! empty( $install_actions ) ) { $this->feedback( implode( ' | ', (array) $install_actions ) ); } } /** * Check if the theme can be overwritten and output the HTML for overwriting a theme on upload. * * @since 5.5.0 * * @return bool Whether the theme can be overwritten and HTML was outputted. */ private function do_overwrite() { if ( 'upload' !== $this->type || ! is_wp_error( $this->result ) || 'folder_exists' !== $this->result->get_error_code() ) { return false; } $folder = $this->result->get_error_data( 'folder_exists' ); $folder = rtrim( $folder, '/' ); $current_theme_data = false; $all_themes = wp_get_themes( array( 'errors' => null ) ); foreach ( $all_themes as $theme ) { $stylesheet_dir = wp_normalize_path( $theme->get_stylesheet_directory() ); if ( rtrim( $stylesheet_dir, '/' ) !== $folder ) { continue; } $current_theme_data = $theme; } $new_theme_data = $this->upgrader->new_theme_data; if ( ! $current_theme_data || ! $new_theme_data ) { return false; } echo '<h2 class="update-from-upload-heading">' . esc_html__( 'This theme is already installed.' ) . '</h2>'; // Check errors for active theme. if ( is_wp_error( $current_theme_data->errors() ) ) { $this->feedback( 'current_theme_has_errors', $current_theme_data->errors()->get_error_message() ); } $this->is_downgrading = version_compare( $current_theme_data['Version'], $new_theme_data['Version'], '>' ); $is_invalid_parent = false; if ( ! empty( $new_theme_data['Template'] ) ) { $is_invalid_parent = ! in_array( $new_theme_data['Template'], array_keys( $all_themes ), true ); } $rows = array( 'Name' => __( 'Theme name' ), 'Version' => __( 'Version' ), 'Author' => __( 'Author' ), 'RequiresWP' => __( 'Required WordPress version' ), 'RequiresPHP' => __( 'Required PHP version' ), 'Template' => __( 'Parent theme' ), ); $table = '<table class="update-from-upload-comparison"><tbody>'; $table .= '<tr><th></th><th>' . esc_html_x( 'Active', 'theme' ) . '</th><th>' . esc_html_x( 'Uploaded', 'theme' ) . '</th></tr>'; $is_same_theme = true; // Let's consider only these rows. foreach ( $rows as $field => $label ) { $old_value = $current_theme_data->display( $field, false ); $old_value = $old_value ? (string) $old_value : '-'; $new_value = ! empty( $new_theme_data[ $field ] ) ? (string) $new_theme_data[ $field ] : '-'; if ( $old_value === $new_value && '-' === $new_value && 'Template' === $field ) { continue; } $is_same_theme = $is_same_theme && ( $old_value === $new_value ); $diff_field = ( 'Version' !== $field && $new_value !== $old_value ); $diff_version = ( 'Version' === $field && $this->is_downgrading ); $invalid_parent = false; if ( 'Template' === $field && $is_invalid_parent ) { $invalid_parent = true; $new_value .= ' ' . __( '(not found)' ); } $table .= '<tr><td class="name-label">' . $label . '</td><td>' . wp_strip_all_tags( $old_value ) . '</td>'; $table .= ( $diff_field || $diff_version || $invalid_parent ) ? '<td class="warning">' : '<td>'; $table .= wp_strip_all_tags( $new_value ) . '</td></tr>'; } $table .= '</tbody></table>'; /** * Filters the compare table output for overwriting a theme package on upload. * * @since 5.5.0 * * @param string $table The output table with Name, Version, Author, RequiresWP, and RequiresPHP info. * @param WP_Theme $current_theme_data Active theme data. * @param array $new_theme_data Array with uploaded theme data. */ echo apply_filters( 'install_theme_overwrite_comparison', $table, $current_theme_data, $new_theme_data ); $install_actions = array(); $can_update = true; $blocked_message = '<p>' . esc_html__( 'The theme cannot be updated due to the following:' ) . '</p>'; $blocked_message .= '<ul class="ul-disc">'; $requires_php = isset( $new_theme_data['RequiresPHP'] ) ? $new_theme_data['RequiresPHP'] : null; $requires_wp = isset( $new_theme_data['RequiresWP'] ) ? $new_theme_data['RequiresWP'] : null; if ( ! is_php_version_compatible( $requires_php ) ) { $error = sprintf( /* translators: 1: Current PHP version, 2: Version required by the uploaded theme. */ __( 'The PHP version on your server is %1$s, however the uploaded theme requires %2$s.' ), PHP_VERSION, $requires_php ); $blocked_message .= '<li>' . esc_html( $error ) . '</li>'; $can_update = false; } if ( ! is_wp_version_compatible( $requires_wp ) ) { $error = sprintf( /* translators: 1: Current WordPress version, 2: Version required by the uploaded theme. */ __( 'Your WordPress version is %1$s, however the uploaded theme requires %2$s.' ), get_bloginfo( 'version' ), $requires_wp ); $blocked_message .= '<li>' . esc_html( $error ) . '</li>'; $can_update = false; } $blocked_message .= '</ul>'; if ( $can_update ) { if ( $this->is_downgrading ) { $warning = sprintf( /* translators: %s: Documentation URL. */ __( 'You are uploading an older version of the active theme. You can continue to install the older version, but be sure to <a href="%s">back up your database and files</a> first.' ), __( 'https://wordpress.org/support/article/wordpress-backups/' ) ); } else { $warning = sprintf( /* translators: %s: Documentation URL. */ __( 'You are updating a theme. Be sure to <a href="%s">back up your database and files</a> first.' ), __( 'https://wordpress.org/support/article/wordpress-backups/' ) ); } echo '<p class="update-from-upload-notice">' . $warning . '</p>'; $overwrite = $this->is_downgrading ? 'downgrade-theme' : 'update-theme'; $install_actions['overwrite_theme'] = sprintf( '<a class="button button-primary update-from-upload-overwrite" href="%s" target="_parent">%s</a>', wp_nonce_url( add_query_arg( 'overwrite', $overwrite, $this->url ), 'theme-upload' ), _x( 'Replace active with uploaded', 'theme' ) ); } else { echo $blocked_message; } $cancel_url = add_query_arg( 'action', 'upload-theme-cancel-overwrite', $this->url ); $install_actions['themes_page'] = sprintf( '<a class="button" href="%s" target="_parent">%s</a>', wp_nonce_url( $cancel_url, 'theme-upload-cancel-overwrite' ), __( 'Cancel and go back' ) ); /** * Filters the list of action links available following a single theme installation failure * when overwriting is allowed. * * @since 5.5.0 * * @param string[] $install_actions Array of theme action links. * @param object $api Object containing WordPress.org API theme data. * @param array $new_theme_data Array with uploaded theme data. */ $install_actions = apply_filters( 'install_theme_overwrite_actions', $install_actions, $this->api, $new_theme_data ); if ( ! empty( $install_actions ) ) { printf( '<p class="update-from-upload-expired hidden">%s</p>', __( 'The uploaded file has expired. Please go back and upload it again.' ) ); echo '<p class="update-from-upload-actions">' . implode( ' ', (array) $install_actions ) . '</p>'; } return true; } } ``` | Uses | Description | | --- | --- | | [WP\_Upgrader\_Skin](wp_upgrader_skin) wp-admin/includes/class-wp-upgrader-skin.php | Generic Skin for the WordPress Upgrader classes. This skin is designed to be extended for specific purposes. | | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php. | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. | wordpress class Requests_Exception_HTTP_504 {} class Requests\_Exception\_HTTP\_504 {} ======================================= Exception for 504 Gateway Timeout responses File: `wp-includes/Requests/Exception/HTTP/504.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/504.php/) ``` class Requests_Exception_HTTP_504 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 504; /** * Reason phrase * * @var string */ protected $reason = 'Gateway Timeout'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_Block_Type {} class WP\_Block\_Type {} ======================== Core class representing a block type. * [register\_block\_type()](../functions/register_block_type) * [\_\_construct](wp_block_type/__construct) β€” Constructor. * [\_\_get](wp_block_type/__get) β€” Proxies getting values for deprecated properties for script and style handles for backward compatibility. * [\_\_isset](wp_block_type/__isset) β€” Proxies checking for deprecated properties for script and style handles for backward compatibility. * [\_\_set](wp_block_type/__set) β€” Proxies setting values for deprecated properties for script and style handles for backward compatibility. * [get\_attributes](wp_block_type/get_attributes) β€” Get all available block attributes including possible layout attribute from Columns block. * [is\_dynamic](wp_block_type/is_dynamic) β€” Returns true if the block type is dynamic, or false otherwise. A dynamic block is one which defers its rendering to occur on-demand at runtime. * [prepare\_attributes\_for\_render](wp_block_type/prepare_attributes_for_render) β€” Validates attributes against the current block schema, populating defaulted and missing values. * [render](wp_block_type/render) β€” Renders the block type output for given attributes. * [set\_props](wp_block_type/set_props) β€” Sets block type properties. File: `wp-includes/class-wp-block-type.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type.php/) ``` class WP_Block_Type { /** * Block API version. * * @since 5.6.0 * @var int */ public $api_version = 1; /** * Block type key. * * @since 5.0.0 * @var string */ public $name; /** * Human-readable block type label. * * @since 5.5.0 * @var string */ public $title = ''; /** * Block type category classification, used in search interfaces * to arrange block types by category. * * @since 5.5.0 * @var string|null */ public $category = null; /** * Setting parent lets a block require that it is only available * when nested within the specified blocks. * * @since 5.5.0 * @var string[]|null */ public $parent = null; /** * Setting ancestor makes a block available only inside the specified * block types at any position of the ancestor's block subtree. * * @since 6.0.0 * @var string[]|null */ public $ancestor = null; /** * Block type icon. * * @since 5.5.0 * @var string|null */ public $icon = null; /** * A detailed block type description. * * @since 5.5.0 * @var string */ public $description = ''; /** * Additional keywords to produce block type as result * in search interfaces. * * @since 5.5.0 * @var string[] */ public $keywords = array(); /** * The translation textdomain. * * @since 5.5.0 * @var string|null */ public $textdomain = null; /** * Alternative block styles. * * @since 5.5.0 * @var array */ public $styles = array(); /** * Block variations. * * @since 5.8.0 * @var array[] */ public $variations = array(); /** * Supported features. * * @since 5.5.0 * @var array|null */ public $supports = null; /** * Structured data for the block preview. * * @since 5.5.0 * @var array|null */ public $example = null; /** * Block type render callback. * * @since 5.0.0 * @var callable */ public $render_callback = null; /** * Block type attributes property schemas. * * @since 5.0.0 * @var array|null */ public $attributes = null; /** * Context values inherited by blocks of this type. * * @since 5.5.0 * @var string[] */ public $uses_context = array(); /** * Context provided by blocks of this type. * * @since 5.5.0 * @var string[]|null */ public $provides_context = null; /** * Block type editor only script handles. * * @since 6.1.0 * @var string[] */ public $editor_script_handles = array(); /** * Block type front end and editor script handles. * * @since 6.1.0 * @var string[] */ public $script_handles = array(); /** * Block type front end only script handles. * * @since 6.1.0 * @var string[] */ public $view_script_handles = array(); /** * Block type editor only style handles. * * @since 6.1.0 * @var string[] */ public $editor_style_handles = array(); /** * Block type front end and editor style handles. * * @since 6.1.0 * @var string[] */ public $style_handles = array(); /** * Deprecated block type properties for script and style handles. * * @since 6.1.0 * @var string[] */ private $deprecated_properties = array( 'editor_script', 'script', 'view_script', 'editor_style', 'style', ); /** * Attributes supported by every block. * * @since 6.0.0 * @var array */ const GLOBAL_ATTRIBUTES = array( 'lock' => array( 'type' => 'object' ), ); /** * Constructor. * * Will populate object properties from the provided arguments. * * @since 5.0.0 * @since 5.5.0 Added the `title`, `category`, `parent`, `icon`, `description`, * `keywords`, `textdomain`, `styles`, `supports`, `example`, * `uses_context`, and `provides_context` properties. * @since 5.6.0 Added the `api_version` property. * @since 5.8.0 Added the `variations` property. * @since 5.9.0 Added the `view_script` property. * @since 6.0.0 Added the `ancestor` property. * @since 6.1.0 Added the `editor_script_handles`, `script_handles`, `view_script_handles, * `editor_style_handles`, and `style_handles` properties. * Deprecated the `editor_script`, `script`, `view_script`, `editor_style`, and `style` properties. * * @see register_block_type() * * @param string $block_type Block type name including namespace. * @param array|string $args { * Optional. Array or string of arguments for registering a block type. Any arguments may be defined, * however the ones described below are supported by default. Default empty array. * * @type string $api_version Block API version. * @type string $title Human-readable block type label. * @type string|null $category Block type category classification, used in * search interfaces to arrange block types by category. * @type string[]|null $parent Setting parent lets a block require that it is only * available when nested within the specified blocks. * @type string[]|null $ancestor Setting ancestor makes a block available only inside the specified * block types at any position of the ancestor's block subtree. * @type string|null $icon Block type icon. * @type string $description A detailed block type description. * @type string[] $keywords Additional keywords to produce block type as * result in search interfaces. * @type string|null $textdomain The translation textdomain. * @type array[] $styles Alternative block styles. * @type array[] $variations Block variations. * @type array|null $supports Supported features. * @type array|null $example Structured data for the block preview. * @type callable|null $render_callback Block type render callback. * @type array|null $attributes Block type attributes property schemas. * @type string[] $uses_context Context values inherited by blocks of this type. * @type string[]|null $provides_context Context provided by blocks of this type. * @type string[] $editor_script_handles Block type editor only script handles. * @type string[] $script_handles Block type front end and editor script handles. * @type string[] $view_script_handles Block type front end only script handles. * @type string[] $editor_style_handles Block type editor only style handles. * @type string[] $style_handles Block type front end and editor style handles. * } */ public function __construct( $block_type, $args = array() ) { $this->name = $block_type; $this->set_props( $args ); } /** * Proxies getting values for deprecated properties for script and style handles for backward compatibility. * Gets the value for the corresponding new property if the first item in the array provided. * * @since 6.1.0 * * @param string $name Deprecated property name. * * @return string|string[]|null|void The value read from the new property if the first item in the array provided, * null when value not found, or void when unknown property name provided. */ public function __get( $name ) { if ( ! in_array( $name, $this->deprecated_properties ) ) { return; } $new_name = $name . '_handles'; if ( ! property_exists( $this, $new_name ) || ! is_array( $this->{$new_name} ) ) { return null; } if ( count( $this->{$new_name} ) > 1 ) { return $this->{$new_name}; } return isset( $this->{$new_name}[0] ) ? $this->{$new_name}[0] : null; } /** * Proxies checking for deprecated properties for script and style handles for backward compatibility. * Checks whether the corresponding new property has the first item in the array provided. * * @since 6.1.0 * * @param string $name Deprecated property name. * * @return boolean Returns true when for the new property the first item in the array exists, * or false otherwise. */ public function __isset( $name ) { if ( ! in_array( $name, $this->deprecated_properties ) ) { return false; } $new_name = $name . '_handles'; return isset( $this->{$new_name}[0] ); } /** * Proxies setting values for deprecated properties for script and style handles for backward compatibility. * Sets the value for the corresponding new property as the first item in the array. * It also allows setting custom properties for backward compatibility. * * @since 6.1.0 * * @param string $name Property name. * @param mixed $value Property value. */ public function __set( $name, $value ) { if ( ! in_array( $name, $this->deprecated_properties ) ) { $this->{$name} = $value; return; } $new_name = $name . '_handles'; if ( is_array( $value ) ) { $filtered = array_filter( $value, 'is_string' ); if ( count( $filtered ) !== count( $value ) ) { _doing_it_wrong( __METHOD__, sprintf( /* translators: %s: The '$value' argument. */ __( 'The %s argument must be a string or a string array.' ), '<code>$value</code>' ), '6.1.0' ); } $this->{$new_name} = array_values( $filtered ); return; } if ( ! is_string( $value ) ) { return; } $this->{$new_name} = array( $value ); } /** * Renders the block type output for given attributes. * * @since 5.0.0 * * @param array $attributes Optional. Block attributes. Default empty array. * @param string $content Optional. Block content. Default empty string. * @return string Rendered block type output. */ public function render( $attributes = array(), $content = '' ) { if ( ! $this->is_dynamic() ) { return ''; } $attributes = $this->prepare_attributes_for_render( $attributes ); return (string) call_user_func( $this->render_callback, $attributes, $content ); } /** * Returns true if the block type is dynamic, or false otherwise. A dynamic * block is one which defers its rendering to occur on-demand at runtime. * * @since 5.0.0 * * @return bool Whether block type is dynamic. */ public function is_dynamic() { return is_callable( $this->render_callback ); } /** * Validates attributes against the current block schema, populating * defaulted and missing values. * * @since 5.0.0 * * @param array $attributes Original block attributes. * @return array Prepared block attributes. */ public function prepare_attributes_for_render( $attributes ) { // If there are no attribute definitions for the block type, skip // processing and return verbatim. if ( ! isset( $this->attributes ) ) { return $attributes; } foreach ( $attributes as $attribute_name => $value ) { // If the attribute is not defined by the block type, it cannot be // validated. if ( ! isset( $this->attributes[ $attribute_name ] ) ) { continue; } $schema = $this->attributes[ $attribute_name ]; // Validate value by JSON schema. An invalid value should revert to // its default, if one exists. This occurs by virtue of the missing // attributes loop immediately following. If there is not a default // assigned, the attribute value should remain unset. $is_valid = rest_validate_value_from_schema( $value, $schema, $attribute_name ); if ( is_wp_error( $is_valid ) ) { unset( $attributes[ $attribute_name ] ); } } // Populate values of any missing attributes for which the block type // defines a default. $missing_schema_attributes = array_diff_key( $this->attributes, $attributes ); foreach ( $missing_schema_attributes as $attribute_name => $schema ) { if ( isset( $schema['default'] ) ) { $attributes[ $attribute_name ] = $schema['default']; } } return $attributes; } /** * Sets block type properties. * * @since 5.0.0 * * @param array|string $args Array or string of arguments for registering a block type. * See WP_Block_Type::__construct() for information on accepted arguments. */ public function set_props( $args ) { $args = wp_parse_args( $args, array( 'render_callback' => null, ) ); $args['name'] = $this->name; // Setup attributes if needed. if ( ! isset( $args['attributes'] ) || ! is_array( $args['attributes'] ) ) { $args['attributes'] = array(); } // Register core attributes. foreach ( static::GLOBAL_ATTRIBUTES as $attr_key => $attr_schema ) { if ( ! array_key_exists( $attr_key, $args['attributes'] ) ) { $args['attributes'][ $attr_key ] = $attr_schema; } } /** * Filters the arguments for registering a block type. * * @since 5.5.0 * * @param array $args Array of arguments for registering a block type. * @param string $block_type Block type name including namespace. */ $args = apply_filters( 'register_block_type_args', $args, $this->name ); foreach ( $args as $property_name => $property_value ) { $this->$property_name = $property_value; } } /** * Get all available block attributes including possible layout attribute from Columns block. * * @since 5.0.0 * * @return array Array of attributes. */ public function get_attributes() { return is_array( $this->attributes ) ? $this->attributes : array(); } } ``` | Version | Description | | --- | --- | | [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
programming_docs
wordpress class Requests_Proxy_HTTP {} class Requests\_Proxy\_HTTP {} ============================== HTTP Proxy connection interface Provides a handler for connection via an HTTP proxy * [\_\_construct](requests_proxy_http/__construct) β€” Constructor * [curl\_before\_send](requests_proxy_http/curl_before_send) β€” Set cURL parameters before the data is sent * [fsockopen\_header](requests_proxy_http/fsockopen_header) β€” Add extra headers to the request before sending * [fsockopen\_remote\_host\_path](requests_proxy_http/fsockopen_remote_host_path) β€” Alter remote path before getting stream data * [fsockopen\_remote\_socket](requests_proxy_http/fsockopen_remote_socket) β€” Alter remote socket information before opening socket connection * [get\_auth\_string](requests_proxy_http/get_auth_string) β€” Get the authentication string (user:pass) * [register](requests_proxy_http/register) β€” Register the necessary callbacks File: `wp-includes/Requests/Proxy/HTTP.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/proxy/http.php/) ``` class Requests_Proxy_HTTP implements Requests_Proxy { /** * Proxy host and port * * Notation: "host:port" (eg 127.0.0.1:8080 or someproxy.com:3128) * * @var string */ public $proxy; /** * Username * * @var string */ public $user; /** * Password * * @var string */ public $pass; /** * Do we need to authenticate? (ie username & password have been provided) * * @var boolean */ public $use_authentication; /** * Constructor * * @since 1.6 * @throws Requests_Exception On incorrect number of arguments (`authbasicbadargs`) * @param array|null $args Array of user and password. Must have exactly two elements */ public function __construct($args = null) { if (is_string($args)) { $this->proxy = $args; } elseif (is_array($args)) { if (count($args) === 1) { list($this->proxy) = $args; } elseif (count($args) === 3) { list($this->proxy, $this->user, $this->pass) = $args; $this->use_authentication = true; } else { throw new Requests_Exception('Invalid number of arguments', 'proxyhttpbadargs'); } } } /** * Register the necessary callbacks * * @since 1.6 * @see curl_before_send * @see fsockopen_remote_socket * @see fsockopen_remote_host_path * @see fsockopen_header * @param Requests_Hooks $hooks Hook system */ public function register(Requests_Hooks $hooks) { $hooks->register('curl.before_send', array($this, 'curl_before_send')); $hooks->register('fsockopen.remote_socket', array($this, 'fsockopen_remote_socket')); $hooks->register('fsockopen.remote_host_path', array($this, 'fsockopen_remote_host_path')); if ($this->use_authentication) { $hooks->register('fsockopen.after_headers', array($this, 'fsockopen_header')); } } /** * Set cURL parameters before the data is sent * * @since 1.6 * @param resource $handle cURL resource */ public function curl_before_send(&$handle) { curl_setopt($handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); curl_setopt($handle, CURLOPT_PROXY, $this->proxy); if ($this->use_authentication) { curl_setopt($handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY); curl_setopt($handle, CURLOPT_PROXYUSERPWD, $this->get_auth_string()); } } /** * Alter remote socket information before opening socket connection * * @since 1.6 * @param string $remote_socket Socket connection string */ public function fsockopen_remote_socket(&$remote_socket) { $remote_socket = $this->proxy; } /** * Alter remote path before getting stream data * * @since 1.6 * @param string $path Path to send in HTTP request string ("GET ...") * @param string $url Full URL we're requesting */ public function fsockopen_remote_host_path(&$path, $url) { $path = $url; } /** * Add extra headers to the request before sending * * @since 1.6 * @param string $out HTTP header string */ public function fsockopen_header(&$out) { $out .= sprintf("Proxy-Authorization: Basic %s\r\n", base64_encode($this->get_auth_string())); } /** * Get the authentication string (user:pass) * * @since 1.6 * @return string */ public function get_auth_string() { return $this->user . ':' . $this->pass; } } ``` | Version | Description | | --- | --- | | [1.6](https://developer.wordpress.org/reference/since/1.6/) | Introduced. | wordpress class WP_Customize_Nav_Menu_Item_Setting {} class WP\_Customize\_Nav\_Menu\_Item\_Setting {} ================================================ Customize Setting to represent a nav\_menu. Subclass of [WP\_Customize\_Setting](wp_customize_setting) to represent a nav\_menu taxonomy term, and the IDs for the nav\_menu\_items associated with the nav menu. * [WP\_Customize\_Setting](wp_customize_setting) * [\_\_construct](wp_customize_nav_menu_item_setting/__construct) β€” Constructor. * [amend\_customize\_save\_response](wp_customize_nav_menu_item_setting/amend_customize_save_response) β€” Export data for the JS client. * [filter\_wp\_get\_nav\_menu\_items](wp_customize_nav_menu_item_setting/filter_wp_get_nav_menu_items) β€” Filters the wp\_get\_nav\_menu\_items() result to supply the previewed menu items. * [flush\_cached\_value](wp_customize_nav_menu_item_setting/flush_cached_value) β€” Clear the cached value when this nav menu item is updated. * [get\_original\_title](wp_customize_nav_menu_item_setting/get_original_title) β€” Get original title. * [get\_type\_label](wp_customize_nav_menu_item_setting/get_type_label) β€” Get type label. * [populate\_value](wp_customize_nav_menu_item_setting/populate_value) β€” Ensure that the value is fully populated with the necessary properties. * [preview](wp_customize_nav_menu_item_setting/preview) β€” Handle previewing the setting. * [sanitize](wp_customize_nav_menu_item_setting/sanitize) β€” Sanitize an input. * [sort\_wp\_get\_nav\_menu\_items](wp_customize_nav_menu_item_setting/sort_wp_get_nav_menu_items) β€” Re-apply the tail logic also applied on $items by wp\_get\_nav\_menu\_items(). * [update](wp_customize_nav_menu_item_setting/update) β€” Creates/updates the nav\_menu\_item post for this setting. * [value](wp_customize_nav_menu_item_setting/value) β€” Get the instance data for a given nav\_menu\_item setting. * [value\_as\_wp\_post\_nav\_menu\_item](wp_customize_nav_menu_item_setting/value_as_wp_post_nav_menu_item) β€” Get the value emulated into a WP\_Post and set up as a nav\_menu\_item. File: `wp-includes/customize/class-wp-customize-nav-menu-item-setting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-item-setting.php/) ``` class WP_Customize_Nav_Menu_Item_Setting extends WP_Customize_Setting { const ID_PATTERN = '/^nav_menu_item\[(?P<id>-?\d+)\]$/'; const POST_TYPE = 'nav_menu_item'; const TYPE = 'nav_menu_item'; /** * Setting type. * * @since 4.3.0 * @var string */ public $type = self::TYPE; /** * Default setting value. * * @since 4.3.0 * @var array * * @see wp_setup_nav_menu_item() */ public $default = array( // The $menu_item_data for wp_update_nav_menu_item(). 'object_id' => 0, 'object' => '', // Taxonomy name. 'menu_item_parent' => 0, // A.K.A. menu-item-parent-id; note that post_parent is different, and not included. 'position' => 0, // A.K.A. menu_order. 'type' => 'custom', // Note that type_label is not included here. 'title' => '', 'url' => '', 'target' => '', 'attr_title' => '', 'description' => '', 'classes' => '', 'xfn' => '', 'status' => 'publish', 'original_title' => '', 'nav_menu_term_id' => 0, // This will be supplied as the $menu_id arg for wp_update_nav_menu_item(). '_invalid' => false, ); /** * Default transport. * * @since 4.3.0 * @since 4.5.0 Default changed to 'refresh' * @var string */ public $transport = 'refresh'; /** * The post ID represented by this setting instance. This is the db_id. * * A negative value represents a placeholder ID for a new menu not yet saved. * * @since 4.3.0 * @var int */ public $post_id; /** * Storage of pre-setup menu item to prevent wasted calls to wp_setup_nav_menu_item(). * * @since 4.3.0 * @var array|null */ protected $value; /** * Previous (placeholder) post ID used before creating a new menu item. * * This value will be exported to JS via the customize_save_response filter * so that JavaScript can update the settings to refer to the newly-assigned * post ID. This value is always negative to indicate it does not refer to * a real post. * * @since 4.3.0 * @var int * * @see WP_Customize_Nav_Menu_Item_Setting::update() * @see WP_Customize_Nav_Menu_Item_Setting::amend_customize_save_response() */ public $previous_post_id; /** * When previewing or updating a menu item, this stores the previous nav_menu_term_id * which ensures that we can apply the proper filters. * * @since 4.3.0 * @var int */ public $original_nav_menu_term_id; /** * Whether or not update() was called. * * @since 4.3.0 * @var bool */ protected $is_updated = false; /** * Status for calling the update method, used in customize_save_response filter. * * See {@see 'customize_save_response'}. * * When status is inserted, the placeholder post ID is stored in $previous_post_id. * When status is error, the error is stored in $update_error. * * @since 4.3.0 * @var string updated|inserted|deleted|error * * @see WP_Customize_Nav_Menu_Item_Setting::update() * @see WP_Customize_Nav_Menu_Item_Setting::amend_customize_save_response() */ public $update_status; /** * Any error object returned by wp_update_nav_menu_item() when setting is updated. * * @since 4.3.0 * @var WP_Error * * @see WP_Customize_Nav_Menu_Item_Setting::update() * @see WP_Customize_Nav_Menu_Item_Setting::amend_customize_save_response() */ public $update_error; /** * Constructor. * * Any supplied $args override class property defaults. * * @since 4.3.0 * * @throws Exception If $id is not valid for this setting type. * * @param WP_Customize_Manager $manager Customizer bootstrap instance. * @param string $id A specific ID of the setting. * Can be a theme mod or option name. * @param array $args Optional. Setting arguments. */ public function __construct( WP_Customize_Manager $manager, $id, array $args = array() ) { if ( empty( $manager->nav_menus ) ) { throw new Exception( 'Expected WP_Customize_Manager::$nav_menus to be set.' ); } if ( ! preg_match( self::ID_PATTERN, $id, $matches ) ) { throw new Exception( "Illegal widget setting ID: $id" ); } $this->post_id = (int) $matches['id']; add_action( 'wp_update_nav_menu_item', array( $this, 'flush_cached_value' ), 10, 2 ); parent::__construct( $manager, $id, $args ); // Ensure that an initially-supplied value is valid. if ( isset( $this->value ) ) { $this->populate_value(); foreach ( array_diff( array_keys( $this->default ), array_keys( $this->value ) ) as $missing ) { throw new Exception( "Supplied nav_menu_item value missing property: $missing" ); } } } /** * Clear the cached value when this nav menu item is updated. * * @since 4.3.0 * * @param int $menu_id The term ID for the menu. * @param int $menu_item_id The post ID for the menu item. */ public function flush_cached_value( $menu_id, $menu_item_id ) { unset( $menu_id ); if ( $menu_item_id === $this->post_id ) { $this->value = null; } } /** * Get the instance data for a given nav_menu_item setting. * * @since 4.3.0 * * @see wp_setup_nav_menu_item() * * @return array|false Instance data array, or false if the item is marked for deletion. */ public function value() { if ( $this->is_previewed && get_current_blog_id() === $this->_previewed_blog_id ) { $undefined = new stdClass(); // Symbol. $post_value = $this->post_value( $undefined ); if ( $undefined === $post_value ) { $value = $this->_original_value; } else { $value = $post_value; } if ( ! empty( $value ) && empty( $value['original_title'] ) ) { $value['original_title'] = $this->get_original_title( (object) $value ); } } elseif ( isset( $this->value ) ) { $value = $this->value; } else { $value = false; // Note that a ID of less than one indicates a nav_menu not yet inserted. if ( $this->post_id > 0 ) { $post = get_post( $this->post_id ); if ( $post && self::POST_TYPE === $post->post_type ) { $is_title_empty = empty( $post->post_title ); $value = (array) wp_setup_nav_menu_item( $post ); if ( $is_title_empty ) { $value['title'] = ''; } } } if ( ! is_array( $value ) ) { $value = $this->default; } // Cache the value for future calls to avoid having to re-call wp_setup_nav_menu_item(). $this->value = $value; $this->populate_value(); $value = $this->value; } if ( ! empty( $value ) && empty( $value['type_label'] ) ) { $value['type_label'] = $this->get_type_label( (object) $value ); } return $value; } /** * Get original title. * * @since 4.7.0 * * @param object $item Nav menu item. * @return string The original title. */ protected function get_original_title( $item ) { $original_title = ''; if ( 'post_type' === $item->type && ! empty( $item->object_id ) ) { $original_object = get_post( $item->object_id ); if ( $original_object ) { /** This filter is documented in wp-includes/post-template.php */ $original_title = apply_filters( 'the_title', $original_object->post_title, $original_object->ID ); if ( '' === $original_title ) { /* translators: %d: ID of a post. */ $original_title = sprintf( __( '#%d (no title)' ), $original_object->ID ); } } } elseif ( 'taxonomy' === $item->type && ! empty( $item->object_id ) ) { $original_term_title = get_term_field( 'name', $item->object_id, $item->object, 'raw' ); if ( ! is_wp_error( $original_term_title ) ) { $original_title = $original_term_title; } } elseif ( 'post_type_archive' === $item->type ) { $original_object = get_post_type_object( $item->object ); if ( $original_object ) { $original_title = $original_object->labels->archives; } } $original_title = html_entity_decode( $original_title, ENT_QUOTES, get_bloginfo( 'charset' ) ); return $original_title; } /** * Get type label. * * @since 4.7.0 * * @param object $item Nav menu item. * @return string The type label. */ protected function get_type_label( $item ) { if ( 'post_type' === $item->type ) { $object = get_post_type_object( $item->object ); if ( $object ) { $type_label = $object->labels->singular_name; } else { $type_label = $item->object; } } elseif ( 'taxonomy' === $item->type ) { $object = get_taxonomy( $item->object ); if ( $object ) { $type_label = $object->labels->singular_name; } else { $type_label = $item->object; } } elseif ( 'post_type_archive' === $item->type ) { $type_label = __( 'Post Type Archive' ); } else { $type_label = __( 'Custom Link' ); } return $type_label; } /** * Ensure that the value is fully populated with the necessary properties. * * Translates some properties added by wp_setup_nav_menu_item() and removes others. * * @since 4.3.0 * * @see WP_Customize_Nav_Menu_Item_Setting::value() */ protected function populate_value() { if ( ! is_array( $this->value ) ) { return; } if ( isset( $this->value['menu_order'] ) ) { $this->value['position'] = $this->value['menu_order']; unset( $this->value['menu_order'] ); } if ( isset( $this->value['post_status'] ) ) { $this->value['status'] = $this->value['post_status']; unset( $this->value['post_status'] ); } if ( ! isset( $this->value['original_title'] ) ) { $this->value['original_title'] = $this->get_original_title( (object) $this->value ); } if ( ! isset( $this->value['nav_menu_term_id'] ) && $this->post_id > 0 ) { $menus = wp_get_post_terms( $this->post_id, WP_Customize_Nav_Menu_Setting::TAXONOMY, array( 'fields' => 'ids', ) ); if ( ! empty( $menus ) ) { $this->value['nav_menu_term_id'] = array_shift( $menus ); } else { $this->value['nav_menu_term_id'] = 0; } } foreach ( array( 'object_id', 'menu_item_parent', 'nav_menu_term_id' ) as $key ) { if ( ! is_int( $this->value[ $key ] ) ) { $this->value[ $key ] = (int) $this->value[ $key ]; } } foreach ( array( 'classes', 'xfn' ) as $key ) { if ( is_array( $this->value[ $key ] ) ) { $this->value[ $key ] = implode( ' ', $this->value[ $key ] ); } } if ( ! isset( $this->value['title'] ) ) { $this->value['title'] = ''; } if ( ! isset( $this->value['_invalid'] ) ) { $this->value['_invalid'] = false; $is_known_invalid = ( ( ( 'post_type' === $this->value['type'] || 'post_type_archive' === $this->value['type'] ) && ! post_type_exists( $this->value['object'] ) ) || ( 'taxonomy' === $this->value['type'] && ! taxonomy_exists( $this->value['object'] ) ) ); if ( $is_known_invalid ) { $this->value['_invalid'] = true; } } // Remove remaining properties available on a setup nav_menu_item post object which aren't relevant to the setting value. $irrelevant_properties = array( 'ID', 'comment_count', 'comment_status', 'db_id', 'filter', 'guid', 'ping_status', 'pinged', 'post_author', 'post_content', 'post_content_filtered', 'post_date', 'post_date_gmt', 'post_excerpt', 'post_mime_type', 'post_modified', 'post_modified_gmt', 'post_name', 'post_parent', 'post_password', 'post_title', 'post_type', 'to_ping', ); foreach ( $irrelevant_properties as $property ) { unset( $this->value[ $property ] ); } } /** * Handle previewing the setting. * * @since 4.3.0 * @since 4.4.0 Added boolean return value. * * @see WP_Customize_Manager::post_value() * * @return bool False if method short-circuited due to no-op. */ public function preview() { if ( $this->is_previewed ) { return false; } $undefined = new stdClass(); $is_placeholder = ( $this->post_id < 0 ); $is_dirty = ( $undefined !== $this->post_value( $undefined ) ); if ( ! $is_placeholder && ! $is_dirty ) { return false; } $this->is_previewed = true; $this->_original_value = $this->value(); $this->original_nav_menu_term_id = $this->_original_value['nav_menu_term_id']; $this->_previewed_blog_id = get_current_blog_id(); add_filter( 'wp_get_nav_menu_items', array( $this, 'filter_wp_get_nav_menu_items' ), 10, 3 ); $sort_callback = array( __CLASS__, 'sort_wp_get_nav_menu_items' ); if ( ! has_filter( 'wp_get_nav_menu_items', $sort_callback ) ) { add_filter( 'wp_get_nav_menu_items', array( __CLASS__, 'sort_wp_get_nav_menu_items' ), 1000, 3 ); } // @todo Add get_post_metadata filters for plugins to add their data. return true; } /** * Filters the wp_get_nav_menu_items() result to supply the previewed menu items. * * @since 4.3.0 * * @see wp_get_nav_menu_items() * * @param WP_Post[] $items An array of menu item post objects. * @param WP_Term $menu The menu object. * @param array $args An array of arguments used to retrieve menu item objects. * @return WP_Post[] Array of menu item objects. */ public function filter_wp_get_nav_menu_items( $items, $menu, $args ) { $this_item = $this->value(); $current_nav_menu_term_id = null; if ( isset( $this_item['nav_menu_term_id'] ) ) { $current_nav_menu_term_id = $this_item['nav_menu_term_id']; unset( $this_item['nav_menu_term_id'] ); } $should_filter = ( $menu->term_id === $this->original_nav_menu_term_id || $menu->term_id === $current_nav_menu_term_id ); if ( ! $should_filter ) { return $items; } // Handle deleted menu item, or menu item moved to another menu. $should_remove = ( false === $this_item || ( isset( $this_item['_invalid'] ) && true === $this_item['_invalid'] ) || ( $this->original_nav_menu_term_id === $menu->term_id && $current_nav_menu_term_id !== $this->original_nav_menu_term_id ) ); if ( $should_remove ) { $filtered_items = array(); foreach ( $items as $item ) { if ( $item->db_id !== $this->post_id ) { $filtered_items[] = $item; } } return $filtered_items; } $mutated = false; $should_update = ( is_array( $this_item ) && $current_nav_menu_term_id === $menu->term_id ); if ( $should_update ) { foreach ( $items as $item ) { if ( $item->db_id === $this->post_id ) { foreach ( get_object_vars( $this->value_as_wp_post_nav_menu_item() ) as $key => $value ) { $item->$key = $value; } $mutated = true; } } // Not found so we have to append it.. if ( ! $mutated ) { $items[] = $this->value_as_wp_post_nav_menu_item(); } } return $items; } /** * Re-apply the tail logic also applied on $items by wp_get_nav_menu_items(). * * @since 4.3.0 * * @see wp_get_nav_menu_items() * * @param WP_Post[] $items An array of menu item post objects. * @param WP_Term $menu The menu object. * @param array $args An array of arguments used to retrieve menu item objects. * @return WP_Post[] Array of menu item objects. */ public static function sort_wp_get_nav_menu_items( $items, $menu, $args ) { // @todo We should probably re-apply some constraints imposed by $args. unset( $args['include'] ); // Remove invalid items only in front end. if ( ! is_admin() ) { $items = array_filter( $items, '_is_valid_nav_menu_item' ); } if ( ARRAY_A === $args['output'] ) { $items = wp_list_sort( $items, array( $args['output_key'] => 'ASC', ) ); $i = 1; foreach ( $items as $k => $item ) { $items[ $k ]->{$args['output_key']} = $i++; } } return $items; } /** * Get the value emulated into a WP_Post and set up as a nav_menu_item. * * @since 4.3.0 * * @return WP_Post With wp_setup_nav_menu_item() applied. */ public function value_as_wp_post_nav_menu_item() { $item = (object) $this->value(); unset( $item->nav_menu_term_id ); $item->post_status = $item->status; unset( $item->status ); $item->post_type = 'nav_menu_item'; $item->menu_order = $item->position; unset( $item->position ); if ( empty( $item->original_title ) ) { $item->original_title = $this->get_original_title( $item ); } if ( empty( $item->title ) && ! empty( $item->original_title ) ) { $item->title = $item->original_title; } if ( $item->title ) { $item->post_title = $item->title; } // 'classes' should be an array, as in wp_setup_nav_menu_item(). if ( isset( $item->classes ) && is_scalar( $item->classes ) ) { $item->classes = explode( ' ', $item->classes ); } $item->ID = $this->post_id; $item->db_id = $this->post_id; $post = new WP_Post( (object) $item ); if ( empty( $post->post_author ) ) { $post->post_author = get_current_user_id(); } if ( ! isset( $post->type_label ) ) { $post->type_label = $this->get_type_label( $post ); } // Ensure nav menu item URL is set according to linked object. if ( 'post_type' === $post->type && ! empty( $post->object_id ) ) { $post->url = get_permalink( $post->object_id ); } elseif ( 'taxonomy' === $post->type && ! empty( $post->object ) && ! empty( $post->object_id ) ) { $post->url = get_term_link( (int) $post->object_id, $post->object ); } elseif ( 'post_type_archive' === $post->type && ! empty( $post->object ) ) { $post->url = get_post_type_archive_link( $post->object ); } if ( is_wp_error( $post->url ) ) { $post->url = ''; } /** This filter is documented in wp-includes/nav-menu.php */ $post->attr_title = apply_filters( 'nav_menu_attr_title', $post->attr_title ); /** This filter is documented in wp-includes/nav-menu.php */ $post->description = apply_filters( 'nav_menu_description', wp_trim_words( $post->description, 200 ) ); /** This filter is documented in wp-includes/nav-menu.php */ $post = apply_filters( 'wp_setup_nav_menu_item', $post ); return $post; } /** * Sanitize an input. * * Note that parent::sanitize() erroneously does wp_unslash() on $value, but * we remove that in this override. * * @since 4.3.0 * @since 5.9.0 Renamed `$menu_item_value` to `$value` for PHP 8 named parameter support. * * @param array $value The menu item value to sanitize. * @return array|false|null|WP_Error Null or WP_Error if an input isn't valid. False if it is marked for deletion. * Otherwise the sanitized value. */ public function sanitize( $value ) { // Restores the more descriptive, specific name for use within this method. $menu_item_value = $value; // Menu is marked for deletion. if ( false === $menu_item_value ) { return $menu_item_value; } // Invalid. if ( ! is_array( $menu_item_value ) ) { return null; } $default = array( 'object_id' => 0, 'object' => '', 'menu_item_parent' => 0, 'position' => 0, 'type' => 'custom', 'title' => '', 'url' => '', 'target' => '', 'attr_title' => '', 'description' => '', 'classes' => '', 'xfn' => '', 'status' => 'publish', 'original_title' => '', 'nav_menu_term_id' => 0, '_invalid' => false, ); $menu_item_value = array_merge( $default, $menu_item_value ); $menu_item_value = wp_array_slice_assoc( $menu_item_value, array_keys( $default ) ); $menu_item_value['position'] = (int) $menu_item_value['position']; foreach ( array( 'object_id', 'menu_item_parent', 'nav_menu_term_id' ) as $key ) { // Note we need to allow negative-integer IDs for previewed objects not inserted yet. $menu_item_value[ $key ] = (int) $menu_item_value[ $key ]; } foreach ( array( 'type', 'object', 'target' ) as $key ) { $menu_item_value[ $key ] = sanitize_key( $menu_item_value[ $key ] ); } foreach ( array( 'xfn', 'classes' ) as $key ) { $value = $menu_item_value[ $key ]; if ( ! is_array( $value ) ) { $value = explode( ' ', $value ); } $menu_item_value[ $key ] = implode( ' ', array_map( 'sanitize_html_class', $value ) ); } $menu_item_value['original_title'] = sanitize_text_field( $menu_item_value['original_title'] ); // Apply the same filters as when calling wp_insert_post(). /** This filter is documented in wp-includes/post.php */ $menu_item_value['title'] = wp_unslash( apply_filters( 'title_save_pre', wp_slash( $menu_item_value['title'] ) ) ); /** This filter is documented in wp-includes/post.php */ $menu_item_value['attr_title'] = wp_unslash( apply_filters( 'excerpt_save_pre', wp_slash( $menu_item_value['attr_title'] ) ) ); /** This filter is documented in wp-includes/post.php */ $menu_item_value['description'] = wp_unslash( apply_filters( 'content_save_pre', wp_slash( $menu_item_value['description'] ) ) ); if ( '' !== $menu_item_value['url'] ) { $menu_item_value['url'] = sanitize_url( $menu_item_value['url'] ); if ( '' === $menu_item_value['url'] ) { return new WP_Error( 'invalid_url', __( 'Invalid URL.' ) ); // Fail sanitization if URL is invalid. } } if ( 'publish' !== $menu_item_value['status'] ) { $menu_item_value['status'] = 'draft'; } $menu_item_value['_invalid'] = (bool) $menu_item_value['_invalid']; /** This filter is documented in wp-includes/class-wp-customize-setting.php */ return apply_filters( "customize_sanitize_{$this->id}", $menu_item_value, $this ); } /** * Creates/updates the nav_menu_item post for this setting. * * Any created menu items will have their assigned post IDs exported to the client * via the {@see 'customize_save_response'} filter. Likewise, any errors will be * exported to the client via the customize_save_response() filter. * * To delete a menu, the client can send false as the value. * * @since 4.3.0 * * @see wp_update_nav_menu_item() * * @param array|false $value The menu item array to update. If false, then the menu item will be deleted * entirely. See WP_Customize_Nav_Menu_Item_Setting::$default for what the value * should consist of. * @return null|void */ protected function update( $value ) { if ( $this->is_updated ) { return; } $this->is_updated = true; $is_placeholder = ( $this->post_id < 0 ); $is_delete = ( false === $value ); // Update the cached value. $this->value = $value; add_filter( 'customize_save_response', array( $this, 'amend_customize_save_response' ) ); if ( $is_delete ) { // If the current setting post is a placeholder, a delete request is a no-op. if ( $is_placeholder ) { $this->update_status = 'deleted'; } else { $r = wp_delete_post( $this->post_id, true ); if ( false === $r ) { $this->update_error = new WP_Error( 'delete_failure' ); $this->update_status = 'error'; } else { $this->update_status = 'deleted'; } // @todo send back the IDs for all associated nav menu items deleted, so these settings (and controls) can be removed from Customizer? } } else { // Handle saving menu items for menus that are being newly-created. if ( $value['nav_menu_term_id'] < 0 ) { $nav_menu_setting_id = sprintf( 'nav_menu[%s]', $value['nav_menu_term_id'] ); $nav_menu_setting = $this->manager->get_setting( $nav_menu_setting_id ); if ( ! $nav_menu_setting || ! ( $nav_menu_setting instanceof WP_Customize_Nav_Menu_Setting ) ) { $this->update_status = 'error'; $this->update_error = new WP_Error( 'unexpected_nav_menu_setting' ); return; } if ( false === $nav_menu_setting->save() ) { $this->update_status = 'error'; $this->update_error = new WP_Error( 'nav_menu_setting_failure' ); return; } if ( (int) $value['nav_menu_term_id'] !== $nav_menu_setting->previous_term_id ) { $this->update_status = 'error'; $this->update_error = new WP_Error( 'unexpected_previous_term_id' ); return; } $value['nav_menu_term_id'] = $nav_menu_setting->term_id; } // Handle saving a nav menu item that is a child of a nav menu item being newly-created. if ( $value['menu_item_parent'] < 0 ) { $parent_nav_menu_item_setting_id = sprintf( 'nav_menu_item[%s]', $value['menu_item_parent'] ); $parent_nav_menu_item_setting = $this->manager->get_setting( $parent_nav_menu_item_setting_id ); if ( ! $parent_nav_menu_item_setting || ! ( $parent_nav_menu_item_setting instanceof WP_Customize_Nav_Menu_Item_Setting ) ) { $this->update_status = 'error'; $this->update_error = new WP_Error( 'unexpected_nav_menu_item_setting' ); return; } if ( false === $parent_nav_menu_item_setting->save() ) { $this->update_status = 'error'; $this->update_error = new WP_Error( 'nav_menu_item_setting_failure' ); return; } if ( (int) $value['menu_item_parent'] !== $parent_nav_menu_item_setting->previous_post_id ) { $this->update_status = 'error'; $this->update_error = new WP_Error( 'unexpected_previous_post_id' ); return; } $value['menu_item_parent'] = $parent_nav_menu_item_setting->post_id; } // Insert or update menu. $menu_item_data = array( 'menu-item-object-id' => $value['object_id'], 'menu-item-object' => $value['object'], 'menu-item-parent-id' => $value['menu_item_parent'], 'menu-item-position' => $value['position'], 'menu-item-type' => $value['type'], 'menu-item-title' => $value['title'], 'menu-item-url' => $value['url'], 'menu-item-description' => $value['description'], 'menu-item-attr-title' => $value['attr_title'], 'menu-item-target' => $value['target'], 'menu-item-classes' => $value['classes'], 'menu-item-xfn' => $value['xfn'], 'menu-item-status' => $value['status'], ); $r = wp_update_nav_menu_item( $value['nav_menu_term_id'], $is_placeholder ? 0 : $this->post_id, wp_slash( $menu_item_data ) ); if ( is_wp_error( $r ) ) { $this->update_status = 'error'; $this->update_error = $r; } else { if ( $is_placeholder ) { $this->previous_post_id = $this->post_id; $this->post_id = $r; $this->update_status = 'inserted'; } else { $this->update_status = 'updated'; } } } } /** * Export data for the JS client. * * @since 4.3.0 * * @see WP_Customize_Nav_Menu_Item_Setting::update() * * @param array $data Additional information passed back to the 'saved' event on `wp.customize`. * @return array Save response data. */ public function amend_customize_save_response( $data ) { if ( ! isset( $data['nav_menu_item_updates'] ) ) { $data['nav_menu_item_updates'] = array(); } $data['nav_menu_item_updates'][] = array( 'post_id' => $this->post_id, 'previous_post_id' => $this->previous_post_id, 'error' => $this->update_error ? $this->update_error->get_error_code() : null, 'status' => $this->update_status, ); return $data; } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Setting](wp_customize_setting) wp-includes/class-wp-customize-setting.php | Customize Setting class. | | Version | Description | | --- | --- | | [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Post_Search_Handler {} class WP\_REST\_Post\_Search\_Handler {} ======================================== Core class representing a search handler for posts in the REST API. * [WP\_REST\_Search\_Handler](wp_rest_search_handler) * [\_\_construct](wp_rest_post_search_handler/__construct) β€” Constructor. * [detect\_rest\_item\_route](wp_rest_post_search_handler/detect_rest_item_route) β€” Attempts to detect the route to access a single item. β€” deprecated * [prepare\_item](wp_rest_post_search_handler/prepare_item) β€” Prepares the search result for a given ID. * [prepare\_item\_links](wp_rest_post_search_handler/prepare_item_links) β€” Prepares links for the search result of a given ID. * [protected\_title\_format](wp_rest_post_search_handler/protected_title_format) β€” Overwrites the default protected title format. * [search\_items](wp_rest_post_search_handler/search_items) β€” Searches the object type content for a given search request. File: `wp-includes/rest-api/search/class-wp-rest-post-search-handler.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/search/class-wp-rest-post-search-handler.php/) ``` class WP_REST_Post_Search_Handler extends WP_REST_Search_Handler { /** * Constructor. * * @since 5.0.0 */ public function __construct() { $this->type = 'post'; // Support all public post types except attachments. $this->subtypes = array_diff( array_values( get_post_types( array( 'public' => true, 'show_in_rest' => true, ), 'names' ) ), array( 'attachment' ) ); } /** * Searches the object type content for a given search request. * * @since 5.0.0 * * @param WP_REST_Request $request Full REST request. * @return array Associative array containing an `WP_REST_Search_Handler::RESULT_IDS` containing * an array of found IDs and `WP_REST_Search_Handler::RESULT_TOTAL` containing the * total count for the matching search results. */ public function search_items( WP_REST_Request $request ) { // Get the post types to search for the current request. $post_types = $request[ WP_REST_Search_Controller::PROP_SUBTYPE ]; if ( in_array( WP_REST_Search_Controller::TYPE_ANY, $post_types, true ) ) { $post_types = $this->subtypes; } $query_args = array( 'post_type' => $post_types, 'post_status' => 'publish', 'paged' => (int) $request['page'], 'posts_per_page' => (int) $request['per_page'], 'ignore_sticky_posts' => true, ); if ( ! empty( $request['search'] ) ) { $query_args['s'] = $request['search']; } if ( ! empty( $request['exclude'] ) ) { $query_args['post__not_in'] = $request['exclude']; } if ( ! empty( $request['include'] ) ) { $query_args['post__in'] = $request['include']; } /** * Filters the query arguments for a REST API search request. * * Enables adding extra arguments or setting defaults for a post search request. * * @since 5.1.0 * * @param array $query_args Key value array of query var to query value. * @param WP_REST_Request $request The request used. */ $query_args = apply_filters( 'rest_post_search_query', $query_args, $request ); $query = new WP_Query(); $posts = $query->query( $query_args ); // Querying the whole post object will warm the object cache, avoiding an extra query per result. $found_ids = wp_list_pluck( $posts, 'ID' ); $total = $query->found_posts; return array( self::RESULT_IDS => $found_ids, self::RESULT_TOTAL => $total, ); } /** * Prepares the search result for a given ID. * * @since 5.0.0 * * @param int $id Item ID. * @param array $fields Fields to include for the item. * @return array Associative array containing all fields for the item. */ public function prepare_item( $id, array $fields ) { $post = get_post( $id ); $data = array(); if ( in_array( WP_REST_Search_Controller::PROP_ID, $fields, true ) ) { $data[ WP_REST_Search_Controller::PROP_ID ] = (int) $post->ID; } if ( in_array( WP_REST_Search_Controller::PROP_TITLE, $fields, true ) ) { if ( post_type_supports( $post->post_type, 'title' ) ) { add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) ); $data[ WP_REST_Search_Controller::PROP_TITLE ] = get_the_title( $post->ID ); remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) ); } else { $data[ WP_REST_Search_Controller::PROP_TITLE ] = ''; } } if ( in_array( WP_REST_Search_Controller::PROP_URL, $fields, true ) ) { $data[ WP_REST_Search_Controller::PROP_URL ] = get_permalink( $post->ID ); } if ( in_array( WP_REST_Search_Controller::PROP_TYPE, $fields, true ) ) { $data[ WP_REST_Search_Controller::PROP_TYPE ] = $this->type; } if ( in_array( WP_REST_Search_Controller::PROP_SUBTYPE, $fields, true ) ) { $data[ WP_REST_Search_Controller::PROP_SUBTYPE ] = $post->post_type; } return $data; } /** * Prepares links for the search result of a given ID. * * @since 5.0.0 * * @param int $id Item ID. * @return array Links for the given item. */ public function prepare_item_links( $id ) { $post = get_post( $id ); $links = array(); $item_route = rest_get_route_for_post( $post ); if ( ! empty( $item_route ) ) { $links['self'] = array( 'href' => rest_url( $item_route ), 'embeddable' => true, ); } $links['about'] = array( 'href' => rest_url( 'wp/v2/types/' . $post->post_type ), ); return $links; } /** * 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. * * @since 5.0.0 * * @return string Protected title format. */ public function protected_title_format() { return '%s'; } /** * Attempts to detect the route to access a single item. * * @since 5.0.0 * @deprecated 5.5.0 Use rest_get_route_for_post() * @see rest_get_route_for_post() * * @param WP_Post $post Post object. * @return string REST route relative to the REST base URI, or empty string if unknown. */ protected function detect_rest_item_route( $post ) { _deprecated_function( __METHOD__, '5.5.0', 'rest_get_route_for_post()' ); return rest_get_route_for_post( $post ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Search\_Handler](wp_rest_search_handler) wp-includes/rest-api/search/class-wp-rest-search-handler.php | Core base class representing a search handler for an object type in the REST API. | | Version | Description | | --- | --- | | [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. | wordpress class WP_Style_Engine_CSS_Rule {} class WP\_Style\_Engine\_CSS\_Rule {} ===================================== Class [WP\_Style\_Engine\_CSS\_Rule](wp_style_engine_css_rule). Holds, sanitizes, processes and prints CSS declarations for the style engine. * [\_\_construct](wp_style_engine_css_rule/__construct) β€” Constructor * [add\_declarations](wp_style_engine_css_rule/add_declarations) β€” Sets the declarations. * [get\_css](wp_style_engine_css_rule/get_css) β€” Gets the CSS. * [get\_declarations](wp_style_engine_css_rule/get_declarations) β€” Gets the declarations object. * [get\_selector](wp_style_engine_css_rule/get_selector) β€” Gets the full selector. * [set\_selector](wp_style_engine_css_rule/set_selector) β€” Sets the selector. File: `wp-includes/style-engine/class-wp-style-engine-css-rule.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-css-rule.php/) ``` class WP_Style_Engine_CSS_Rule { /** * The selector. * * @since 6.1.0 * @var string */ protected $selector; /** * The selector declarations. * * Contains a WP_Style_Engine_CSS_Declarations object. * * @since 6.1.0 * @var WP_Style_Engine_CSS_Declarations */ protected $declarations; /** * Constructor * * @since 6.1.0 * * @param string $selector The CSS selector. * @param string[]|WP_Style_Engine_CSS_Declarations $declarations An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ), * or a WP_Style_Engine_CSS_Declarations object. */ public function __construct( $selector = '', $declarations = array() ) { $this->set_selector( $selector ); $this->add_declarations( $declarations ); } /** * Sets the selector. * * @since 6.1.0 * * @param string $selector The CSS selector. * * @return WP_Style_Engine_CSS_Rule Returns the object to allow chaining of methods. */ public function set_selector( $selector ) { $this->selector = $selector; return $this; } /** * Sets the declarations. * * @since 6.1.0 * * @param array|WP_Style_Engine_CSS_Declarations $declarations An array of declarations (property => value pairs), * or a WP_Style_Engine_CSS_Declarations object. * * @return WP_Style_Engine_CSS_Rule Returns the object to allow chaining of methods. */ public function add_declarations( $declarations ) { $is_declarations_object = ! is_array( $declarations ); $declarations_array = $is_declarations_object ? $declarations->get_declarations() : $declarations; if ( null === $this->declarations ) { if ( $is_declarations_object ) { $this->declarations = $declarations; return $this; } $this->declarations = new WP_Style_Engine_CSS_Declarations( $declarations_array ); } $this->declarations->add_declarations( $declarations_array ); return $this; } /** * Gets the declarations object. * * @since 6.1.0 * * @return WP_Style_Engine_CSS_Declarations The declarations object. */ public function get_declarations() { return $this->declarations; } /** * Gets the full selector. * * @since 6.1.0 * * @return string */ public function get_selector() { return $this->selector; } /** * Gets the CSS. * * @since 6.1.0 * * @param bool $should_prettify Whether to add spacing, new lines and indents. * @param number $indent_count The number of tab indents to apply to the rule. Applies if `prettify` is `true`. * * @return string */ public function get_css( $should_prettify = false, $indent_count = 0 ) { $rule_indent = $should_prettify ? str_repeat( "\t", $indent_count ) : ''; $declarations_indent = $should_prettify ? $indent_count + 1 : 0; $suffix = $should_prettify ? "\n" : ''; $spacer = $should_prettify ? ' ' : ''; $selector = $should_prettify ? str_replace( ',', ",\n", $this->get_selector() ) : $this->get_selector(); $css_declarations = $this->declarations->get_declarations_string( $should_prettify, $declarations_indent ); if ( empty( $css_declarations ) ) { return ''; } return "{$rule_indent}{$selector}{$spacer}{{$suffix}{$css_declarations}{$suffix}{$rule_indent}}"; } } ``` | Version | Description | | --- | --- | | [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. | wordpress class WP_User_Query {} class WP\_User\_Query {} ======================== Core class used for querying users. * [WP\_User\_Query::prepare\_query()](wp_user_query/prepare_query): for information on accepted arguments. This class allows querying WordPress database tables β€˜wp\_usersβ€˜ and β€˜wp\_usermetaβ€˜. ``` <?php $args = array( . . . ); // The Query $user_query = new WP_User_Query( $args ); // User Loop if ( ! empty( $user_query->get_results() ) ) { foreach ( $user_query->get_results() as $user ) { echo '<p>' . $user->display_name . '</p>'; } } else { echo 'No users found.'; } ?> ``` Show users associated with certain role. * **role** (*string / array*) – use [User Role](https://wordpress.org/support/article/roles-and-capabilities/ "Roles and Capabilities"). An array or a comma-separated list of role names that users must match to be included in results. Note that this is an inclusive list: users must match \*each\* role. Default empty. * **role\_\_in** (*array*) – An array of role names. Matched users must have at least one of these roles. Default empty array. (since [Version 4.4](https://codex.wordpress.org/Version_4.4 "Version 4.4")). * **role\_\_not\_in** (*array*) – An array of role names to exclude. Users matching one or more of these roles will not be included in results. Default empty array. (since [Version 4.4](https://codex.wordpress.org/Version_4.4 "Version 4.4")). **Display Administrator role users** ``` $user_query = new WP_User_Query( array( 'role' => 'Administrator' ) ); ``` **Display Subscriber role users** ``` $user_query = new WP_User_Query( array( 'role' => 'Subscriber' ) ); ``` **Display all users except Subscriber role users** ``` $user_query = new WP_User_Query( array( 'role__not_in' => 'Subscriber' ) ); ``` Show specific users. * **include** (*array*) – List of users to be included. * **exclude** (*array*) – List of users to be excluded. **Display specific users list** ``` $user_query = new WP_User_Query( array( 'include' => array( 1, 2, 3 ) ) ); ``` **Display all users except a specific list of users** ``` $user_query = new WP_User_Query( array( 'exclude' => array( 4, 5, 6 ) ) ); ``` Show users associated with certain blog on the network. * **blog\_id** (*int*) – The blog id on a multisite environment. Defaults to the current blog id. **Display users from blog 33** ``` $user_query = new WP_User_Query( array( 'blog_id' => 33 ) ); ``` Search users. * **search** (*string*) – Searches for possible string matches on columns. Use of the \* wildcard before and/or after the string will match on columns starting with\*, \*ending with, or \*containing\* the string you enter. * **search\_columns** (*array*) – List of [database table columns](https://codex.wordpress.org/Database_Description#Table:_wp_users "Database Description") to matches the search string across multiple columns. + β€˜IDβ€˜ – Search by user id. + β€˜user\_loginβ€˜ – Search by user login. + β€˜user\_nicenameβ€˜ – Search by user nicename. + β€˜user\_emailβ€˜ – Search by user email. + β€˜user\_urlβ€˜ – Search by user url. We can use the [user\_search\_columns](../hooks/user_search_columns "Plugin API/Filter Reference/user search columns") filter to modify the search columns. **Display users based on a keyword search** ``` $user_query = new WP_User_Query( array( 'search' => 'Rami' ) ); ``` **Display users based on a keyword search, only on login and email columns** ``` $args = array( 'search' => 'Rami', 'search_columns' => array( 'user_login', 'user_email' ) ); $user_query = new WP_User_Query( $args ); ``` Limit retrieved Users. * **number** (*int*) – The maximum returned number of results (needed in pagination). * **offset** (*int*) – Offset the returned results (needed in pagination). * **paged** (*int*) – When used with number, defines the page of results to return. Default 1. (since [Version 4.4](https://codex.wordpress.org/Version_4.4 "Version 4.4")). **Display 10 users** ``` $user_query = new WP_User_Query( array( 'number' => 10 ) ); ``` **Display 5 users starting from 25** ``` $user_query = new WP_User_Query( array( 'number' => 5, 'offset' => 25 ) ); ``` Sort retrieved Users. * **orderby** (*string|array*) – Sort retrieved users by parameter. Defaults to β€˜login’. It can be a string with a single field, a string containing a list of values separated by commas or spaces, or an array with fields. + β€˜IDβ€˜ – Order by user id. + β€˜display\_nameβ€˜ – Order by user display name. + β€˜nameβ€˜ / β€˜user\_nameβ€˜ – Order by user name. + β€˜includeβ€˜ – Order by the included list of user\_ids (requires the include parameter) (since [Version 4.1](https://codex.wordpress.org/Version_4.1 "Version 4.1")). + β€˜loginβ€˜ / β€˜user\_loginβ€˜ – Order by user login. + β€˜nicenameβ€˜ / β€˜user\_nicenameβ€˜ – Order by user nicename. + β€˜emailβ€˜ / β€˜user\_emailβ€˜ – Order by user email. + β€˜urlβ€˜ / β€˜user\_urlβ€˜ – Order by user url. + β€˜registeredβ€˜ / β€˜user\_registeredβ€˜ – Order by user registered date. + β€˜post\_countβ€˜ – Order by user post count. + β€˜meta\_valueβ€˜ – Note that a β€˜meta\_key=keyname’ must also be present in the query (available with [Version 3.7](https://codex.wordpress.org/Version_3.7 "Version 3.7")). + β€˜meta\_value\_numβ€˜ – Note that a β€˜meta\_key=keyname’ must also be present in the query (available with [Version 4.2](https://codex.wordpress.org/Version_4.2 "Version 4.2")). * **order** (*string*) – Designates the ascending or descending order of the β€˜orderbyβ€˜ parameter. Defaults to β€˜ASC’. + β€˜ASCβ€˜ – ascending order from lowest to highest values (1, 2, 3; a, b, c). + β€˜DESCβ€˜ – descending order from highest to lowest values (3, 2, 1; c, b, a). **Display users sorted by Post Count, Descending order** ``` $user_query = new WP_User_Query( array ( 'orderby' => 'post_count', 'order' => 'DESC' ) ); ``` **Display users sorted by registered, Ascending order** ``` $user_query = new WP_User_Query( array ( 'orderby' => 'registered', 'order' => 'ASC' ) ); ``` Date queries are handled through to the [WP\_Date\_Query](wp_date_query) object and are applied to the user\_registered field. Available since [version 4.1](https://codex.wordpress.org/Version_4.1). * **date\_query** (*array*) – See the documentation for the [WP\_Query](wp_query) class. **Find users that registered during the last 12 hours:** ``` $args = array( 'date_query' => array( array( 'after' => '12 hours ago', 'inclusive' => true ) ) ); $user_query = new WP_User_Query( $args ); ``` Show users associated with a certain custom field. The [WP\_Meta\_Query](wp_meta_query) class is used to parse this part of the query since [3.2.0](https://codex.wordpress.org/Version_3.2 "Version 3.2"), so check the docs for that class for the full, up to date [list of arguments](wp_meta_query "Class Reference/WP Meta Query"). * **meta\_key** (*string*) – Custom field key. * **meta\_value** (*string*) – Custom field value. * **meta\_compare** (*string*) – Operator to test the β€˜meta\_valueβ€˜. See 'compare' below. * **meta\_query** (*array*) – Custom field parameters (available with [Version 3.5](https://codex.wordpress.org/Version_3.5 "Version 3.5")). + **key** (*string*) – Custom field key. + **value** (*string*|*array*) – Custom field value (*Note*: Array support is limited to a compare value of β€˜IN’, β€˜NOT IN’, β€˜BETWEEN’, β€˜NOT BETWEEN’, β€˜EXISTS’ or β€˜NOT EXISTS’) + **compare** (*string*) – Operator to test. Possible values are β€˜=’, β€˜!=’, β€˜>’, β€˜>=’, β€˜<β€˜, β€˜<=’, β€˜LIKE’, β€˜NOT LIKE’, β€˜IN’, β€˜NOT IN’, β€˜BETWEEN’, β€˜NOT BETWEEN’, β€˜EXISTS’, and β€˜NOT EXISTS’ ; β€˜REGEXP’, β€˜NOT REGEXP’ and β€˜RLIKE’ were added in WordPress 3.7. Default value is β€˜=’. **Note:** Currently 'NOT EXISTS' does not always work as intended if 'relation' is 'OR' when, (1) using the ['role'](https://codex.wordpress.org/Class_Reference/WP_User_Query#User_Role_Parameter) parameter on single site installs, or (2) for any query on multisite. See [ticket #23849](https://core.trac.wordpress.org/ticket/23849). **Note 2:** with β€˜LIKE’ the value parameter is change to β€˜%<value>%’. So the string is searched anywhere in the custom field value. If value parameter contain a β€˜%’ it is escaped. So it bans to search a string beginning by some characters, for exemple… To construct this query you must use β€˜REGEXP’ with a regular expression in value parameter (ex : β€˜^n.\*’ matchs all values that beginning by β€œn” or β€œN”). + **type** (*string*) – Custom field type. Possible values are β€˜NUMERIC’, β€˜BINARY’, β€˜CHAR’, β€˜DATE’, β€˜DATETIME’, β€˜DECIMAL’, β€˜SIGNED’, β€˜TIME’, β€˜UNSIGNED’. Default value is β€˜CHAR’. You can also specify precision and scale for the β€˜DECIMAL’ and β€˜NUMERIC’ types (for example, β€˜DECIMAL(10,5)’ or β€˜NUMERIC(10)’ are valid). **Display users from Israel** ``` $user_query = new WP_User_Query( array( 'meta_key' => 'country', 'meta_value' => 'Israel' ) ); ``` **Display users under 30 years old** ``` $user_query = new WP_User_Query( array( 'meta_key' => 'age', 'meta_value' => '30', 'meta_compare' => '<' ) ); ``` **Multiple custom user fields handling** ``` $args = array( 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'country', 'value' => 'Israel', 'compare' => '=' ), array( 'key' => 'age', 'value' => array( 20, 30 ), 'type' => 'numeric', 'compare' => 'BETWEEN' ) ) ); $user_query = new WP_User_Query( $args ); ``` Which users? * **who** (*string*) – Which users to query. Currently only β€˜authors’ is supported. Default is all users. **Display only authors** ``` $user_query = new WP_User_Query( array( 'who' => 'authors' ) ); ``` Equals to: ``` $args = array( 'meta_key' => 'user_level', 'meta_value' => '0', 'meta_compare' => '!=', 'blog_id' => 0 ) $user_query = new WP_User_Query( $args ); ``` * **count\_total** (*boolean*) – Whether to count the total number of users found. When true (default), the total number of results for the query can be retrieved using the get\_total() method. If you don’t need the total number of results, set this to false. * **has\_published\_posts** (*boolean / array*) – Pass an array of post types to filter results to users who have published posts in those post types. true is an alias for all public post types. Default is null. Since [Version 4.3](https://codex.wordpress.org/Version_4.3 "Version 4.3"). Set return values. * **fields** (*string|array*) – Which fields to return. Defaults to *all*. + β€˜IDβ€˜ – Return an array of user id’s. + β€˜display\_nameβ€˜ – Return an array of user display names. + β€˜loginβ€˜ / β€˜user\_loginβ€˜ – Return an array of user login names. + β€˜nicenameβ€˜ / β€˜user\_nicenameβ€˜ – Return an array of user nicenames. + β€˜emailβ€˜ / β€˜user\_emailβ€˜ – Return an array of user emails. + β€˜urlβ€˜ / β€˜user\_urlβ€˜ – Return an array of user urls. + β€˜registeredβ€˜ / β€˜user\_registeredβ€˜ – Return an array of user registered dates. + β€˜all (default) or all\_with\_metaβ€˜ – Returns an array of [WP\_User](https://codex.wordpress.org/Class_Reference/WP_User "Class Reference/WP User") objects. Must pass an array to subset fields returned. \*’all\_with\_meta’ currently returns the same fields as β€˜all’ which does not include user fields stored in wp\_usermeta. You must create a second query to get the user meta fields by ID or use the \_\_get PHP magic method to get the values of these fields. **Return an array of [WP\_User](wp_user) object** ``` $user_query = new WP_User_Query( array( 'role' => 'editor', 'fields' => 'all' ) ); ``` **Return List all blog editors, return limited fields in resulting row objects:** ``` $user_fields = array( 'user_login', 'user_nicename', 'user_email', 'user_url' ); $user_query = new WP_User_Query( array( 'role' => 'editor', 'fields' => $user_fields ) ); ``` (Array) An array of IDs, stdClass objects, or [WP\_User](https://codex.wordpress.org/Class_Reference/WP_User "Class Reference/WP User") objects, depending on the value of the β€˜fieldsβ€˜ parameter. * If β€˜fieldsβ€˜ is set to β€˜all’ (default), or β€˜all\_with\_meta’, it will return an array of [WP\_User](https://codex.wordpress.org/Class_Reference/WP_User "Class Reference/WP User") objects (does not include related user meta fields even with β€˜all\_with\_meta’ set) . * If β€˜fieldsβ€˜ is set to an array of [wp\_users](https://codex.wordpress.org/Database_Description#Table:_wp_users "Database Description") table fields, it will return an array of stdClass objects with only those fields. * If β€˜fieldsβ€˜ is set to any individual [wp\_users](https://codex.wordpress.org/Database_Description#Table:_wp_users "Database Description") table field, an array of IDs will be returned. * **[found\_users\_query](../hooks/found_users_query "Plugin API/Filter Reference/found users query (page does not exist)")** – Alters SQL β€˜SELECT FOUND\_ROWS()’ clause to the query that returns the count total. * [\_\_call](wp_user_query/__call) β€” Makes private/protected methods readable for backward compatibility. * [\_\_construct](wp_user_query/__construct) β€” PHP5 constructor. * [\_\_get](wp_user_query/__get) β€” Makes private properties readable for backward compatibility. * [\_\_isset](wp_user_query/__isset) β€” Makes private properties checkable for backward compatibility. * [\_\_set](wp_user_query/__set) β€” Makes private properties settable for backward compatibility. * [\_\_unset](wp_user_query/__unset) β€” Makes private properties un-settable for backward compatibility. * [fill\_query\_vars](wp_user_query/fill_query_vars) β€” Fills in missing query variables with default values. * [get](wp_user_query/get) β€” Retrieves query variable. * [get\_results](wp_user_query/get_results) β€” Returns the list of users. * [get\_search\_sql](wp_user_query/get_search_sql) β€” Used internally to generate an SQL string for searching across multiple columns. * [get\_total](wp_user_query/get_total) β€” Returns the total number of users for the current query. * [parse\_order](wp_user_query/parse_order) β€” Parses an 'order' query variable and casts it to ASC or DESC as necessary. * [parse\_orderby](wp_user_query/parse_orderby) β€” Parses and sanitizes 'orderby' keys passed to the user query. * [prepare\_query](wp_user_query/prepare_query) β€” Prepares the query variables. * [query](wp_user_query/query) β€” Executes the query, with the current variables. * [set](wp_user_query/set) β€” Sets query variable. File: `wp-includes/class-wp-user-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-query.php/) ``` class WP_User_Query { /** * Query vars, after parsing * * @since 3.5.0 * @var array */ public $query_vars = array(); /** * List of found user IDs. * * @since 3.1.0 * @var array */ private $results; /** * Total number of found users for the current query * * @since 3.1.0 * @var int */ private $total_users = 0; /** * Metadata query container. * * @since 4.2.0 * @var WP_Meta_Query */ public $meta_query = false; /** * The SQL query used to fetch matching users. * * @since 4.4.0 * @var string */ public $request; private $compat_fields = array( 'results', 'total_users' ); // SQL clauses. public $query_fields; public $query_from; public $query_where; public $query_orderby; public $query_limit; /** * PHP5 constructor. * * @since 3.1.0 * * @param null|string|array $query Optional. The query variables. */ public function __construct( $query = null ) { if ( ! empty( $query ) ) { $this->prepare_query( $query ); $this->query(); } } /** * Fills in missing query variables with default values. * * @since 4.4.0 * * @param array $args Query vars, as passed to `WP_User_Query`. * @return array Complete query variables with undefined ones filled in with defaults. */ public static function fill_query_vars( $args ) { $defaults = array( 'blog_id' => get_current_blog_id(), 'role' => '', 'role__in' => array(), 'role__not_in' => array(), 'capability' => '', 'capability__in' => array(), 'capability__not_in' => array(), 'meta_key' => '', 'meta_value' => '', 'meta_compare' => '', 'include' => array(), 'exclude' => array(), 'search' => '', 'search_columns' => array(), 'orderby' => 'login', 'order' => 'ASC', 'offset' => '', 'number' => '', 'paged' => 1, 'count_total' => true, 'fields' => 'all', 'who' => '', 'has_published_posts' => null, 'nicename' => '', 'nicename__in' => array(), 'nicename__not_in' => array(), 'login' => '', 'login__in' => array(), 'login__not_in' => array(), ); return wp_parse_args( $args, $defaults ); } /** * Prepares the query variables. * * @since 3.1.0 * @since 4.1.0 Added the ability to order by the `include` value. * @since 4.2.0 Added 'meta_value_num' support for `$orderby` parameter. Added multi-dimensional array syntax * for `$orderby` parameter. * @since 4.3.0 Added 'has_published_posts' parameter. * @since 4.4.0 Added 'paged', 'role__in', and 'role__not_in' parameters. The 'role' parameter was updated to * permit an array or comma-separated list of values. The 'number' parameter was updated to support * querying for all users with using -1. * @since 4.7.0 Added 'nicename', 'nicename__in', 'nicename__not_in', 'login', 'login__in', * and 'login__not_in' parameters. * @since 5.1.0 Introduced the 'meta_compare_key' parameter. * @since 5.3.0 Introduced the 'meta_type_key' parameter. * @since 5.9.0 Added 'capability', 'capability__in', and 'capability__not_in' parameters. * * @global wpdb $wpdb WordPress database abstraction object. * @global WP_Roles $wp_roles WordPress role management object. * * @param string|array $query { * Optional. Array or string of Query parameters. * * @type int $blog_id The site ID. Default is the current site. * @type string|string[] $role An array or a comma-separated list of role names that users must match * to be included in results. Note that this is an inclusive list: users * must match *each* role. Default empty. * @type string[] $role__in An array of role names. Matched users must have at least one of these * roles. Default empty array. * @type string[] $role__not_in An array of role names to exclude. Users matching one or more of these * roles will not be included in results. Default empty array. * @type string|string[] $meta_key Meta key or keys to filter by. * @type string|string[] $meta_value Meta value or values to filter by. * @type string $meta_compare MySQL operator used for comparing the meta value. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_compare_key MySQL operator used for comparing the meta key. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_type MySQL data type that the meta_value column will be CAST to for comparisons. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_type_key MySQL data type that the meta_key column will be CAST to for comparisons. * See WP_Meta_Query::__construct() for accepted values and default value. * @type array $meta_query An associative array of WP_Meta_Query arguments. * See WP_Meta_Query::__construct() for accepted values. * @type string|string[] $capability An array or a comma-separated list of capability names that users must match * to be included in results. Note that this is an inclusive list: users * must match *each* capability. * Does NOT work for capabilities not in the database or filtered via {@see 'map_meta_cap'}. * Default empty. * @type string[] $capability__in An array of capability names. Matched users must have at least one of these * capabilities. * Does NOT work for capabilities not in the database or filtered via {@see 'map_meta_cap'}. * Default empty array. * @type string[] $capability__not_in An array of capability names to exclude. Users matching one or more of these * capabilities will not be included in results. * Does NOT work for capabilities not in the database or filtered via {@see 'map_meta_cap'}. * Default empty array. * @type int[] $include An array of user IDs to include. Default empty array. * @type int[] $exclude An array of user IDs to exclude. Default empty array. * @type string $search Search keyword. Searches for possible string matches on columns. * When `$search_columns` is left empty, it tries to determine which * column to search in based on search string. Default empty. * @type string[] $search_columns Array of column names to be searched. Accepts 'ID', 'user_login', * 'user_email', 'user_url', 'user_nicename', 'display_name'. * Default empty array. * @type string|array $orderby Field(s) to sort the retrieved users by. May be a single value, * an array of values, or a multi-dimensional array with fields as * keys and orders ('ASC' or 'DESC') as values. Accepted values are: * - 'ID' * - 'display_name' (or 'name') * - 'include' * - 'user_login' (or 'login') * - 'login__in' * - 'user_nicename' (or 'nicename'), * - 'nicename__in' * - 'user_email (or 'email') * - 'user_url' (or 'url'), * - 'user_registered' (or 'registered') * - 'post_count' * - 'meta_value', * - 'meta_value_num' * - The value of `$meta_key` * - An array key of `$meta_query` * To use 'meta_value' or 'meta_value_num', `$meta_key` * must be also be defined. Default 'user_login'. * @type string $order Designates ascending or descending order of users. Order values * passed as part of an `$orderby` array take precedence over this * parameter. Accepts 'ASC', 'DESC'. Default 'ASC'. * @type int $offset Number of users to offset in retrieved results. Can be used in * conjunction with pagination. Default 0. * @type int $number Number of users to limit the query for. Can be used in * conjunction with pagination. Value -1 (all) is supported, but * should be used with caution on larger sites. * Default -1 (all users). * @type int $paged When used with number, defines the page of results to return. * Default 1. * @type bool $count_total Whether to count the total number of users found. If pagination * is not needed, setting this to false can improve performance. * Default true. * @type string|string[] $fields Which fields to return. Single or all fields (string), or array * of fields. Accepts: * - 'ID' * - 'display_name' * - 'user_login' * - 'user_nicename' * - 'user_email' * - 'user_url' * - 'user_registered' * - 'user_pass' * - 'user_activation_key' * - 'user_status' * - 'spam' (only available on multisite installs) * - 'deleted' (only available on multisite installs) * - 'all' for all fields and loads user meta. * - 'all_with_meta' Deprecated. Use 'all'. * Default 'all'. * @type string $who Type of users to query. Accepts 'authors'. * Default empty (all users). * @type bool|string[] $has_published_posts Pass an array of post types to filter results to users who have * published posts in those post types. `true` is an alias for all * public post types. * @type string $nicename The user nicename. Default empty. * @type string[] $nicename__in An array of nicenames to include. Users matching one of these * nicenames will be included in results. Default empty array. * @type string[] $nicename__not_in An array of nicenames to exclude. Users matching one of these * nicenames will not be included in results. Default empty array. * @type string $login The user login. Default empty. * @type string[] $login__in An array of logins to include. Users matching one of these * logins will be included in results. Default empty array. * @type string[] $login__not_in An array of logins to exclude. Users matching one of these * logins will not be included in results. Default empty array. * } */ public function prepare_query( $query = array() ) { global $wpdb, $wp_roles; if ( empty( $this->query_vars ) || ! empty( $query ) ) { $this->query_limit = null; $this->query_vars = $this->fill_query_vars( $query ); } /** * Fires before the WP_User_Query has been parsed. * * The passed WP_User_Query object contains the query variables, * not yet passed into SQL. * * @since 4.0.0 * * @param WP_User_Query $query Current instance of WP_User_Query (passed by reference). */ do_action_ref_array( 'pre_get_users', array( &$this ) ); // Ensure that query vars are filled after 'pre_get_users'. $qv =& $this->query_vars; $qv = $this->fill_query_vars( $qv ); $allowed_fields = array( 'id', 'user_login', 'user_pass', 'user_nicename', 'user_email', 'user_url', 'user_registered', 'user_activation_key', 'user_status', 'display_name', ); if ( is_multisite() ) { $allowed_fields[] = 'spam'; $allowed_fields[] = 'deleted'; } if ( is_array( $qv['fields'] ) ) { $qv['fields'] = array_map( 'strtolower', $qv['fields'] ); $qv['fields'] = array_intersect( array_unique( $qv['fields'] ), $allowed_fields ); if ( empty( $qv['fields'] ) ) { $qv['fields'] = array( 'id' ); } $this->query_fields = array(); foreach ( $qv['fields'] as $field ) { $field = 'id' === $field ? 'ID' : sanitize_key( $field ); $this->query_fields[] = "$wpdb->users.$field"; } $this->query_fields = implode( ',', $this->query_fields ); } elseif ( 'all_with_meta' === $qv['fields'] || 'all' === $qv['fields'] || ! in_array( $qv['fields'], $allowed_fields, true ) ) { $this->query_fields = "$wpdb->users.ID"; } else { $field = 'id' === strtolower( $qv['fields'] ) ? 'ID' : sanitize_key( $qv['fields'] ); $this->query_fields = "$wpdb->users.$field"; } if ( isset( $qv['count_total'] ) && $qv['count_total'] ) { $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields; } $this->query_from = "FROM $wpdb->users"; $this->query_where = 'WHERE 1=1'; // Parse and sanitize 'include', for use by 'orderby' as well as 'include' below. if ( ! empty( $qv['include'] ) ) { $include = wp_parse_id_list( $qv['include'] ); } else { $include = false; } $blog_id = 0; if ( isset( $qv['blog_id'] ) ) { $blog_id = absint( $qv['blog_id'] ); } if ( $qv['has_published_posts'] && $blog_id ) { if ( true === $qv['has_published_posts'] ) { $post_types = get_post_types( array( 'public' => true ) ); } else { $post_types = (array) $qv['has_published_posts']; } foreach ( $post_types as &$post_type ) { $post_type = $wpdb->prepare( '%s', $post_type ); } $posts_table = $wpdb->get_blog_prefix( $blog_id ) . 'posts'; $this->query_where .= " AND $wpdb->users.ID IN ( SELECT DISTINCT $posts_table.post_author FROM $posts_table WHERE $posts_table.post_status = 'publish' AND $posts_table.post_type IN ( " . implode( ', ', $post_types ) . ' ) )'; } // nicename if ( '' !== $qv['nicename'] ) { $this->query_where .= $wpdb->prepare( ' AND user_nicename = %s', $qv['nicename'] ); } if ( ! empty( $qv['nicename__in'] ) ) { $sanitized_nicename__in = array_map( 'esc_sql', $qv['nicename__in'] ); $nicename__in = implode( "','", $sanitized_nicename__in ); $this->query_where .= " AND user_nicename IN ( '$nicename__in' )"; } if ( ! empty( $qv['nicename__not_in'] ) ) { $sanitized_nicename__not_in = array_map( 'esc_sql', $qv['nicename__not_in'] ); $nicename__not_in = implode( "','", $sanitized_nicename__not_in ); $this->query_where .= " AND user_nicename NOT IN ( '$nicename__not_in' )"; } // login if ( '' !== $qv['login'] ) { $this->query_where .= $wpdb->prepare( ' AND user_login = %s', $qv['login'] ); } if ( ! empty( $qv['login__in'] ) ) { $sanitized_login__in = array_map( 'esc_sql', $qv['login__in'] ); $login__in = implode( "','", $sanitized_login__in ); $this->query_where .= " AND user_login IN ( '$login__in' )"; } if ( ! empty( $qv['login__not_in'] ) ) { $sanitized_login__not_in = array_map( 'esc_sql', $qv['login__not_in'] ); $login__not_in = implode( "','", $sanitized_login__not_in ); $this->query_where .= " AND user_login NOT IN ( '$login__not_in' )"; } // Meta query. $this->meta_query = new WP_Meta_Query(); $this->meta_query->parse_query_vars( $qv ); if ( isset( $qv['who'] ) && 'authors' === $qv['who'] && $blog_id ) { _deprecated_argument( 'WP_User_Query', '5.9.0', sprintf( /* translators: 1: who, 2: capability */ __( '%1$s is deprecated. Use %2$s instead.' ), '<code>who</code>', '<code>capability</code>' ) ); $who_query = array( 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'user_level', 'value' => 0, 'compare' => '!=', ); // Prevent extra meta query. $qv['blog_id'] = 0; $blog_id = 0; if ( empty( $this->meta_query->queries ) ) { $this->meta_query->queries = array( $who_query ); } else { // Append the cap query to the original queries and reparse the query. $this->meta_query->queries = array( 'relation' => 'AND', array( $this->meta_query->queries, $who_query ), ); } $this->meta_query->parse_query_vars( $this->meta_query->queries ); } // Roles. $roles = array(); if ( isset( $qv['role'] ) ) { if ( is_array( $qv['role'] ) ) { $roles = $qv['role']; } elseif ( is_string( $qv['role'] ) && ! empty( $qv['role'] ) ) { $roles = array_map( 'trim', explode( ',', $qv['role'] ) ); } } $role__in = array(); if ( isset( $qv['role__in'] ) ) { $role__in = (array) $qv['role__in']; } $role__not_in = array(); if ( isset( $qv['role__not_in'] ) ) { $role__not_in = (array) $qv['role__not_in']; } // Capabilities. $available_roles = array(); if ( ! empty( $qv['capability'] ) || ! empty( $qv['capability__in'] ) || ! empty( $qv['capability__not_in'] ) ) { $wp_roles->for_site( $blog_id ); $available_roles = $wp_roles->roles; } $capabilities = array(); if ( ! empty( $qv['capability'] ) ) { if ( is_array( $qv['capability'] ) ) { $capabilities = $qv['capability']; } elseif ( is_string( $qv['capability'] ) ) { $capabilities = array_map( 'trim', explode( ',', $qv['capability'] ) ); } } $capability__in = array(); if ( ! empty( $qv['capability__in'] ) ) { $capability__in = (array) $qv['capability__in']; } $capability__not_in = array(); if ( ! empty( $qv['capability__not_in'] ) ) { $capability__not_in = (array) $qv['capability__not_in']; } // Keep track of all capabilities and the roles they're added on. $caps_with_roles = array(); foreach ( $available_roles as $role => $role_data ) { $role_caps = array_keys( array_filter( $role_data['capabilities'] ) ); foreach ( $capabilities as $cap ) { if ( in_array( $cap, $role_caps, true ) ) { $caps_with_roles[ $cap ][] = $role; break; } } foreach ( $capability__in as $cap ) { if ( in_array( $cap, $role_caps, true ) ) { $role__in[] = $role; break; } } foreach ( $capability__not_in as $cap ) { if ( in_array( $cap, $role_caps, true ) ) { $role__not_in[] = $role; break; } } } $role__in = array_merge( $role__in, $capability__in ); $role__not_in = array_merge( $role__not_in, $capability__not_in ); $roles = array_unique( $roles ); $role__in = array_unique( $role__in ); $role__not_in = array_unique( $role__not_in ); // Support querying by capabilities added directly to users. if ( $blog_id && ! empty( $capabilities ) ) { $capabilities_clauses = array( 'relation' => 'AND' ); foreach ( $capabilities as $cap ) { $clause = array( 'relation' => 'OR' ); $clause[] = array( 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities', 'value' => '"' . $cap . '"', 'compare' => 'LIKE', ); if ( ! empty( $caps_with_roles[ $cap ] ) ) { foreach ( $caps_with_roles[ $cap ] as $role ) { $clause[] = array( 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities', 'value' => '"' . $role . '"', 'compare' => 'LIKE', ); } } $capabilities_clauses[] = $clause; } $role_queries[] = $capabilities_clauses; if ( empty( $this->meta_query->queries ) ) { $this->meta_query->queries[] = $capabilities_clauses; } else { // Append the cap query to the original queries and reparse the query. $this->meta_query->queries = array( 'relation' => 'AND', array( $this->meta_query->queries, array( $capabilities_clauses ) ), ); } $this->meta_query->parse_query_vars( $this->meta_query->queries ); } if ( $blog_id && ( ! empty( $roles ) || ! empty( $role__in ) || ! empty( $role__not_in ) || is_multisite() ) ) { $role_queries = array(); $roles_clauses = array( 'relation' => 'AND' ); if ( ! empty( $roles ) ) { foreach ( $roles as $role ) { $roles_clauses[] = array( 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities', 'value' => '"' . $role . '"', 'compare' => 'LIKE', ); } $role_queries[] = $roles_clauses; } $role__in_clauses = array( 'relation' => 'OR' ); if ( ! empty( $role__in ) ) { foreach ( $role__in as $role ) { $role__in_clauses[] = array( 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities', 'value' => '"' . $role . '"', 'compare' => 'LIKE', ); } $role_queries[] = $role__in_clauses; } $role__not_in_clauses = array( 'relation' => 'AND' ); if ( ! empty( $role__not_in ) ) { foreach ( $role__not_in as $role ) { $role__not_in_clauses[] = array( 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities', 'value' => '"' . $role . '"', 'compare' => 'NOT LIKE', ); } $role_queries[] = $role__not_in_clauses; } // If there are no specific roles named, make sure the user is a member of the site. if ( empty( $role_queries ) ) { $role_queries[] = array( 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities', 'compare' => 'EXISTS', ); } // Specify that role queries should be joined with AND. $role_queries['relation'] = 'AND'; if ( empty( $this->meta_query->queries ) ) { $this->meta_query->queries = $role_queries; } else { // Append the cap query to the original queries and reparse the query. $this->meta_query->queries = array( 'relation' => 'AND', array( $this->meta_query->queries, $role_queries ), ); } $this->meta_query->parse_query_vars( $this->meta_query->queries ); } if ( ! empty( $this->meta_query->queries ) ) { $clauses = $this->meta_query->get_sql( 'user', $wpdb->users, 'ID', $this ); $this->query_from .= $clauses['join']; $this->query_where .= $clauses['where']; if ( $this->meta_query->has_or_relation() ) { $this->query_fields = 'DISTINCT ' . $this->query_fields; } } // Sorting. $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : ''; $order = $this->parse_order( $qv['order'] ); if ( empty( $qv['orderby'] ) ) { // Default order is by 'user_login'. $ordersby = array( 'user_login' => $order ); } elseif ( is_array( $qv['orderby'] ) ) { $ordersby = $qv['orderby']; } else { // 'orderby' values may be a comma- or space-separated list. $ordersby = preg_split( '/[,\s]+/', $qv['orderby'] ); } $orderby_array = array(); foreach ( $ordersby as $_key => $_value ) { if ( ! $_value ) { continue; } if ( is_int( $_key ) ) { // Integer key means this is a flat array of 'orderby' fields. $_orderby = $_value; $_order = $order; } else { // Non-integer key means this the key is the field and the value is ASC/DESC. $_orderby = $_key; $_order = $_value; } $parsed = $this->parse_orderby( $_orderby ); if ( ! $parsed ) { continue; } if ( 'nicename__in' === $_orderby || 'login__in' === $_orderby ) { $orderby_array[] = $parsed; } else { $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order ); } } // If no valid clauses were found, order by user_login. if ( empty( $orderby_array ) ) { $orderby_array[] = "user_login $order"; } $this->query_orderby = 'ORDER BY ' . implode( ', ', $orderby_array ); // Limit. if ( isset( $qv['number'] ) && $qv['number'] > 0 ) { if ( $qv['offset'] ) { $this->query_limit = $wpdb->prepare( 'LIMIT %d, %d', $qv['offset'], $qv['number'] ); } else { $this->query_limit = $wpdb->prepare( 'LIMIT %d, %d', $qv['number'] * ( $qv['paged'] - 1 ), $qv['number'] ); } } $search = ''; if ( isset( $qv['search'] ) ) { $search = trim( $qv['search'] ); } if ( $search ) { $leading_wild = ( ltrim( $search, '*' ) != $search ); $trailing_wild = ( rtrim( $search, '*' ) != $search ); if ( $leading_wild && $trailing_wild ) { $wild = 'both'; } elseif ( $leading_wild ) { $wild = 'leading'; } elseif ( $trailing_wild ) { $wild = 'trailing'; } else { $wild = false; } if ( $wild ) { $search = trim( $search, '*' ); } $search_columns = array(); if ( $qv['search_columns'] ) { $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename', 'display_name' ) ); } if ( ! $search_columns ) { if ( false !== strpos( $search, '@' ) ) { $search_columns = array( 'user_email' ); } elseif ( is_numeric( $search ) ) { $search_columns = array( 'user_login', 'ID' ); } elseif ( preg_match( '|^https?://|', $search ) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) ) { $search_columns = array( 'user_url' ); } else { $search_columns = array( 'user_login', 'user_url', 'user_email', 'user_nicename', 'display_name' ); } } /** * Filters the columns to search in a WP_User_Query search. * * The default columns depend on the search term, and include 'ID', 'user_login', * 'user_email', 'user_url', 'user_nicename', and 'display_name'. * * @since 3.6.0 * * @param string[] $search_columns Array of column names to be searched. * @param string $search Text being searched. * @param WP_User_Query $query The current WP_User_Query instance. */ $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this ); $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild ); } if ( ! empty( $include ) ) { // Sanitized earlier. $ids = implode( ',', $include ); $this->query_where .= " AND $wpdb->users.ID IN ($ids)"; } elseif ( ! empty( $qv['exclude'] ) ) { $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) ); $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)"; } // Date queries are allowed for the user_registered field. if ( ! empty( $qv['date_query'] ) && is_array( $qv['date_query'] ) ) { $date_query = new WP_Date_Query( $qv['date_query'], 'user_registered' ); $this->query_where .= $date_query->get_sql(); } /** * Fires after the WP_User_Query has been parsed, and before * the query is executed. * * The passed WP_User_Query object contains SQL parts formed * from parsing the given query. * * @since 3.1.0 * * @param WP_User_Query $query Current instance of WP_User_Query (passed by reference). */ do_action_ref_array( 'pre_user_query', array( &$this ) ); } /** * Executes the query, with the current variables. * * @since 3.1.0 * * @global wpdb $wpdb WordPress database abstraction object. */ public function query() { global $wpdb; $qv =& $this->query_vars; /** * Filters the users array before the query takes place. * * Return a non-null value to bypass WordPress' default user queries. * * Filtering functions that require pagination information are encouraged to set * the `total_users` property of the WP_User_Query object, passed to the filter * by reference. If WP_User_Query does not perform a database query, it will not * have enough information to generate these values itself. * * @since 5.1.0 * * @param array|null $results Return an array of user data to short-circuit WP's user query * or null to allow WP to run its normal queries. * @param WP_User_Query $query The WP_User_Query instance (passed by reference). */ $this->results = apply_filters_ref_array( 'users_pre_query', array( null, &$this ) ); if ( null === $this->results ) { $this->request = " SELECT {$this->query_fields} {$this->query_from} {$this->query_where} {$this->query_orderby} {$this->query_limit} "; if ( is_array( $qv['fields'] ) ) { $this->results = $wpdb->get_results( $this->request ); } else { $this->results = $wpdb->get_col( $this->request ); } if ( isset( $qv['count_total'] ) && $qv['count_total'] ) { /** * Filters SELECT FOUND_ROWS() query for the current WP_User_Query instance. * * @since 3.2.0 * @since 5.1.0 Added the `$this` parameter. * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query. * @param WP_User_Query $query The current WP_User_Query instance. */ $found_users_query = apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()', $this ); $this->total_users = (int) $wpdb->get_var( $found_users_query ); } } if ( ! $this->results ) { return; } if ( is_array( $qv['fields'] ) && isset( $this->results[0]->ID ) ) { foreach ( $this->results as $result ) { $result->id = $result->ID; } } elseif ( 'all_with_meta' === $qv['fields'] || 'all' === $qv['fields'] ) { cache_users( $this->results ); $r = array(); foreach ( $this->results as $userid ) { if ( 'all_with_meta' === $qv['fields'] ) { $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] ); } else { $r[] = new WP_User( $userid, '', $qv['blog_id'] ); } } $this->results = $r; } } /** * Retrieves query variable. * * @since 3.5.0 * * @param string $query_var Query variable key. * @return mixed */ public function get( $query_var ) { if ( isset( $this->query_vars[ $query_var ] ) ) { return $this->query_vars[ $query_var ]; } return null; } /** * Sets query variable. * * @since 3.5.0 * * @param string $query_var Query variable key. * @param mixed $value Query variable value. */ public function set( $query_var, $value ) { $this->query_vars[ $query_var ] = $value; } /** * Used internally to generate an SQL string for searching across multiple columns. * * @since 3.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $search Search string. * @param string[] $columns Array of columns to search. * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for single site. * Single site allows leading and trailing wildcards, Network Admin only trailing. * @return string */ protected function get_search_sql( $search, $columns, $wild = false ) { global $wpdb; $searches = array(); $leading_wild = ( 'leading' === $wild || 'both' === $wild ) ? '%' : ''; $trailing_wild = ( 'trailing' === $wild || 'both' === $wild ) ? '%' : ''; $like = $leading_wild . $wpdb->esc_like( $search ) . $trailing_wild; foreach ( $columns as $column ) { if ( 'ID' === $column ) { $searches[] = $wpdb->prepare( "$column = %s", $search ); } else { $searches[] = $wpdb->prepare( "$column LIKE %s", $like ); } } return ' AND (' . implode( ' OR ', $searches ) . ')'; } /** * Returns the list of users. * * @since 3.1.0 * * @return array Array of results. */ public function get_results() { return $this->results; } /** * Returns the total number of users for the current query. * * @since 3.1.0 * * @return int Number of total users. */ public function get_total() { return $this->total_users; } /** * Parses and sanitizes 'orderby' keys passed to the user query. * * @since 4.2.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $orderby Alias for the field to order by. * @return string Value to used in the ORDER clause, if `$orderby` is valid. */ protected function parse_orderby( $orderby ) { global $wpdb; $meta_query_clauses = $this->meta_query->get_clauses(); $_orderby = ''; if ( in_array( $orderby, array( 'login', 'nicename', 'email', 'url', 'registered' ), true ) ) { $_orderby = 'user_' . $orderby; } elseif ( in_array( $orderby, array( 'user_login', 'user_nicename', 'user_email', 'user_url', 'user_registered' ), true ) ) { $_orderby = $orderby; } elseif ( 'name' === $orderby || 'display_name' === $orderby ) { $_orderby = 'display_name'; } elseif ( 'post_count' === $orderby ) { // @todo Avoid the JOIN. $where = get_posts_by_author_sql( 'post' ); $this->query_from .= " LEFT OUTER JOIN ( SELECT post_author, COUNT(*) as post_count FROM $wpdb->posts $where GROUP BY post_author ) p ON ({$wpdb->users}.ID = p.post_author) "; $_orderby = 'post_count'; } elseif ( 'ID' === $orderby || 'id' === $orderby ) { $_orderby = 'ID'; } elseif ( 'meta_value' === $orderby || $this->get( 'meta_key' ) == $orderby ) { $_orderby = "$wpdb->usermeta.meta_value"; } elseif ( 'meta_value_num' === $orderby ) { $_orderby = "$wpdb->usermeta.meta_value+0"; } elseif ( 'include' === $orderby && ! empty( $this->query_vars['include'] ) ) { $include = wp_parse_id_list( $this->query_vars['include'] ); $include_sql = implode( ',', $include ); $_orderby = "FIELD( $wpdb->users.ID, $include_sql )"; } elseif ( 'nicename__in' === $orderby ) { $sanitized_nicename__in = array_map( 'esc_sql', $this->query_vars['nicename__in'] ); $nicename__in = implode( "','", $sanitized_nicename__in ); $_orderby = "FIELD( user_nicename, '$nicename__in' )"; } elseif ( 'login__in' === $orderby ) { $sanitized_login__in = array_map( 'esc_sql', $this->query_vars['login__in'] ); $login__in = implode( "','", $sanitized_login__in ); $_orderby = "FIELD( user_login, '$login__in' )"; } elseif ( isset( $meta_query_clauses[ $orderby ] ) ) { $meta_clause = $meta_query_clauses[ $orderby ]; $_orderby = sprintf( 'CAST(%s.meta_value AS %s)', esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) ); } return $_orderby; } /** * Parses an 'order' query variable and casts it to ASC or DESC as necessary. * * @since 4.2.0 * * @param string $order The 'order' query variable. * @return string The sanitized 'order' query variable. */ protected function parse_order( $order ) { if ( ! is_string( $order ) || empty( $order ) ) { return 'DESC'; } if ( 'ASC' === strtoupper( $order ) ) { return 'ASC'; } else { return 'DESC'; } } /** * Makes private properties readable for backward compatibility. * * @since 4.0.0 * * @param string $name Property to get. * @return mixed Property. */ public function __get( $name ) { if ( in_array( $name, $this->compat_fields, true ) ) { return $this->$name; } } /** * Makes private properties settable for backward compatibility. * * @since 4.0.0 * * @param string $name Property to check if set. * @param mixed $value Property value. * @return mixed Newly-set property. */ public function __set( $name, $value ) { if ( in_array( $name, $this->compat_fields, true ) ) { return $this->$name = $value; } } /** * Makes private properties checkable for backward compatibility. * * @since 4.0.0 * * @param string $name Property to check if set. * @return bool Whether the property is set. */ public function __isset( $name ) { if ( in_array( $name, $this->compat_fields, true ) ) { return isset( $this->$name ); } } /** * Makes private properties un-settable for backward compatibility. * * @since 4.0.0 * * @param string $name Property to unset. */ public function __unset( $name ) { if ( in_array( $name, $this->compat_fields, true ) ) { unset( $this->$name ); } } /** * Makes private/protected methods readable for backward compatibility. * * @since 4.0.0 * * @param string $name Method to call. * @param array $arguments Arguments to pass when calling. * @return mixed Return value of the callback, false otherwise. */ public function __call( $name, $arguments ) { if ( 'get_search_sql' === $name ) { return $this->get_search_sql( ...$arguments ); } return false; } } ``` | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
programming_docs
wordpress class AtomEntry {} class AtomEntry {} ================== Structure that store Atom Entry Properties File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/) ``` class AtomEntry { /** * Stores Links * @var array * @access public */ var $links = array(); /** * Stores Categories * @var array * @access public */ var $categories = array(); } ``` wordpress class Requests_Exception_HTTP_400 {} class Requests\_Exception\_HTTP\_400 {} ======================================= Exception for 400 Bad Request responses File: `wp-includes/Requests/Exception/HTTP/400.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/400.php/) ``` class Requests_Exception_HTTP_400 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 400; /** * Reason phrase * * @var string */ protected $reason = 'Bad Request'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_Customize_Nav_Menus {} class WP\_Customize\_Nav\_Menus {} ================================== Customize Nav Menus class. Implements menu management in the Customizer. * [WP\_Customize\_Manager](wp_customize_manager) * [\_\_construct](wp_customize_nav_menus/__construct) β€” Constructor. * [ajax\_insert\_auto\_draft\_post](wp_customize_nav_menus/ajax_insert_auto_draft_post) β€” Ajax handler for adding a new auto-draft post. * [ajax\_load\_available\_items](wp_customize_nav_menus/ajax_load_available_items) β€” Ajax handler for loading available menu items. * [ajax\_search\_available\_items](wp_customize_nav_menus/ajax_search_available_items) β€” Ajax handler for searching available menu items. * [available\_item\_types](wp_customize_nav_menus/available_item_types) β€” Returns an array of all the available item types. * [available\_items\_template](wp_customize_nav_menus/available_items_template) β€” Prints the HTML template used to render the add-menu-item frame. * [customize\_dynamic\_partial\_args](wp_customize_nav_menus/customize_dynamic_partial_args) β€” Filters arguments for dynamic nav\_menu selective refresh partials. * [customize\_preview\_enqueue\_deps](wp_customize_nav_menus/customize_preview_enqueue_deps) β€” Enqueues scripts for the Customizer preview. * [customize\_preview\_init](wp_customize_nav_menus/customize_preview_init) β€” Adds hooks for the Customizer preview. * [customize\_register](wp_customize_nav_menus/customize_register) β€” Adds the customizer settings and controls. * [enqueue\_scripts](wp_customize_nav_menus/enqueue_scripts) β€” Enqueues scripts and styles for Customizer pane. * [export\_partial\_rendered\_nav\_menu\_instances](wp_customize_nav_menus/export_partial_rendered_nav_menu_instances) β€” Exports any wp\_nav\_menu() calls during the rendering of any partials. * [export\_preview\_data](wp_customize_nav_menus/export_preview_data) β€” Exports data from PHP to JS. * [filter\_dynamic\_setting\_args](wp_customize_nav_menus/filter_dynamic_setting_args) β€” Filters a dynamic setting's constructor args. * [filter\_dynamic\_setting\_class](wp_customize_nav_menus/filter_dynamic_setting_class) β€” Allows non-statically created settings to be constructed with custom WP\_Customize\_Setting subclass. * [filter\_nonces](wp_customize_nav_menus/filter_nonces) β€” Adds a nonce for customizing menus. * [filter\_wp\_nav\_menu](wp_customize_nav_menus/filter_wp_nav_menu) β€” Prepares wp\_nav\_menu() calls for partial refresh. * [filter\_wp\_nav\_menu\_args](wp_customize_nav_menus/filter_wp_nav_menu_args) β€” Keeps track of the arguments that are being passed to wp\_nav\_menu(). * [hash\_nav\_menu\_args](wp_customize_nav_menus/hash_nav_menu_args) β€” Hashes (hmac) the nav menu arguments to ensure they are not tampered with when submitted in the Ajax request. * [insert\_auto\_draft\_post](wp_customize_nav_menus/insert_auto_draft_post) β€” Adds a new `auto-draft` post. * [intval\_base10](wp_customize_nav_menus/intval_base10) β€” Gets the base10 intval. * [load\_available\_items\_query](wp_customize_nav_menus/load_available_items_query) β€” Performs the post\_type and taxonomy queries for loading available menu items. * [make\_auto\_draft\_status\_previewable](wp_customize_nav_menus/make_auto_draft_status_previewable) β€” Makes the auto-draft status protected so that it can be queried. * [print\_custom\_links\_available\_menu\_item](wp_customize_nav_menus/print_custom_links_available_menu_item) β€” Prints the markup for available menu item custom links. * [print\_post\_type\_container](wp_customize_nav_menus/print_post_type_container) β€” Prints the markup for new menu items. * [print\_templates](wp_customize_nav_menus/print_templates) β€” Prints the JavaScript templates used to render Menu Customizer components. * [render\_nav\_menu\_partial](wp_customize_nav_menus/render_nav_menu_partial) β€” Renders a specific menu via wp\_nav\_menu() using the supplied arguments. * [sanitize\_nav\_menus\_created\_posts](wp_customize_nav_menus/sanitize_nav_menus_created_posts) β€” Sanitizes post IDs for posts created for nav menu items to be published. * [save\_nav\_menus\_created\_posts](wp_customize_nav_menus/save_nav_menus_created_posts) β€” Publishes the auto-draft posts that were created for nav menu items. * [search\_available\_items\_query](wp_customize_nav_menus/search_available_items_query) β€” Performs post queries for available-item searching. File: `wp-includes/class-wp-customize-nav-menus.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-nav-menus.php/) ``` final class WP_Customize_Nav_Menus { /** * WP_Customize_Manager instance. * * @since 4.3.0 * @var WP_Customize_Manager */ public $manager; /** * Original nav menu locations before the theme was switched. * * @since 4.9.0 * @var array */ protected $original_nav_menu_locations; /** * Constructor. * * @since 4.3.0 * * @param WP_Customize_Manager $manager Customizer bootstrap instance. */ public function __construct( $manager ) { $this->manager = $manager; $this->original_nav_menu_locations = get_nav_menu_locations(); // See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L469-L499 add_action( 'customize_register', array( $this, 'customize_register' ), 11 ); add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_dynamic_setting_args' ), 10, 2 ); add_filter( 'customize_dynamic_setting_class', array( $this, 'filter_dynamic_setting_class' ), 10, 3 ); add_action( 'customize_save_nav_menus_created_posts', array( $this, 'save_nav_menus_created_posts' ) ); // Skip remaining hooks when the user can't manage nav menus anyway. if ( ! current_user_can( 'edit_theme_options' ) ) { return; } add_filter( 'customize_refresh_nonces', array( $this, 'filter_nonces' ) ); add_action( 'wp_ajax_load-available-menu-items-customizer', array( $this, 'ajax_load_available_items' ) ); add_action( 'wp_ajax_search-available-menu-items-customizer', array( $this, 'ajax_search_available_items' ) ); add_action( 'wp_ajax_customize-nav-menus-insert-auto-draft', array( $this, 'ajax_insert_auto_draft_post' ) ); add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_templates' ) ); add_action( 'customize_controls_print_footer_scripts', array( $this, 'available_items_template' ) ); add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) ); add_action( 'customize_preview_init', array( $this, 'make_auto_draft_status_previewable' ) ); // Selective Refresh partials. add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 ); } /** * Adds a nonce for customizing menus. * * @since 4.5.0 * * @param string[] $nonces Array of nonces. * @return string[] Modified array of nonces. */ public function filter_nonces( $nonces ) { $nonces['customize-menus'] = wp_create_nonce( 'customize-menus' ); return $nonces; } /** * Ajax handler for loading available menu items. * * @since 4.3.0 */ public function ajax_load_available_items() { check_ajax_referer( 'customize-menus', 'customize-menus-nonce' ); if ( ! current_user_can( 'edit_theme_options' ) ) { wp_die( -1 ); } $all_items = array(); $item_types = array(); if ( isset( $_POST['item_types'] ) && is_array( $_POST['item_types'] ) ) { $item_types = wp_unslash( $_POST['item_types'] ); } elseif ( isset( $_POST['type'] ) && isset( $_POST['object'] ) ) { // Back compat. $item_types[] = array( 'type' => wp_unslash( $_POST['type'] ), 'object' => wp_unslash( $_POST['object'] ), 'page' => empty( $_POST['page'] ) ? 0 : absint( $_POST['page'] ), ); } else { wp_send_json_error( 'nav_menus_missing_type_or_object_parameter' ); } foreach ( $item_types as $item_type ) { if ( empty( $item_type['type'] ) || empty( $item_type['object'] ) ) { wp_send_json_error( 'nav_menus_missing_type_or_object_parameter' ); } $type = sanitize_key( $item_type['type'] ); $object = sanitize_key( $item_type['object'] ); $page = empty( $item_type['page'] ) ? 0 : absint( $item_type['page'] ); $items = $this->load_available_items_query( $type, $object, $page ); if ( is_wp_error( $items ) ) { wp_send_json_error( $items->get_error_code() ); } $all_items[ $item_type['type'] . ':' . $item_type['object'] ] = $items; } wp_send_json_success( array( 'items' => $all_items ) ); } /** * Performs the post_type and taxonomy queries for loading available menu items. * * @since 4.3.0 * * @param string $object_type Optional. Accepts any custom object type and has built-in support for * 'post_type' and 'taxonomy'. Default is 'post_type'. * @param string $object_name Optional. Accepts any registered taxonomy or post type name. Default is 'page'. * @param int $page Optional. The page number used to generate the query offset. Default is '0'. * @return array|WP_Error An array of menu items on success, a WP_Error object on failure. */ public function load_available_items_query( $object_type = 'post_type', $object_name = 'page', $page = 0 ) { $items = array(); if ( 'post_type' === $object_type ) { $post_type = get_post_type_object( $object_name ); if ( ! $post_type ) { return new WP_Error( 'nav_menus_invalid_post_type' ); } /* * If we're dealing with pages, let's prioritize the Front Page, * Posts Page and Privacy Policy Page at the top of the list. */ $important_pages = array(); $suppress_page_ids = array(); if ( 0 === $page && 'page' === $object_name ) { // Insert Front Page or custom "Home" link. $front_page = 'page' === get_option( 'show_on_front' ) ? (int) get_option( 'page_on_front' ) : 0; if ( ! empty( $front_page ) ) { $front_page_obj = get_post( $front_page ); $important_pages[] = $front_page_obj; $suppress_page_ids[] = $front_page_obj->ID; } else { // Add "Home" link. Treat as a page, but switch to custom on add. $items[] = array( 'id' => 'home', 'title' => _x( 'Home', 'nav menu home label' ), 'type' => 'custom', 'type_label' => __( 'Custom Link' ), 'object' => '', 'url' => home_url(), ); } // Insert Posts Page. $posts_page = 'page' === get_option( 'show_on_front' ) ? (int) get_option( 'page_for_posts' ) : 0; if ( ! empty( $posts_page ) ) { $posts_page_obj = get_post( $posts_page ); $important_pages[] = $posts_page_obj; $suppress_page_ids[] = $posts_page_obj->ID; } // Insert Privacy Policy Page. $privacy_policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' ); if ( ! empty( $privacy_policy_page_id ) ) { $privacy_policy_page = get_post( $privacy_policy_page_id ); if ( $privacy_policy_page instanceof WP_Post && 'publish' === $privacy_policy_page->post_status ) { $important_pages[] = $privacy_policy_page; $suppress_page_ids[] = $privacy_policy_page->ID; } } } elseif ( 'post' !== $object_name && 0 === $page && $post_type->has_archive ) { // Add a post type archive link. $items[] = array( 'id' => $object_name . '-archive', 'title' => $post_type->labels->archives, 'type' => 'post_type_archive', 'type_label' => __( 'Post Type Archive' ), 'object' => $object_name, 'url' => get_post_type_archive_link( $object_name ), ); } // Prepend posts with nav_menus_created_posts on first page. $posts = array(); if ( 0 === $page && $this->manager->get_setting( 'nav_menus_created_posts' ) ) { foreach ( $this->manager->get_setting( 'nav_menus_created_posts' )->value() as $post_id ) { $auto_draft_post = get_post( $post_id ); if ( $post_type->name === $auto_draft_post->post_type ) { $posts[] = $auto_draft_post; } } } $args = array( 'numberposts' => 10, 'offset' => 10 * $page, 'orderby' => 'date', 'order' => 'DESC', 'post_type' => $object_name, ); // Add suppression array to arguments for get_posts. if ( ! empty( $suppress_page_ids ) ) { $args['post__not_in'] = $suppress_page_ids; } $posts = array_merge( $posts, $important_pages, get_posts( $args ) ); foreach ( $posts as $post ) { $post_title = $post->post_title; if ( '' === $post_title ) { /* translators: %d: ID of a post. */ $post_title = sprintf( __( '#%d (no title)' ), $post->ID ); } $post_type_label = get_post_type_object( $post->post_type )->labels->singular_name; $post_states = get_post_states( $post ); if ( ! empty( $post_states ) ) { $post_type_label = implode( ',', $post_states ); } $items[] = array( 'id' => "post-{$post->ID}", 'title' => html_entity_decode( $post_title, ENT_QUOTES, get_bloginfo( 'charset' ) ), 'type' => 'post_type', 'type_label' => $post_type_label, 'object' => $post->post_type, 'object_id' => (int) $post->ID, 'url' => get_permalink( (int) $post->ID ), ); } } elseif ( 'taxonomy' === $object_type ) { $terms = get_terms( array( 'taxonomy' => $object_name, 'child_of' => 0, 'exclude' => '', 'hide_empty' => false, 'hierarchical' => 1, 'include' => '', 'number' => 10, 'offset' => 10 * $page, 'order' => 'DESC', 'orderby' => 'count', 'pad_counts' => false, ) ); if ( is_wp_error( $terms ) ) { return $terms; } foreach ( $terms as $term ) { $items[] = array( 'id' => "term-{$term->term_id}", 'title' => html_entity_decode( $term->name, ENT_QUOTES, get_bloginfo( 'charset' ) ), 'type' => 'taxonomy', 'type_label' => get_taxonomy( $term->taxonomy )->labels->singular_name, 'object' => $term->taxonomy, 'object_id' => (int) $term->term_id, 'url' => get_term_link( (int) $term->term_id, $term->taxonomy ), ); } } /** * Filters the available menu items. * * @since 4.3.0 * * @param array $items The array of menu items. * @param string $object_type The object type. * @param string $object_name The object name. * @param int $page The current page number. */ $items = apply_filters( 'customize_nav_menu_available_items', $items, $object_type, $object_name, $page ); return $items; } /** * Ajax handler for searching available menu items. * * @since 4.3.0 */ public function ajax_search_available_items() { check_ajax_referer( 'customize-menus', 'customize-menus-nonce' ); if ( ! current_user_can( 'edit_theme_options' ) ) { wp_die( -1 ); } if ( empty( $_POST['search'] ) ) { wp_send_json_error( 'nav_menus_missing_search_parameter' ); } $p = isset( $_POST['page'] ) ? absint( $_POST['page'] ) : 0; if ( $p < 1 ) { $p = 1; } $s = sanitize_text_field( wp_unslash( $_POST['search'] ) ); $items = $this->search_available_items_query( array( 'pagenum' => $p, 's' => $s, ) ); if ( empty( $items ) ) { wp_send_json_error( array( 'message' => __( 'No results found.' ) ) ); } else { wp_send_json_success( array( 'items' => $items ) ); } } /** * Performs post queries for available-item searching. * * Based on WP_Editor::wp_link_query(). * * @since 4.3.0 * * @param array $args Optional. Accepts 'pagenum' and 's' (search) arguments. * @return array Menu items. */ public function search_available_items_query( $args = array() ) { $items = array(); $post_type_objects = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' ); $query = array( 'post_type' => array_keys( $post_type_objects ), '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; $query['offset'] = $args['pagenum'] > 1 ? $query['posts_per_page'] * ( $args['pagenum'] - 1 ) : 0; if ( isset( $args['s'] ) ) { $query['s'] = $args['s']; } $posts = array(); // Prepend list of posts with nav_menus_created_posts search results on first page. $nav_menus_created_posts_setting = $this->manager->get_setting( 'nav_menus_created_posts' ); if ( 1 === $args['pagenum'] && $nav_menus_created_posts_setting && count( $nav_menus_created_posts_setting->value() ) > 0 ) { $stub_post_query = new WP_Query( array_merge( $query, array( 'post_status' => 'auto-draft', 'post__in' => $nav_menus_created_posts_setting->value(), 'posts_per_page' => -1, ) ) ); $posts = array_merge( $posts, $stub_post_query->posts ); } // Query posts. $get_posts = new WP_Query( $query ); $posts = array_merge( $posts, $get_posts->posts ); // Create items for posts. foreach ( $posts as $post ) { $post_title = $post->post_title; if ( '' === $post_title ) { /* translators: %d: ID of a post. */ $post_title = sprintf( __( '#%d (no title)' ), $post->ID ); } $post_type_label = $post_type_objects[ $post->post_type ]->labels->singular_name; $post_states = get_post_states( $post ); if ( ! empty( $post_states ) ) { $post_type_label = implode( ',', $post_states ); } $items[] = array( 'id' => 'post-' . $post->ID, 'title' => html_entity_decode( $post_title, ENT_QUOTES, get_bloginfo( 'charset' ) ), 'type' => 'post_type', 'type_label' => $post_type_label, 'object' => $post->post_type, 'object_id' => (int) $post->ID, 'url' => get_permalink( (int) $post->ID ), ); } // Query taxonomy terms. $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'names' ); $terms = get_terms( array( 'taxonomies' => $taxonomies, 'name__like' => $args['s'], 'number' => 20, 'hide_empty' => false, 'offset' => 20 * ( $args['pagenum'] - 1 ), ) ); // Check if any taxonomies were found. if ( ! empty( $terms ) ) { foreach ( $terms as $term ) { $items[] = array( 'id' => 'term-' . $term->term_id, 'title' => html_entity_decode( $term->name, ENT_QUOTES, get_bloginfo( 'charset' ) ), 'type' => 'taxonomy', 'type_label' => get_taxonomy( $term->taxonomy )->labels->singular_name, 'object' => $term->taxonomy, 'object_id' => (int) $term->term_id, 'url' => get_term_link( (int) $term->term_id, $term->taxonomy ), ); } } // Add "Home" link if search term matches. Treat as a page, but switch to custom on add. if ( isset( $args['s'] ) ) { // Only insert custom "Home" link if there's no Front Page $front_page = 'page' === get_option( 'show_on_front' ) ? (int) get_option( 'page_on_front' ) : 0; if ( empty( $front_page ) ) { $title = _x( 'Home', 'nav menu home label' ); $matches = function_exists( 'mb_stripos' ) ? false !== mb_stripos( $title, $args['s'] ) : false !== stripos( $title, $args['s'] ); if ( $matches ) { $items[] = array( 'id' => 'home', 'title' => $title, 'type' => 'custom', 'type_label' => __( 'Custom Link' ), 'object' => '', 'url' => home_url(), ); } } } /** * Filters the available menu items during a search request. * * @since 4.5.0 * * @param array $items The array of menu items. * @param array $args Includes 'pagenum' and 's' (search) arguments. */ $items = apply_filters( 'customize_nav_menu_searched_items', $items, $args ); return $items; } /** * Enqueues scripts and styles for Customizer pane. * * @since 4.3.0 */ public function enqueue_scripts() { wp_enqueue_style( 'customize-nav-menus' ); wp_enqueue_script( 'customize-nav-menus' ); $temp_nav_menu_setting = new WP_Customize_Nav_Menu_Setting( $this->manager, 'nav_menu[-1]' ); $temp_nav_menu_item_setting = new WP_Customize_Nav_Menu_Item_Setting( $this->manager, 'nav_menu_item[-1]' ); $num_locations = count( get_registered_nav_menus() ); if ( 1 === $num_locations ) { $locations_description = __( 'Your theme can display menus in one location.' ); } else { /* translators: %s: Number of menu locations. */ $locations_description = sprintf( _n( 'Your theme can display menus in %s location.', 'Your theme can display menus in %s locations.', $num_locations ), number_format_i18n( $num_locations ) ); } // Pass data to JS. $settings = array( 'allMenus' => wp_get_nav_menus(), 'itemTypes' => $this->available_item_types(), 'l10n' => array( 'untitled' => _x( '(no label)', 'missing menu item navigation label' ), 'unnamed' => _x( '(unnamed)', 'Missing menu name.' ), 'custom_label' => __( 'Custom Link' ), 'page_label' => get_post_type_object( 'page' )->labels->singular_name, /* translators: %s: Menu location. */ 'menuLocation' => _x( '(Currently set to: %s)', 'menu' ), 'locationsTitle' => 1 === $num_locations ? __( 'Menu Location' ) : __( 'Menu Locations' ), 'locationsDescription' => $locations_description, 'menuNameLabel' => __( 'Menu Name' ), 'newMenuNameDescription' => __( 'If your theme has multiple menus, giving them clear names will help you manage them.' ), 'itemAdded' => __( 'Menu item added' ), 'itemDeleted' => __( 'Menu item deleted' ), 'menuAdded' => __( 'Menu created' ), 'menuDeleted' => __( 'Menu deleted' ), 'movedUp' => __( 'Menu item moved up' ), 'movedDown' => __( 'Menu item moved down' ), 'movedLeft' => __( 'Menu item moved out of submenu' ), 'movedRight' => __( 'Menu item is now a sub-item' ), /* translators: &#9656; is the unicode right-pointing triangle. %s: Section title in the Customizer. */ 'customizingMenus' => sprintf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) ), /* translators: %s: Title of an invalid menu item. */ 'invalidTitleTpl' => __( '%s (Invalid)' ), /* translators: %s: Title of a menu item in draft status. */ 'pendingTitleTpl' => __( '%s (Pending)' ), /* translators: %d: Number of menu items found. */ 'itemsFound' => __( 'Number of items found: %d' ), /* translators: %d: Number of additional menu items found. */ 'itemsFoundMore' => __( 'Additional items found: %d' ), 'itemsLoadingMore' => __( 'Loading more results... please wait.' ), 'reorderModeOn' => __( 'Reorder mode enabled' ), 'reorderModeOff' => __( 'Reorder mode closed' ), 'reorderLabelOn' => esc_attr__( 'Reorder menu items' ), 'reorderLabelOff' => esc_attr__( 'Close reorder mode' ), ), 'settingTransport' => 'postMessage', 'phpIntMax' => PHP_INT_MAX, 'defaultSettingValues' => array( 'nav_menu' => $temp_nav_menu_setting->default, 'nav_menu_item' => $temp_nav_menu_item_setting->default, ), 'locationSlugMappedToName' => get_registered_nav_menus(), ); $data = sprintf( 'var _wpCustomizeNavMenusSettings = %s;', wp_json_encode( $settings ) ); wp_scripts()->add_data( 'customize-nav-menus', 'data', $data ); // This is copied from nav-menus.php, and it has an unfortunate object name of `menus`. $nav_menus_l10n = array( 'oneThemeLocationNoMenus' => null, 'moveUp' => __( 'Move up one' ), 'moveDown' => __( 'Move down one' ), 'moveToTop' => __( 'Move to the top' ), /* translators: %s: Previous item name. */ 'moveUnder' => __( 'Move under %s' ), /* translators: %s: Previous item name. */ 'moveOutFrom' => __( 'Move out from under %s' ), /* translators: %s: Previous item name. */ 'under' => __( 'Under %s' ), /* translators: %s: Previous item name. */ 'outFrom' => __( 'Out from under %s' ), /* translators: 1: Item name, 2: Item position, 3: Total number of items. */ 'menuFocus' => __( '%1$s. Menu item %2$d of %3$d.' ), /* translators: 1: Item name, 2: Item position, 3: Parent item name. */ 'subMenuFocus' => __( '%1$s. Sub item number %2$d under %3$s.' ), ); wp_localize_script( 'nav-menu', 'menus', $nav_menus_l10n ); } /** * Filters a dynamic setting's constructor args. * * For a dynamic setting to be registered, this filter must be employed * to override the default false value with an array of args to pass to * the WP_Customize_Setting constructor. * * @since 4.3.0 * * @param false|array $setting_args The arguments to the WP_Customize_Setting constructor. * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`. * @return array|false */ public function filter_dynamic_setting_args( $setting_args, $setting_id ) { if ( preg_match( WP_Customize_Nav_Menu_Setting::ID_PATTERN, $setting_id ) ) { $setting_args = array( 'type' => WP_Customize_Nav_Menu_Setting::TYPE, 'transport' => 'postMessage', ); } elseif ( preg_match( WP_Customize_Nav_Menu_Item_Setting::ID_PATTERN, $setting_id ) ) { $setting_args = array( 'type' => WP_Customize_Nav_Menu_Item_Setting::TYPE, 'transport' => 'postMessage', ); } return $setting_args; } /** * Allows non-statically created settings to be constructed with custom WP_Customize_Setting subclass. * * @since 4.3.0 * * @param string $setting_class WP_Customize_Setting or a subclass. * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`. * @param array $setting_args WP_Customize_Setting or a subclass. * @return string */ public function filter_dynamic_setting_class( $setting_class, $setting_id, $setting_args ) { unset( $setting_id ); if ( ! empty( $setting_args['type'] ) && WP_Customize_Nav_Menu_Setting::TYPE === $setting_args['type'] ) { $setting_class = 'WP_Customize_Nav_Menu_Setting'; } elseif ( ! empty( $setting_args['type'] ) && WP_Customize_Nav_Menu_Item_Setting::TYPE === $setting_args['type'] ) { $setting_class = 'WP_Customize_Nav_Menu_Item_Setting'; } return $setting_class; } /** * Adds the customizer settings and controls. * * @since 4.3.0 */ public function customize_register() { $changeset = $this->manager->unsanitized_post_values(); // Preview settings for nav menus early so that the sections and controls will be added properly. $nav_menus_setting_ids = array(); foreach ( array_keys( $changeset ) as $setting_id ) { if ( preg_match( '/^(nav_menu_locations|nav_menu|nav_menu_item)\[/', $setting_id ) ) { $nav_menus_setting_ids[] = $setting_id; } } $settings = $this->manager->add_dynamic_settings( $nav_menus_setting_ids ); if ( $this->manager->settings_previewed() ) { foreach ( $settings as $setting ) { $setting->preview(); } } // Require JS-rendered control types. $this->manager->register_panel_type( 'WP_Customize_Nav_Menus_Panel' ); $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Control' ); $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Name_Control' ); $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Locations_Control' ); $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Auto_Add_Control' ); $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Item_Control' ); // Create a panel for Menus. $description = '<p>' . __( 'This panel is used for managing navigation menus for content you have already published on your site. You can create menus and add items for existing content such as pages, posts, categories, tags, formats, or custom links.' ) . '</p>'; if ( current_theme_supports( 'widgets' ) ) { $description .= '<p>' . sprintf( /* translators: %s: URL to the Widgets panel of the Customizer. */ __( 'Menus can be displayed in locations defined by your theme or in <a href="%s">widget areas</a> by adding a &#8220;Navigation Menu&#8221; widget.' ), "javascript:wp.customize.panel( 'widgets' ).focus();" ) . '</p>'; } else { $description .= '<p>' . __( 'Menus can be displayed in locations defined by your theme.' ) . '</p>'; } /* * Once multiple theme supports are allowed in WP_Customize_Panel, * this panel can be restricted to themes that support menus or widgets. */ $this->manager->add_panel( new WP_Customize_Nav_Menus_Panel( $this->manager, 'nav_menus', array( 'title' => __( 'Menus' ), 'description' => $description, 'priority' => 100, ) ) ); $menus = wp_get_nav_menus(); // Menu locations. $locations = get_registered_nav_menus(); $num_locations = count( $locations ); if ( 1 === $num_locations ) { $description = '<p>' . __( 'Your theme can display menus in one location. Select which menu you would like to use.' ) . '</p>'; } else { /* translators: %s: Number of menu locations. */ $description = '<p>' . sprintf( _n( 'Your theme can display menus in %s location. Select which menu you would like to use.', 'Your theme can display menus in %s locations. Select which menu appears in each location.', $num_locations ), number_format_i18n( $num_locations ) ) . '</p>'; } if ( current_theme_supports( 'widgets' ) ) { /* translators: URL to the Widgets panel of the Customizer. */ $description .= '<p>' . sprintf( __( 'If your theme has widget areas, you can also add menus there. Visit the <a href="%s">Widgets panel</a> and add a &#8220;Navigation Menu widget&#8221; to display a menu in a sidebar or footer.' ), "javascript:wp.customize.panel( 'widgets' ).focus();" ) . '</p>'; } $this->manager->add_section( 'menu_locations', array( 'title' => 1 === $num_locations ? _x( 'View Location', 'menu locations' ) : _x( 'View All Locations', 'menu locations' ), 'panel' => 'nav_menus', 'priority' => 30, 'description' => $description, ) ); $choices = array( '0' => __( '&mdash; Select &mdash;' ) ); foreach ( $menus as $menu ) { $choices[ $menu->term_id ] = wp_html_excerpt( $menu->name, 40, '&hellip;' ); } // Attempt to re-map the nav menu location assignments when previewing a theme switch. $mapped_nav_menu_locations = array(); if ( ! $this->manager->is_theme_active() ) { $theme_mods = get_option( 'theme_mods_' . $this->manager->get_stylesheet(), array() ); // If there is no data from a previous activation, start fresh. if ( empty( $theme_mods['nav_menu_locations'] ) ) { $theme_mods['nav_menu_locations'] = array(); } $mapped_nav_menu_locations = wp_map_nav_menu_locations( $theme_mods['nav_menu_locations'], $this->original_nav_menu_locations ); } foreach ( $locations as $location => $description ) { $setting_id = "nav_menu_locations[{$location}]"; $setting = $this->manager->get_setting( $setting_id ); if ( $setting ) { $setting->transport = 'postMessage'; remove_filter( "customize_sanitize_{$setting_id}", 'absint' ); add_filter( "customize_sanitize_{$setting_id}", array( $this, 'intval_base10' ) ); } else { $this->manager->add_setting( $setting_id, array( 'sanitize_callback' => array( $this, 'intval_base10' ), 'theme_supports' => 'menus', 'type' => 'theme_mod', 'transport' => 'postMessage', 'default' => 0, ) ); } // Override the assigned nav menu location if mapped during previewed theme switch. if ( empty( $changeset[ $setting_id ] ) && isset( $mapped_nav_menu_locations[ $location ] ) ) { $this->manager->set_post_value( $setting_id, $mapped_nav_menu_locations[ $location ] ); } $this->manager->add_control( new WP_Customize_Nav_Menu_Location_Control( $this->manager, $setting_id, array( 'label' => $description, 'location_id' => $location, 'section' => 'menu_locations', 'choices' => $choices, ) ) ); } // Used to denote post states for special pages. if ( ! function_exists( 'get_post_states' ) ) { require_once ABSPATH . 'wp-admin/includes/template.php'; } // Register each menu as a Customizer section, and add each menu item to each menu. foreach ( $menus as $menu ) { $menu_id = $menu->term_id; // Create a section for each menu. $section_id = 'nav_menu[' . $menu_id . ']'; $this->manager->add_section( new WP_Customize_Nav_Menu_Section( $this->manager, $section_id, array( 'title' => html_entity_decode( $menu->name, ENT_QUOTES, get_bloginfo( 'charset' ) ), 'priority' => 10, 'panel' => 'nav_menus', ) ) ); $nav_menu_setting_id = 'nav_menu[' . $menu_id . ']'; $this->manager->add_setting( new WP_Customize_Nav_Menu_Setting( $this->manager, $nav_menu_setting_id, array( 'transport' => 'postMessage', ) ) ); // Add the menu contents. $menu_items = (array) wp_get_nav_menu_items( $menu_id ); foreach ( array_values( $menu_items ) as $i => $item ) { // Create a setting for each menu item (which doesn't actually manage data, currently). $menu_item_setting_id = 'nav_menu_item[' . $item->ID . ']'; $value = (array) $item; if ( empty( $value['post_title'] ) ) { $value['title'] = ''; } $value['nav_menu_term_id'] = $menu_id; $this->manager->add_setting( new WP_Customize_Nav_Menu_Item_Setting( $this->manager, $menu_item_setting_id, array( 'value' => $value, 'transport' => 'postMessage', ) ) ); // Create a control for each menu item. $this->manager->add_control( new WP_Customize_Nav_Menu_Item_Control( $this->manager, $menu_item_setting_id, array( 'label' => $item->title, 'section' => $section_id, 'priority' => 10 + $i, ) ) ); } // Note: other controls inside of this section get added dynamically in JS via the MenuSection.ready() function. } // Add the add-new-menu section and controls. $this->manager->add_section( 'add_menu', array( 'type' => 'new_menu', 'title' => __( 'New Menu' ), 'panel' => 'nav_menus', 'priority' => 20, ) ); $this->manager->add_setting( new WP_Customize_Filter_Setting( $this->manager, 'nav_menus_created_posts', array( 'transport' => 'postMessage', 'type' => 'option', // To prevent theme prefix in changeset. 'default' => array(), 'sanitize_callback' => array( $this, 'sanitize_nav_menus_created_posts' ), ) ) ); } /** * Gets the base10 intval. * * This is used as a setting's sanitize_callback; we can't use just plain * intval because the second argument is not what intval() expects. * * @since 4.3.0 * * @param mixed $value Number to convert. * @return int Integer. */ public function intval_base10( $value ) { return intval( $value, 10 ); } /** * Returns an array of all the available item types. * * @since 4.3.0 * @since 4.7.0 Each array item now includes a `$type_label` in addition to `$title`, `$type`, and `$object`. * * @return array The available menu item types. */ public function available_item_types() { $item_types = array(); $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' ); if ( $post_types ) { foreach ( $post_types as $slug => $post_type ) { $item_types[] = array( 'title' => $post_type->labels->name, 'type_label' => $post_type->labels->singular_name, 'type' => 'post_type', 'object' => $post_type->name, ); } } $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'objects' ); if ( $taxonomies ) { foreach ( $taxonomies as $slug => $taxonomy ) { if ( 'post_format' === $taxonomy && ! current_theme_supports( 'post-formats' ) ) { continue; } $item_types[] = array( 'title' => $taxonomy->labels->name, 'type_label' => $taxonomy->labels->singular_name, 'type' => 'taxonomy', 'object' => $taxonomy->name, ); } } /** * Filters the available menu item types. * * @since 4.3.0 * @since 4.7.0 Each array item now includes a `$type_label` in addition to `$title`, `$type`, and `$object`. * * @param array $item_types Navigation menu item types. */ $item_types = apply_filters( 'customize_nav_menu_available_item_types', $item_types ); return $item_types; } /** * Adds a new `auto-draft` post. * * @since 4.7.0 * * @param array $postarr { * Post array. Note that post_status is overridden to be `auto-draft`. * * @var string $post_title Post title. Required. * @var string $post_type Post type. Required. * @var string $post_name Post name. * @var string $post_content Post content. * } * @return WP_Post|WP_Error Inserted auto-draft post object or error. */ public function insert_auto_draft_post( $postarr ) { if ( ! isset( $postarr['post_type'] ) ) { return new WP_Error( 'unknown_post_type', __( 'Invalid post type.' ) ); } if ( empty( $postarr['post_title'] ) ) { return new WP_Error( 'empty_title', __( 'Empty title.' ) ); } if ( ! empty( $postarr['post_status'] ) ) { return new WP_Error( 'status_forbidden', __( 'Status is forbidden.' ) ); } /* * If the changeset is a draft, this will change to draft the next time the changeset * is updated; otherwise, auto-draft will persist in autosave revisions, until save. */ $postarr['post_status'] = 'auto-draft'; // Auto-drafts are allowed to have empty post_names, so it has to be explicitly set. if ( empty( $postarr['post_name'] ) ) { $postarr['post_name'] = sanitize_title( $postarr['post_title'] ); } if ( ! isset( $postarr['meta_input'] ) ) { $postarr['meta_input'] = array(); } $postarr['meta_input']['_customize_draft_post_name'] = $postarr['post_name']; $postarr['meta_input']['_customize_changeset_uuid'] = $this->manager->changeset_uuid(); unset( $postarr['post_name'] ); add_filter( 'wp_insert_post_empty_content', '__return_false', 1000 ); $r = wp_insert_post( wp_slash( $postarr ), true ); remove_filter( 'wp_insert_post_empty_content', '__return_false', 1000 ); if ( is_wp_error( $r ) ) { return $r; } else { return get_post( $r ); } } /** * Ajax handler for adding a new auto-draft post. * * @since 4.7.0 */ public function ajax_insert_auto_draft_post() { if ( ! check_ajax_referer( 'customize-menus', 'customize-menus-nonce', false ) ) { wp_send_json_error( 'bad_nonce', 400 ); } if ( ! current_user_can( 'customize' ) ) { wp_send_json_error( 'customize_not_allowed', 403 ); } if ( empty( $_POST['params'] ) || ! is_array( $_POST['params'] ) ) { wp_send_json_error( 'missing_params', 400 ); } $params = wp_unslash( $_POST['params'] ); $illegal_params = array_diff( array_keys( $params ), array( 'post_type', 'post_title' ) ); if ( ! empty( $illegal_params ) ) { wp_send_json_error( 'illegal_params', 400 ); } $params = array_merge( array( 'post_type' => '', 'post_title' => '', ), $params ); if ( empty( $params['post_type'] ) || ! post_type_exists( $params['post_type'] ) ) { status_header( 400 ); wp_send_json_error( 'missing_post_type_param' ); } $post_type_object = get_post_type_object( $params['post_type'] ); if ( ! current_user_can( $post_type_object->cap->create_posts ) || ! current_user_can( $post_type_object->cap->publish_posts ) ) { status_header( 403 ); wp_send_json_error( 'insufficient_post_permissions' ); } $params['post_title'] = trim( $params['post_title'] ); if ( '' === $params['post_title'] ) { status_header( 400 ); wp_send_json_error( 'missing_post_title' ); } $r = $this->insert_auto_draft_post( $params ); if ( is_wp_error( $r ) ) { $error = $r; if ( ! empty( $post_type_object->labels->singular_name ) ) { $singular_name = $post_type_object->labels->singular_name; } else { $singular_name = __( 'Post' ); } $data = array( /* translators: 1: Post type name, 2: Error message. */ 'message' => sprintf( __( '%1$s could not be created: %2$s' ), $singular_name, $error->get_error_message() ), ); wp_send_json_error( $data ); } else { $post = $r; $data = array( 'post_id' => $post->ID, 'url' => get_permalink( $post->ID ), ); wp_send_json_success( $data ); } } /** * Prints the JavaScript templates used to render Menu Customizer components. * * Templates are imported into the JS use wp.template. * * @since 4.3.0 */ public function print_templates() { ?> <script type="text/html" id="tmpl-available-menu-item"> <li id="menu-item-tpl-{{ data.id }}" class="menu-item-tpl" data-menu-item-id="{{ data.id }}"> <div class="menu-item-bar"> <div class="menu-item-handle"> <span class="item-type" aria-hidden="true">{{ data.type_label }}</span> <span class="item-title" aria-hidden="true"> <span class="menu-item-title<# if ( ! data.title ) { #> no-title<# } #>">{{ data.title || wp.customize.Menus.data.l10n.untitled }}</span> </span> <button type="button" class="button-link item-add"> <span class="screen-reader-text"> <?php /* translators: 1: Title of a menu item, 2: Type of a menu item. */ printf( __( 'Add to menu: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.type_label }}' ); ?> </span> </button> </div> </div> </li> </script> <script type="text/html" id="tmpl-menu-item-reorder-nav"> <div class="menu-item-reorder-nav"> <?php printf( '<button type="button" class="menus-move-up">%1$s</button><button type="button" class="menus-move-down">%2$s</button><button type="button" class="menus-move-left">%3$s</button><button type="button" class="menus-move-right">%4$s</button>', __( 'Move up' ), __( 'Move down' ), __( 'Move one level up' ), __( 'Move one level down' ) ); ?> </div> </script> <script type="text/html" id="tmpl-nav-menu-delete-button"> <div class="menu-delete-item"> <button type="button" class="button-link button-link-delete"> <?php _e( 'Delete Menu' ); ?> </button> </div> </script> <script type="text/html" id="tmpl-nav-menu-submit-new-button"> <p id="customize-new-menu-submit-description"><?php _e( 'Click &#8220;Next&#8221; to start adding links to your new menu.' ); ?></p> <button id="customize-new-menu-submit" type="button" class="button" aria-describedby="customize-new-menu-submit-description"><?php _e( 'Next' ); ?></button> </script> <script type="text/html" id="tmpl-nav-menu-locations-header"> <span class="customize-control-title customize-section-title-menu_locations-heading">{{ data.l10n.locationsTitle }}</span> <p class="customize-control-description customize-section-title-menu_locations-description">{{ data.l10n.locationsDescription }}</p> </script> <script type="text/html" id="tmpl-nav-menu-create-menu-section-title"> <p class="add-new-menu-notice"> <?php _e( 'It does not look like your site has any menus yet. Want to build one? Click the button to start.' ); ?> </p> <p class="add-new-menu-notice"> <?php _e( 'You&#8217;ll create a menu, assign it a location, and add menu items like links to pages and categories. If your theme has multiple menu areas, you might need to create more than one.' ); ?> </p> <h3> <button type="button" class="button customize-add-menu-button"> <?php _e( 'Create New Menu' ); ?> </button> </h3> </script> <?php } /** * Prints the HTML template used to render the add-menu-item frame. * * @since 4.3.0 */ public function available_items_template() { ?> <div id="available-menu-items" class="accordion-container"> <div class="customize-section-title"> <button type="button" class="customize-section-back" tabindex="-1"> <span class="screen-reader-text"><?php _e( 'Back' ); ?></span> </button> <h3> <span class="customize-action"> <?php /* translators: &#9656; is the unicode right-pointing triangle. %s: Section title in the Customizer. */ printf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) ); ?> </span> <?php _e( 'Add Menu Items' ); ?> </h3> </div> <div id="available-menu-items-search" class="accordion-section cannot-expand"> <div class="accordion-section-title"> <label class="screen-reader-text" for="menu-items-search"><?php _e( 'Search Menu Items' ); ?></label> <input type="text" id="menu-items-search" placeholder="<?php esc_attr_e( 'Search menu items&hellip;' ); ?>" aria-describedby="menu-items-search-desc" /> <p class="screen-reader-text" id="menu-items-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p> <span class="spinner"></span> </div> <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> <ul class="accordion-section-content available-menu-items-list" data-type="search"></ul> </div> <?php // Ensure the page post type comes first in the list. $item_types = $this->available_item_types(); $page_item_type = null; foreach ( $item_types as $i => $item_type ) { if ( isset( $item_type['object'] ) && 'page' === $item_type['object'] ) { $page_item_type = $item_type; unset( $item_types[ $i ] ); } } $this->print_custom_links_available_menu_item(); if ( $page_item_type ) { $this->print_post_type_container( $page_item_type ); } // Containers for per-post-type item browsing; items are added with JS. foreach ( $item_types as $item_type ) { $this->print_post_type_container( $item_type ); } ?> </div><!-- #available-menu-items --> <?php } /** * Prints the markup for new menu items. * * To be used in the template #available-menu-items. * * @since 4.7.0 * * @param array $available_item_type Menu item data to output, including title, type, and label. */ protected function print_post_type_container( $available_item_type ) { $id = sprintf( 'available-menu-items-%s-%s', $available_item_type['type'], $available_item_type['object'] ); ?> <div id="<?php echo esc_attr( $id ); ?>" class="accordion-section"> <h4 class="accordion-section-title" role="presentation"> <?php echo esc_html( $available_item_type['title'] ); ?> <span class="spinner"></span> <span class="no-items"><?php _e( 'No items' ); ?></span> <button type="button" class="button-link" aria-expanded="false"> <span class="screen-reader-text"> <?php /* translators: %s: Title of a section with menu items. */ printf( __( 'Toggle section: %s' ), esc_html( $available_item_type['title'] ) ); ?> </span> <span class="toggle-indicator" aria-hidden="true"></span> </button> </h4> <div class="accordion-section-content"> <?php if ( 'post_type' === $available_item_type['type'] ) : ?> <?php $post_type_obj = get_post_type_object( $available_item_type['object'] ); ?> <?php if ( current_user_can( $post_type_obj->cap->create_posts ) && current_user_can( $post_type_obj->cap->publish_posts ) ) : ?> <div class="new-content-item"> <label for="<?php echo esc_attr( 'create-item-input-' . $available_item_type['object'] ); ?>" class="screen-reader-text"><?php echo esc_html( $post_type_obj->labels->add_new_item ); ?></label> <input type="text" id="<?php echo esc_attr( 'create-item-input-' . $available_item_type['object'] ); ?>" class="create-item-input" placeholder="<?php echo esc_attr( $post_type_obj->labels->add_new_item ); ?>"> <button type="button" class="button add-content"><?php _e( 'Add' ); ?></button> </div> <?php endif; ?> <?php endif; ?> <ul class="available-menu-items-list" data-type="<?php echo esc_attr( $available_item_type['type'] ); ?>" data-object="<?php echo esc_attr( $available_item_type['object'] ); ?>" data-type_label="<?php echo esc_attr( isset( $available_item_type['type_label'] ) ? $available_item_type['type_label'] : $available_item_type['type'] ); ?>"></ul> </div> </div> <?php } /** * Prints the markup for available menu item custom links. * * @since 4.7.0 */ protected function print_custom_links_available_menu_item() { ?> <div id="new-custom-menu-item" class="accordion-section"> <h4 class="accordion-section-title" role="presentation"> <?php _e( 'Custom Links' ); ?> <button type="button" class="button-link" aria-expanded="false"> <span class="screen-reader-text"><?php _e( 'Toggle section: Custom Links' ); ?></span> <span class="toggle-indicator" aria-hidden="true"></span> </button> </h4> <div class="accordion-section-content customlinkdiv"> <input type="hidden" value="custom" id="custom-menu-item-type" name="menu-item[-1][menu-item-type]" /> <p id="menu-item-url-wrap" class="wp-clearfix"> <label class="howto" for="custom-menu-item-url"><?php _e( 'URL' ); ?></label> <input id="custom-menu-item-url" name="menu-item[-1][menu-item-url]" type="text" class="code menu-item-textbox" placeholder="https://"> </p> <p id="menu-item-name-wrap" class="wp-clearfix"> <label class="howto" for="custom-menu-item-name"><?php _e( 'Link Text' ); ?></label> <input id="custom-menu-item-name" name="menu-item[-1][menu-item-title]" type="text" class="regular-text menu-item-textbox"> </p> <p class="button-controls"> <span class="add-to-menu"> <input type="submit" class="button submit-add-to-menu right" value="<?php esc_attr_e( 'Add to Menu' ); ?>" name="add-custom-menu-item" id="custom-menu-item-submit"> <span class="spinner"></span> </span> </p> </div> </div> <?php } // // Start functionality specific to partial-refresh of menu changes in Customizer preview. // /** * Nav menu args used for each instance, keyed by the args HMAC. * * @since 4.3.0 * @var array */ public $preview_nav_menu_instance_args = array(); /** * Filters arguments for dynamic nav_menu selective refresh partials. * * @since 4.5.0 * * @param array|false $partial_args Partial args. * @param string $partial_id Partial ID. * @return array Partial args. */ public function customize_dynamic_partial_args( $partial_args, $partial_id ) { if ( preg_match( '/^nav_menu_instance\[[0-9a-f]{32}\]$/', $partial_id ) ) { if ( false === $partial_args ) { $partial_args = array(); } $partial_args = array_merge( $partial_args, array( 'type' => 'nav_menu_instance', 'render_callback' => array( $this, 'render_nav_menu_partial' ), 'container_inclusive' => true, 'settings' => array(), // Empty because the nav menu instance may relate to a menu or a location. 'capability' => 'edit_theme_options', ) ); } return $partial_args; } /** * Adds hooks for the Customizer preview. * * @since 4.3.0 */ public function customize_preview_init() { add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue_deps' ) ); add_filter( 'wp_nav_menu_args', array( $this, 'filter_wp_nav_menu_args' ), 1000 ); add_filter( 'wp_nav_menu', array( $this, 'filter_wp_nav_menu' ), 10, 2 ); add_action( 'wp_footer', array( $this, 'export_preview_data' ), 1 ); add_filter( 'customize_render_partials_response', array( $this, 'export_partial_rendered_nav_menu_instances' ) ); } /** * Makes the auto-draft status protected so that it can be queried. * * @since 4.7.0 * * @global stdClass[] $wp_post_statuses List of post statuses. */ public function make_auto_draft_status_previewable() { global $wp_post_statuses; $wp_post_statuses['auto-draft']->protected = true; } /** * Sanitizes post IDs for posts created for nav menu items to be published. * * @since 4.7.0 * * @param array $value Post IDs. * @return array Post IDs. */ public function sanitize_nav_menus_created_posts( $value ) { $post_ids = array(); foreach ( wp_parse_id_list( $value ) as $post_id ) { if ( empty( $post_id ) ) { continue; } $post = get_post( $post_id ); if ( 'auto-draft' !== $post->post_status && 'draft' !== $post->post_status ) { continue; } $post_type_obj = get_post_type_object( $post->post_type ); if ( ! $post_type_obj ) { continue; } if ( ! current_user_can( $post_type_obj->cap->publish_posts ) || ! current_user_can( 'edit_post', $post_id ) ) { continue; } $post_ids[] = $post->ID; } return $post_ids; } /** * Publishes the auto-draft posts that were created for nav menu items. * * The post IDs will have been sanitized by already by * `WP_Customize_Nav_Menu_Items::sanitize_nav_menus_created_posts()` to * remove any post IDs for which the user cannot publish or for which the * post is not an auto-draft. * * @since 4.7.0 * * @param WP_Customize_Setting $setting Customizer setting object. */ public function save_nav_menus_created_posts( $setting ) { $post_ids = $setting->post_value(); if ( ! empty( $post_ids ) ) { foreach ( $post_ids as $post_id ) { // Prevent overriding the status that a user may have prematurely updated the post to. $current_status = get_post_status( $post_id ); if ( 'auto-draft' !== $current_status && 'draft' !== $current_status ) { continue; } $target_status = 'attachment' === get_post_type( $post_id ) ? 'inherit' : 'publish'; $args = array( 'ID' => $post_id, 'post_status' => $target_status, ); $post_name = get_post_meta( $post_id, '_customize_draft_post_name', true ); if ( $post_name ) { $args['post_name'] = $post_name; } // Note that wp_publish_post() cannot be used because unique slugs need to be assigned. wp_update_post( wp_slash( $args ) ); delete_post_meta( $post_id, '_customize_draft_post_name' ); } } } /** * Keeps track of the arguments that are being passed to wp_nav_menu(). * * @since 4.3.0 * * @see wp_nav_menu() * @see WP_Customize_Widgets::filter_dynamic_sidebar_params() * * @param array $args An array containing wp_nav_menu() arguments. * @return array Arguments. */ public function filter_wp_nav_menu_args( $args ) { /* * The following conditions determine whether or not this instance of * wp_nav_menu() can use selective refreshed. A wp_nav_menu() can be * selective refreshed if... */ $can_partial_refresh = ( // ...if wp_nav_menu() is directly echoing out the menu (and thus isn't manipulating the string after generated), ! empty( $args['echo'] ) && // ...and if the fallback_cb can be serialized to JSON, since it will be included in the placement context data, ( empty( $args['fallback_cb'] ) || is_string( $args['fallback_cb'] ) ) && // ...and if the walker can also be serialized to JSON, since it will be included in the placement context data as well, ( empty( $args['walker'] ) || is_string( $args['walker'] ) ) // ...and if it has a theme location assigned or an assigned menu to display, && ( ! empty( $args['theme_location'] ) || ( ! empty( $args['menu'] ) && ( is_numeric( $args['menu'] ) || is_object( $args['menu'] ) ) ) ) && // ...and if the nav menu would be rendered with a wrapper container element (upon which to attach data-* attributes). ( ! empty( $args['container'] ) || ( isset( $args['items_wrap'] ) && '<' === substr( $args['items_wrap'], 0, 1 ) ) ) ); $args['can_partial_refresh'] = $can_partial_refresh; $exported_args = $args; // Empty out args which may not be JSON-serializable. if ( ! $can_partial_refresh ) { $exported_args['fallback_cb'] = ''; $exported_args['walker'] = ''; } /* * Replace object menu arg with a term_id menu arg, as this exports better * to JS and is easier to compare hashes. */ if ( ! empty( $exported_args['menu'] ) && is_object( $exported_args['menu'] ) ) { $exported_args['menu'] = $exported_args['menu']->term_id; } ksort( $exported_args ); $exported_args['args_hmac'] = $this->hash_nav_menu_args( $exported_args ); $args['customize_preview_nav_menus_args'] = $exported_args; $this->preview_nav_menu_instance_args[ $exported_args['args_hmac'] ] = $exported_args; return $args; } /** * Prepares wp_nav_menu() calls for partial refresh. * * Injects attributes into container element. * * @since 4.3.0 * * @see wp_nav_menu() * * @param string $nav_menu_content The HTML content for the navigation menu. * @param object $args An object containing wp_nav_menu() arguments. * @return string Nav menu HTML with selective refresh attributes added if partial can be refreshed. */ public function filter_wp_nav_menu( $nav_menu_content, $args ) { if ( isset( $args->customize_preview_nav_menus_args['can_partial_refresh'] ) && $args->customize_preview_nav_menus_args['can_partial_refresh'] ) { $attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'nav_menu_instance[' . $args->customize_preview_nav_menus_args['args_hmac'] . ']' ) ); $attributes .= ' data-customize-partial-type="nav_menu_instance"'; $attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $args->customize_preview_nav_menus_args ) ) ); $nav_menu_content = preg_replace( '#^(<\w+)#', '$1 ' . str_replace( '\\', '\\\\', $attributes ), $nav_menu_content, 1 ); } return $nav_menu_content; } /** * Hashes (hmac) the nav menu arguments to ensure they are not tampered with when * submitted in the Ajax request. * * Note that the array is expected to be pre-sorted. * * @since 4.3.0 * * @param array $args The arguments to hash. * @return string Hashed nav menu arguments. */ public function hash_nav_menu_args( $args ) { return wp_hash( serialize( $args ) ); } /** * Enqueues scripts for the Customizer preview. * * @since 4.3.0 */ public function customize_preview_enqueue_deps() { wp_enqueue_script( 'customize-preview-nav-menus' ); // Note that we have overridden this. } /** * Exports data from PHP to JS. * * @since 4.3.0 */ public function export_preview_data() { // Why not wp_localize_script? Because we're not localizing, and it forces values into strings. $exports = array( 'navMenuInstanceArgs' => $this->preview_nav_menu_instance_args, ); printf( '<script>var _wpCustomizePreviewNavMenusExports = %s;</script>', wp_json_encode( $exports ) ); } /** * Exports any wp_nav_menu() calls during the rendering of any partials. * * @since 4.5.0 * * @param array $response Response. * @return array Response. */ public function export_partial_rendered_nav_menu_instances( $response ) { $response['nav_menu_instance_args'] = $this->preview_nav_menu_instance_args; return $response; } /** * Renders a specific menu via wp_nav_menu() using the supplied arguments. * * @since 4.3.0 * * @see wp_nav_menu() * * @param WP_Customize_Partial $partial Partial. * @param array $nav_menu_args Nav menu args supplied as container context. * @return string|false */ public function render_nav_menu_partial( $partial, $nav_menu_args ) { unset( $partial ); if ( ! isset( $nav_menu_args['args_hmac'] ) ) { // Error: missing_args_hmac. return false; } $nav_menu_args_hmac = $nav_menu_args['args_hmac']; unset( $nav_menu_args['args_hmac'] ); ksort( $nav_menu_args ); if ( ! hash_equals( $this->hash_nav_menu_args( $nav_menu_args ), $nav_menu_args_hmac ) ) { // Error: args_hmac_mismatch. return false; } ob_start(); wp_nav_menu( $nav_menu_args ); $content = ob_get_clean(); return $content; } } ``` | Version | Description | | --- | --- | | [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
programming_docs
wordpress class WP_Ajax_Response {} class WP\_Ajax\_Response {} =========================== Send XML response back to Ajax request. [WP\_Ajax\_Response](wp_ajax_response) is WordPress’ class for generating XML-formatted responses to Ajax requests. This is most commonly used to generate responses to custom AJAX actions when using the [wp\_ajax\_](../hooks/wp_ajax_action "Plugin API/Action Reference/wp ajax (action)") action hook. NOTE: Refer source code for the complete methods and properties. $responses() An array that stores the XML responses to be sent. To use [WP\_Ajax\_Response](wp_ajax_response), you need to instantiate the class with an array of options, then call the instances `send()` method to output the response. The options array takes the following key=>value pairs: β€˜what’ A string containing the XMLRPC response type (used as the name of the xml element). β€˜action’ A boolean or string that will behave like a nonce. This is added to the **response** element’s *action* attribute. β€˜id’ This is either an integer (usually 1) or a [WP\_Error](wp_error "Function Reference/WP Error") object (if you need to return an error). Most commonly, the id value is used as a boolean, where 1 is a success and 0 is a failure. β€˜old\_id’ This is `false` by default, but you can alternatively provide an integer for the previous id, if needed. β€˜position’ This is an integer or a string where -1 = top, 1 = bottom, β€˜html ID’ = after, β€˜-html ID’ = before β€˜data’ A string containing output content or a message (such as html). This is disregarded if you pass a [WP\_Error](wp_error) object as the id. β€˜supplemental’ This can an associative array of strings, which will be rendered into children of the `<supplemental>` element. Keys become element names, and values are embedded in CDATA within those elements. Useful for passing additional information to the browser. Responses are made in the XML-RPC format and may be handled by JavaScript. A typical WordPress autosave response looks like this: ``` <?xml version='1.0' standalone='yes'?> <wp_ajax> <response action='autosave_1'> <autosave id='1' position='1'> <response_data> <![CDATA[Draft saved at 9:31:55 pm.]]> </response_data> <supplemental></supplemental> </autosave> </response> </wp_ajax> ``` Let’s break this example down to see what it means: <wp\_ajax> This the root element of every response. All responses made by the *[WP\_Ajax\_Response](wp_ajax_response)* class are wrapped in the `<wp_ajax>` element. <response> Immediately within the wp\_ajax element is `<response>`, which contains the attributes β€˜action’ and β€˜position’. These attributes correspond to the β€˜action’ and β€˜position’ key=>value pairs defined in the options array. <autosave> (arbitrary) Next, the above example shows an `<autosave>` element – this element matches the value of the β€˜what’ key=>value pair in the options array. In your own use, **this element can be named whatever you like**, provided it is a valid XML element name. <response\_data> / <wp\_error\_data> Within the custom response element (e.g. `<autosave>`), there will either be a `<response_data>` element (with CDATA tag) or a `<wp_error_data>` element. If you pass a [WP\_Error](wp_error) object to [WP\_Ajax\_Response](wp_ajax_response) as the β€˜id’ in your options array, the `<wp_error_data>` element is automatically generated. Otherwise, the `<response_data>` element is used with whatever value you passed to [WP\_Ajax\_Response](wp_ajax_response) with your option array’s β€œdata” value. For the most part, any content you want to pass back to the browser (such as HTML), can be passed in your option array’s β€œdata” key=>value pair. <supplemental> Finally, the `<supplemental>` element will contain whatever arbitrary structure you decide to pass along with your option array’s β€œsupplemental” key=>value pair. * [\_\_construct](wp_ajax_response/__construct) β€” Constructor - Passes args to WP\_Ajax\_Response::add(). * [add](wp_ajax_response/add) β€” Appends data to an XML response based on given arguments. * [send](wp_ajax_response/send) β€” Display XML formatted responses. File: `wp-includes/class-wp-ajax-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-ajax-response.php/) ``` class WP_Ajax_Response { /** * Store XML responses to send. * * @since 2.1.0 * @var array */ public $responses = array(); /** * Constructor - Passes args to WP_Ajax_Response::add(). * * @since 2.1.0 * * @see WP_Ajax_Response::add() * * @param string|array $args Optional. Will be passed to add() method. */ public function __construct( $args = '' ) { if ( ! empty( $args ) ) { $this->add( $args ); } } /** * 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> * * @since 2.1.0 * * @param string|array $args { * Optional. An array or string of XML response arguments. * * @type string $what XML-RPC response type. Used as a child element of `<response>`. * Default 'object' (`<object>`). * @type string|false $action Value 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. * @type int|WP_Error $id The response ID, used as the response type `id` attribute. Also * accepts a `WP_Error` object if the ID does not exist. Default 0. * @type int|false $old_id The previous response ID. Used as the value for the response type * `old_id` attribute. False hides the attribute. Default false. * @type string $position Value of the response type `position` attribute. Accepts 1 (bottom), * -1 (top), HTML ID (after), or -HTML ID (before). Default 1 (bottom). * @type string|WP_Error $data The response content/message. Also accepts a WP_Error object if the * ID does not exist. Default empty. * @type array $supplemental An array of extra strings that will be output within a `<supplemental>` * element as CDATA. Default empty array. * } * @return string XML response. */ 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; } /** * Display XML formatted responses. * * Sets the content type header to text/xml. * * @since 2.1.0 */ 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(); } } } ``` | Version | Description | | --- | --- | | [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. | wordpress class WP_Theme_JSON_Schema {} class WP\_Theme\_JSON\_Schema {} ================================ Class that migrates a given theme.json structure to the latest schema. This class is for internal core usage and is not supposed to be used by extenders (plugins and/or themes). This is a low-level API that may need to do breaking changes. Please, use get\_global\_settings, get\_global\_styles, and get\_global\_stylesheet instead. * [migrate](wp_theme_json_schema/migrate) β€” Function that migrates a given theme.json structure to the last version. * [migrate\_v1\_to\_v2](wp_theme_json_schema/migrate_v1_to_v2) β€” Removes the custom prefixes for a few properties that were part of v1: * [rename\_paths](wp_theme_json_schema/rename_paths) β€” Processes the settings subtree. * [rename\_settings](wp_theme_json_schema/rename_settings) β€” Processes a settings array, renaming or moving properties. * [unset\_setting\_by\_path](wp_theme_json_schema/unset_setting_by_path) β€” Removes a property from within the provided settings by its path. File: `wp-includes/class-wp-theme-json-schema.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme-json-schema.php/) ``` class WP_Theme_JSON_Schema { /** * Maps old properties to their new location within the schema's settings. * This will be applied at both the defaults and individual block levels. */ const V1_TO_V2_RENAMED_PATHS = array( 'border.customRadius' => 'border.radius', 'spacing.customMargin' => 'spacing.margin', 'spacing.customPadding' => 'spacing.padding', 'typography.customLineHeight' => 'typography.lineHeight', ); /** * Function that migrates a given theme.json structure to the last version. * * @since 5.9.0 * * @param array $theme_json The structure to migrate. * * @return array The structure in the last version. */ public static function migrate( $theme_json ) { if ( ! isset( $theme_json['version'] ) ) { $theme_json = array( 'version' => WP_Theme_JSON::LATEST_SCHEMA, ); } if ( 1 === $theme_json['version'] ) { $theme_json = self::migrate_v1_to_v2( $theme_json ); } return $theme_json; } /** * Removes the custom prefixes for a few properties * that were part of v1: * * 'border.customRadius' => 'border.radius', * 'spacing.customMargin' => 'spacing.margin', * 'spacing.customPadding' => 'spacing.padding', * 'typography.customLineHeight' => 'typography.lineHeight', * * @since 5.9.0 * * @param array $old Data to migrate. * * @return array Data without the custom prefixes. */ private static function migrate_v1_to_v2( $old ) { // Copy everything. $new = $old; // Overwrite the things that changed. if ( isset( $old['settings'] ) ) { $new['settings'] = self::rename_paths( $old['settings'], self::V1_TO_V2_RENAMED_PATHS ); } // Set the new version. $new['version'] = 2; return $new; } /** * Processes the settings subtree. * * @since 5.9.0 * * @param array $settings Array to process. * @param array $paths_to_rename Paths to rename. * * @return array The settings in the new format. */ private static function rename_paths( $settings, $paths_to_rename ) { $new_settings = $settings; // Process any renamed/moved paths within default settings. self::rename_settings( $new_settings, $paths_to_rename ); // Process individual block settings. if ( isset( $new_settings['blocks'] ) && is_array( $new_settings['blocks'] ) ) { foreach ( $new_settings['blocks'] as &$block_settings ) { self::rename_settings( $block_settings, $paths_to_rename ); } } return $new_settings; } /** * Processes a settings array, renaming or moving properties. * * @since 5.9.0 * * @param array $settings Reference to settings either defaults or an individual block's. * @param array $paths_to_rename Paths to rename. */ private static function rename_settings( &$settings, $paths_to_rename ) { foreach ( $paths_to_rename as $original => $renamed ) { $original_path = explode( '.', $original ); $renamed_path = explode( '.', $renamed ); $current_value = _wp_array_get( $settings, $original_path, null ); if ( null !== $current_value ) { _wp_array_set( $settings, $renamed_path, $current_value ); self::unset_setting_by_path( $settings, $original_path ); } } } /** * Removes a property from within the provided settings by its path. * * @since 5.9.0 * * @param array $settings Reference to the current settings array. * @param array $path Path to the property to be removed. * * @return void */ private static function unset_setting_by_path( &$settings, $path ) { $tmp_settings = &$settings; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable $last_key = array_pop( $path ); foreach ( $path as $key ) { $tmp_settings = &$tmp_settings[ $key ]; } unset( $tmp_settings[ $last_key ] ); } } ``` | Version | Description | | --- | --- | | [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. | wordpress class WP_Object_Cache {} class WP\_Object\_Cache {} ========================== Core class that implements an object cache. The WordPress Object Cache is used to save on trips to the database. The Object Cache stores all of the cache data to memory and makes the cache contents available by using a key, which is used to name and later retrieve the cache contents. The Object Cache can be replaced by other caching mechanisms by placing files in the wp-content folder which is looked at in wp-settings. If that file exists, then this file will not be included. [WP\_Object\_Cache](wp_object_cache) is WordPress’ class for caching data which may be computationally expensive to regenerate, such as the result of complex database queries. The object cache is defined in `[wp-includes/cache.php](https://core.trac.wordpress.org/browser/tags/5.5.1/src/wp-includes/cache.php#L0)`. Do not use the class directly in your code when writing plugins, but use the wp\_cache functions listed below. By default, the object cache is non-persistent. This means that data stored in the cache resides in memory only and only for the duration of the request. Cached data will not be stored persistently across page loads unless you install a [persistent caching](wp_object_cache#persistent-caching) plugin. Use the [Transients API](https://developer.wordpress.org/apis/handbook/transients/ "Transients API") instead of these functions if you need to guarantee that your data will be cached. If persistent caching is configured, then the transients functions will use the wp\_cache functions described in this document. However if persistent caching has not been enabled, then the data will instead be cached to the options table. Most of these functions take a: * $key: the key to indicate the value. * $data: the value you want to store. * $group: (optional) this is a way of grouping data within the cache. Allows you to use the same key across different groups. * $expire: (optional) this defines how many seconds to keep the cache for. Only applicable to some functions. Defaults to 0 (as long as possible). [wp\_cache\_add](../functions/wp_cache_add) ``` wp_cache_add( $key, $data, $group, $expire ) ``` This function adds data to the cache if the cache key doesn’t already exist. If it does exist, the data is not added and the function returns false. [wp\_cache\_set](../functions/wp_cache_set) ``` wp_cache_set( $key, $data, $group, $expire ) ``` Adds data to the cache. If the cache key already exists, then it will be overwritten; if not then it will be created. [wp\_cache\_get](../functions/wp_cache_get) ``` wp_cache_get( $key, $group ) wp_cache_get( $key, $group = '', $force = false, $found = null ) ``` Returns the value of the cached object, or false if the cache key doesn’t exist. To disambiguate a cached false from a non-existing key, you should do absolute testing of $found, which is passed by reference, against false: if $found === false, the key does not exist. [wp\_cache\_delete](../functions/wp_cache_delete) ``` wp_cache_delete( $key, $group ) ``` Clears data from the cache for the given key. [wp\_cache\_replace](../functions/wp_cache_replace) ``` wp_cache_replace( $key, $data, $group, $expire ) ``` Replaces the given cache if it exists, returns false otherwise. This is similar to [wp\_cache\_set()](../functions/wp_cache_set) except the cache object is not added if it doesn’t already exist. [wp\_cache\_flush](../functions/wp_cache_flush) ``` wp_cache_flush() ``` Clears all cached data. [wp\_cache\_add\_non\_persistent\_groups](../functions/wp_cache_add_non_persistent_groups) ``` wp_cache_add_non_persistent_groups($groups) ``` Hints to the object cache that the group or list of groups should not be cached in persistent storage. This is useful when adding items to the cache that should only be available for the duration of a script session, and not beyond. $groups can be an array of strings, or a single group name. NB: only some caching plugins implement this function! Prior to [WordPress 2.5](https://wordpress.org/support/wordpress-version/version-2-5/ "Version 2.5"), data stored using the wp\_cache functions was stored persistently if you added define('WP\_CACHE', true) to your wp-config.php file. This is no longer the case, **and adding the define will have no effect** unless you install a persistent cache plugin (see list below). * [Memcached Object Cache](https://wordpress.org/extend/plugins/memcached/) provides a persistent backend for the WordPress object cache. A memcached server and the PECL memcached extension are required. * [Redis Object Cache](https://wordpress.org/plugins/redis-cache/) supports the use of [Predis](https://github.com/nrk/predis) (PHP client library), [HHVM’s Redis extension](https://github.com/facebook/hhvm/blob/master/hphp/system/php/redis/Redis.php) and the [PECL Redis extension](https://pecl.php.net/package/redis) to provide a persistent backend for the WordPress object cache. [Redis](http://redis.io/) is required. * [W3 Total Cache](https://wordpress.org/extend/plugins/w3-total-cache/) provides object level caching using disk, opcode or memcache(d) memory stores. Be advised that W3TC also provides: browser, page and database caching, in addition to Content Delivery Network Support, Mobile Support, Minification and more. It is not the easiest way to get object caching in WordPress. * [LiteSpeed Cache](https://wordpress.org/plugins/litespeed-cache/) supports the use of Redis, Memcached, and LSMCD object caches. LSCWP also provides server-level full-page caching, support for browser cache and CDN, and other optimization features. But be advised that this solution requires [LiteSpeed Web Server,](https://en.wikipedia.org/wiki/LiteSpeed_Web_Server) . The [Transients\_API](https://developer.wordpress.org/apis/handbook/transients/ "Transients API") provides persistent but temporary data caching by giving it a custom name and a timeframe after which it will be expired and regenerated. *Note: Transients only get deleted when a request is made. So, until someone visits your page and calls up the Transient, it will stay in the DB. In short: It’s not a real persistent cache and not equal to stuff running on cron jobs.* * The [Debug Bar](https://wordpress.org/plugins/debug-bar/) plugin helps you analyze the object cache. * Scott Taylor’s article [WordPress + Memcached](http://scotty-t.com/2012/01/20/wordpress-memcached/) explains various cache plugins and concepts. * [\_\_construct](wp_object_cache/__construct) β€” Sets up object properties; PHP 5 style constructor. * [\_\_get](wp_object_cache/__get) β€” Makes private properties readable for backward compatibility. * [\_\_isset](wp_object_cache/__isset) β€” Makes private properties checkable for backward compatibility. * [\_\_set](wp_object_cache/__set) β€” Makes private properties settable for backward compatibility. * [\_\_unset](wp_object_cache/__unset) β€” Makes private properties un-settable for backward compatibility. * [\_exists](wp_object_cache/_exists) β€” Serves as a utility function to determine whether a key exists in the cache. * [add](wp_object_cache/add) β€” Adds data to the cache if it doesn't already exist. * [add\_global\_groups](wp_object_cache/add_global_groups) β€” Sets the list of global cache groups. * [add\_multiple](wp_object_cache/add_multiple) β€” Adds multiple values to the cache in one call. * [decr](wp_object_cache/decr) β€” Decrements numeric cache item's value. * [delete](wp_object_cache/delete) β€” Removes the contents of the cache key in the group. * [delete\_multiple](wp_object_cache/delete_multiple) β€” Deletes multiple values from the cache in one call. * [flush](wp_object_cache/flush) β€” Clears the object cache of all data. * [flush\_group](wp_object_cache/flush_group) β€” Removes all cache items in a group. * [get](wp_object_cache/get) β€” Retrieves the cache contents, if it exists. * [get\_multiple](wp_object_cache/get_multiple) β€” Retrieves multiple values from the cache in one call. * [incr](wp_object_cache/incr) β€” Increments numeric cache item's value. * [is\_valid\_key](wp_object_cache/is_valid_key) β€” Serves as a utility function to determine whether a key is valid. * [replace](wp_object_cache/replace) β€” Replaces the contents in the cache, if contents already exist. * [reset](wp_object_cache/reset) β€” Resets cache keys. β€” deprecated * [set](wp_object_cache/set) β€” Sets the data contents into the cache. * [set\_multiple](wp_object_cache/set_multiple) β€” Sets multiple values to the cache in one call. * [stats](wp_object_cache/stats) β€” Echoes the stats of the caching. * [switch\_to\_blog](wp_object_cache/switch_to_blog) β€” Switches the internal blog ID. File: `wp-includes/class-wp-object-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-object-cache.php/) ``` class WP_Object_Cache { /** * Holds the cached objects. * * @since 2.0.0 * @var array */ private $cache = array(); /** * The amount of times the cache data was already stored in the cache. * * @since 2.5.0 * @var int */ public $cache_hits = 0; /** * Amount of times the cache did not have the request in cache. * * @since 2.0.0 * @var int */ public $cache_misses = 0; /** * List of global cache groups. * * @since 3.0.0 * @var string[] */ protected $global_groups = array(); /** * The blog prefix to prepend to keys in non-global groups. * * @since 3.5.0 * @var string */ private $blog_prefix; /** * Holds the value of is_multisite(). * * @since 3.5.0 * @var bool */ private $multisite; /** * Sets up object properties; PHP 5 style constructor. * * @since 2.0.8 */ public function __construct() { $this->multisite = is_multisite(); $this->blog_prefix = $this->multisite ? get_current_blog_id() . ':' : ''; } /** * Makes private properties readable for backward compatibility. * * @since 4.0.0 * * @param string $name Property to get. * @return mixed Property. */ public function __get( $name ) { return $this->$name; } /** * Makes private properties settable for backward compatibility. * * @since 4.0.0 * * @param string $name Property to set. * @param mixed $value Property value. * @return mixed Newly-set property. */ public function __set( $name, $value ) { return $this->$name = $value; } /** * Makes private properties checkable for backward compatibility. * * @since 4.0.0 * * @param string $name Property to check if set. * @return bool Whether the property is set. */ public function __isset( $name ) { return isset( $this->$name ); } /** * Makes private properties un-settable for backward compatibility. * * @since 4.0.0 * * @param string $name Property to unset. */ public function __unset( $name ) { unset( $this->$name ); } /** * Serves as a utility function to determine whether a key is valid. * * @since 6.1.0 * * @param int|string $key Cache key to check for validity. * @return bool Whether the key is valid. */ protected function is_valid_key( $key ) { if ( is_int( $key ) ) { return true; } if ( is_string( $key ) && trim( $key ) !== '' ) { return true; } $type = gettype( $key ); if ( ! function_exists( '__' ) ) { wp_load_translations_early(); } $message = is_string( $key ) ? __( 'Cache key must not be an empty string.' ) /* translators: %s: The type of the given cache key. */ : sprintf( __( 'Cache key must be integer or non-empty string, %s given.' ), $type ); _doing_it_wrong( sprintf( '%s::%s', __CLASS__, debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 )[1]['function'] ), $message, '6.1.0' ); return false; } /** * Serves as a utility function to determine whether a key exists in the cache. * * @since 3.4.0 * * @param int|string $key Cache key to check for existence. * @param string $group Cache group for the key existence check. * @return bool Whether the key exists in the cache for the given group. */ protected function _exists( $key, $group ) { return isset( $this->cache[ $group ] ) && ( isset( $this->cache[ $group ][ $key ] ) || array_key_exists( $key, $this->cache[ $group ] ) ); } /** * Adds data to the cache if it doesn't already exist. * * @since 2.0.0 * * @uses WP_Object_Cache::_exists() Checks to see if the cache already has data. * @uses WP_Object_Cache::set() Sets the data after the checking the cache * contents existence. * * @param int|string $key What to call the contents in the cache. * @param mixed $data The contents to store in the cache. * @param string $group Optional. Where to group the cache contents. Default 'default'. * @param int $expire Optional. When to expire the cache contents, in seconds. * Default 0 (no expiration). * @return bool True on success, false if cache key and group already exist. */ public function add( $key, $data, $group = 'default', $expire = 0 ) { if ( wp_suspend_cache_addition() ) { return false; } if ( ! $this->is_valid_key( $key ) ) { return false; } if ( empty( $group ) ) { $group = 'default'; } $id = $key; if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) { $id = $this->blog_prefix . $key; } if ( $this->_exists( $id, $group ) ) { return false; } return $this->set( $key, $data, $group, (int) $expire ); } /** * Adds multiple values to the cache in one call. * * @since 6.0.0 * * @param array $data Array of keys and values to be added. * @param string $group Optional. Where the cache contents are grouped. Default empty. * @param int $expire Optional. When to expire the cache contents, in seconds. * Default 0 (no expiration). * @return bool[] Array of return values, grouped by key. Each value is either * true on success, or false if cache key and group already exist. */ public function add_multiple( array $data, $group = '', $expire = 0 ) { $values = array(); foreach ( $data as $key => $value ) { $values[ $key ] = $this->add( $key, $value, $group, $expire ); } return $values; } /** * Replaces the contents in the cache, if contents already exist. * * @since 2.0.0 * * @see WP_Object_Cache::set() * * @param int|string $key What to call the contents in the cache. * @param mixed $data The contents to store in the cache. * @param string $group Optional. Where to group the cache contents. Default 'default'. * @param int $expire Optional. When to expire the cache contents, in seconds. * Default 0 (no expiration). * @return bool True if contents were replaced, false if original value does not exist. */ public function replace( $key, $data, $group = 'default', $expire = 0 ) { if ( ! $this->is_valid_key( $key ) ) { return false; } if ( empty( $group ) ) { $group = 'default'; } $id = $key; if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) { $id = $this->blog_prefix . $key; } if ( ! $this->_exists( $id, $group ) ) { return false; } return $this->set( $key, $data, $group, (int) $expire ); } /** * Sets the data contents into the cache. * * The cache contents are grouped by the $group parameter followed by the * $key. This allows for duplicate IDs in unique groups. Therefore, naming of * the group should be used with care and should follow normal function * naming guidelines outside of core WordPress usage. * * The $expire parameter is not used, because the cache will automatically * expire for each time a page is accessed and PHP finishes. The method is * more for cache plugins which use files. * * @since 2.0.0 * @since 6.1.0 Returns false if cache key is invalid. * * @param int|string $key What to call the contents in the cache. * @param mixed $data The contents to store in the cache. * @param string $group Optional. Where to group the cache contents. Default 'default'. * @param int $expire Optional. Not used. * @return bool True if contents were set, false if key is invalid. */ public function set( $key, $data, $group = 'default', $expire = 0 ) { if ( ! $this->is_valid_key( $key ) ) { return false; } if ( empty( $group ) ) { $group = 'default'; } if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) { $key = $this->blog_prefix . $key; } if ( is_object( $data ) ) { $data = clone $data; } $this->cache[ $group ][ $key ] = $data; return true; } /** * Sets multiple values to the cache in one call. * * @since 6.0.0 * * @param array $data Array of key and value to be set. * @param string $group Optional. Where the cache contents are grouped. Default empty. * @param int $expire Optional. When to expire the cache contents, in seconds. * Default 0 (no expiration). * @return bool[] Array of return values, grouped by key. Each value is always true. */ public function set_multiple( array $data, $group = '', $expire = 0 ) { $values = array(); foreach ( $data as $key => $value ) { $values[ $key ] = $this->set( $key, $value, $group, $expire ); } return $values; } /** * Retrieves the cache contents, if it exists. * * The contents will be first attempted to be retrieved by searching by the * key in the cache group. If the cache is hit (success) then the contents * are returned. * * On failure, the number of cache misses will be incremented. * * @since 2.0.0 * * @param int|string $key The key under which the cache contents are stored. * @param string $group Optional. Where the cache contents are grouped. Default 'default'. * @param bool $force Optional. Unused. Whether to force an update of the local cache * from the persistent cache. Default false. * @param bool $found Optional. Whether the key was found in the cache (passed by reference). * Disambiguates a return of false, a storable value. Default null. * @return mixed|false The cache contents on success, false on failure to retrieve contents. */ public function get( $key, $group = 'default', $force = false, &$found = null ) { if ( ! $this->is_valid_key( $key ) ) { return false; } if ( empty( $group ) ) { $group = 'default'; } if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) { $key = $this->blog_prefix . $key; } if ( $this->_exists( $key, $group ) ) { $found = true; $this->cache_hits += 1; if ( is_object( $this->cache[ $group ][ $key ] ) ) { return clone $this->cache[ $group ][ $key ]; } else { return $this->cache[ $group ][ $key ]; } } $found = false; $this->cache_misses += 1; return false; } /** * Retrieves multiple values from the cache in one call. * * @since 5.5.0 * * @param array $keys Array of keys under which the cache contents are stored. * @param string $group Optional. Where the cache contents are grouped. Default 'default'. * @param bool $force Optional. Whether to force an update of the local cache * from the persistent cache. Default false. * @return array Array of return values, grouped by key. Each value is either * the cache contents on success, or false on failure. */ public function get_multiple( $keys, $group = 'default', $force = false ) { $values = array(); foreach ( $keys as $key ) { $values[ $key ] = $this->get( $key, $group, $force ); } return $values; } /** * Removes the contents of the cache key in the group. * * If the cache key does not exist in the group, then nothing will happen. * * @since 2.0.0 * * @param int|string $key What the contents in the cache are called. * @param string $group Optional. Where the cache contents are grouped. Default 'default'. * @param bool $deprecated Optional. Unused. Default false. * @return bool True on success, false if the contents were not deleted. */ public function delete( $key, $group = 'default', $deprecated = false ) { if ( ! $this->is_valid_key( $key ) ) { return false; } if ( empty( $group ) ) { $group = 'default'; } if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) { $key = $this->blog_prefix . $key; } if ( ! $this->_exists( $key, $group ) ) { return false; } unset( $this->cache[ $group ][ $key ] ); return true; } /** * Deletes multiple values from the cache in one call. * * @since 6.0.0 * * @param array $keys Array of keys to be deleted. * @param string $group Optional. Where the cache contents are grouped. Default empty. * @return bool[] Array of return values, grouped by key. Each value is either * true on success, or false if the contents were not deleted. */ public function delete_multiple( array $keys, $group = '' ) { $values = array(); foreach ( $keys as $key ) { $values[ $key ] = $this->delete( $key, $group ); } return $values; } /** * Increments numeric cache item's value. * * @since 3.3.0 * * @param int|string $key The cache key to increment. * @param int $offset Optional. The amount by which to increment the item's value. * Default 1. * @param string $group Optional. The group the key is in. Default 'default'. * @return int|false The item's new value on success, false on failure. */ public function incr( $key, $offset = 1, $group = 'default' ) { if ( ! $this->is_valid_key( $key ) ) { return false; } if ( empty( $group ) ) { $group = 'default'; } if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) { $key = $this->blog_prefix . $key; } if ( ! $this->_exists( $key, $group ) ) { return false; } if ( ! is_numeric( $this->cache[ $group ][ $key ] ) ) { $this->cache[ $group ][ $key ] = 0; } $offset = (int) $offset; $this->cache[ $group ][ $key ] += $offset; if ( $this->cache[ $group ][ $key ] < 0 ) { $this->cache[ $group ][ $key ] = 0; } return $this->cache[ $group ][ $key ]; } /** * Decrements numeric cache item's value. * * @since 3.3.0 * * @param int|string $key The cache key to decrement. * @param int $offset Optional. The amount by which to decrement the item's value. * Default 1. * @param string $group Optional. The group the key is in. Default 'default'. * @return int|false The item's new value on success, false on failure. */ public function decr( $key, $offset = 1, $group = 'default' ) { if ( ! $this->is_valid_key( $key ) ) { return false; } if ( empty( $group ) ) { $group = 'default'; } if ( $this->multisite && ! isset( $this->global_groups[ $group ] ) ) { $key = $this->blog_prefix . $key; } if ( ! $this->_exists( $key, $group ) ) { return false; } if ( ! is_numeric( $this->cache[ $group ][ $key ] ) ) { $this->cache[ $group ][ $key ] = 0; } $offset = (int) $offset; $this->cache[ $group ][ $key ] -= $offset; if ( $this->cache[ $group ][ $key ] < 0 ) { $this->cache[ $group ][ $key ] = 0; } return $this->cache[ $group ][ $key ]; } /** * Clears the object cache of all data. * * @since 2.0.0 * * @return true Always returns true. */ public function flush() { $this->cache = array(); return true; } /** * Removes all cache items in a group. * * @since 6.1.0 * * @param string $group Name of group to remove from cache. * @return true Always returns true. */ public function flush_group( $group ) { unset( $this->cache[ $group ] ); return true; } /** * Sets the list of global cache groups. * * @since 3.0.0 * * @param string|string[] $groups List of groups that are global. */ public function add_global_groups( $groups ) { $groups = (array) $groups; $groups = array_fill_keys( $groups, true ); $this->global_groups = array_merge( $this->global_groups, $groups ); } /** * Switches the internal blog ID. * * This changes the blog ID used to create keys in blog specific groups. * * @since 3.5.0 * * @param int $blog_id Blog ID. */ public function switch_to_blog( $blog_id ) { $blog_id = (int) $blog_id; $this->blog_prefix = $this->multisite ? $blog_id . ':' : ''; } /** * Resets cache keys. * * @since 3.0.0 * * @deprecated 3.5.0 Use WP_Object_Cache::switch_to_blog() * @see switch_to_blog() */ public function reset() { _deprecated_function( __FUNCTION__, '3.5.0', 'WP_Object_Cache::switch_to_blog()' ); // Clear out non-global caches since the blog ID has changed. foreach ( array_keys( $this->cache ) as $group ) { if ( ! isset( $this->global_groups[ $group ] ) ) { unset( $this->cache[ $group ] ); } } } /** * Echoes the stats of the caching. * * Gives the cache hits, and cache misses. Also prints every cached group, * key and the data. * * @since 2.0.0 */ public function stats() { echo '<p>'; echo "<strong>Cache Hits:</strong> {$this->cache_hits}<br />"; echo "<strong>Cache Misses:</strong> {$this->cache_misses}<br />"; echo '</p>'; echo '<ul>'; foreach ( $this->cache as $group => $cache ) { echo '<li><strong>Group:</strong> ' . esc_html( $group ) . ' - ( ' . number_format( strlen( serialize( $cache ) ) / KB_IN_BYTES, 2 ) . 'k )</li>'; } echo '</ul>'; } } ``` | Version | Description | | --- | --- | | [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
programming_docs
wordpress class WP_Scripts {} class WP\_Scripts {} ==================== Core class used to register scripts. * [WP\_Dependencies](wp_dependencies) * [\_\_construct](wp_scripts/__construct) β€” Constructor. * [add\_inline\_script](wp_scripts/add_inline_script) β€” Adds extra code to a registered script. * [all\_deps](wp_scripts/all_deps) β€” Determines script dependencies. * [do\_footer\_items](wp_scripts/do_footer_items) β€” Processes items and dependencies for the footer group. * [do\_head\_items](wp_scripts/do_head_items) β€” Processes items and dependencies for the head group. * [do\_item](wp_scripts/do_item) β€” Processes a script dependency. * [in\_default\_dir](wp_scripts/in_default_dir) β€” Whether a handle's source is in a default directory. * [init](wp_scripts/init) β€” Initialize the class. * [localize](wp_scripts/localize) β€” Localizes a script, only if the script has already been added. * [print\_extra\_script](wp_scripts/print_extra_script) β€” Prints extra scripts of a registered script. * [print\_inline\_script](wp_scripts/print_inline_script) β€” Prints inline scripts registered for a specific handle. * [print\_scripts](wp_scripts/print_scripts) β€” Prints scripts. * [print\_scripts\_l10n](wp_scripts/print_scripts_l10n) β€” Prints extra scripts of a registered script. β€” deprecated * [print\_translations](wp_scripts/print_translations) β€” Prints translations set for a specific handle. * [reset](wp_scripts/reset) β€” Resets class properties. * [set\_group](wp_scripts/set_group) β€” Sets handle group. * [set\_translations](wp_scripts/set_translations) β€” Sets a translation textdomain. File: `wp-includes/class-wp-scripts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-scripts-php-2/) ``` class WP_Scripts extends WP_Dependencies { /** * Base URL for scripts. * * Full URL with trailing slash. * * @since 2.6.0 * @var string */ public $base_url; /** * URL of the content directory. * * @since 2.8.0 * @var string */ public $content_url; /** * Default version string for scripts. * * @since 2.6.0 * @var string */ public $default_version; /** * Holds handles of scripts which are enqueued in footer. * * @since 2.8.0 * @var array */ public $in_footer = array(); /** * Holds a list of script handles which will be concatenated. * * @since 2.8.0 * @var string */ public $concat = ''; /** * Holds a string which contains script handles and their version. * * @since 2.8.0 * @deprecated 3.4.0 * @var string */ public $concat_version = ''; /** * Whether to perform concatenation. * * @since 2.8.0 * @var bool */ public $do_concat = false; /** * Holds HTML markup of scripts and additional data if concatenation * is enabled. * * @since 2.8.0 * @var string */ public $print_html = ''; /** * Holds inline code if concatenation is enabled. * * @since 2.8.0 * @var string */ public $print_code = ''; /** * Holds a list of script handles which are not in the default directory * if concatenation is enabled. * * Unused in core. * * @since 2.8.0 * @var string */ public $ext_handles = ''; /** * Holds a string which contains handles and versions of scripts which * are not in the default directory if concatenation is enabled. * * Unused in core. * * @since 2.8.0 * @var string */ public $ext_version = ''; /** * List of default directories. * * @since 2.8.0 * @var array */ public $default_dirs; /** * Holds a string which contains the type attribute for script tag. * * If the active theme does not declare HTML5 support for 'script', * then it initializes as `type='text/javascript'`. * * @since 5.3.0 * @var string */ private $type_attr = ''; /** * Constructor. * * @since 2.6.0 */ public function __construct() { $this->init(); add_action( 'init', array( $this, 'init' ), 0 ); } /** * Initialize the class. * * @since 3.4.0 */ 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 ) ); } /** * Prints scripts. * * Prints the scripts passed to it or the print queue. Also prints all necessary dependencies. * * @since 2.1.0 * @since 2.8.0 Added the `$group` parameter. * * @param string|string[]|false $handles Optional. Scripts to be printed: queue (false), * single script (string), or multiple scripts (array of strings). * Default false. * @param int|false $group Optional. Group level: level (int), no groups (false). * Default false. * @return string[] Handles of scripts that have been printed. */ public function print_scripts( $handles = false, $group = false ) { return $this->do_items( $handles, $group ); } /** * Prints extra scripts of a registered script. * * @since 2.1.0 * @since 2.8.0 Added the `$display` parameter. * @deprecated 3.3.0 * * @see print_extra_script() * * @param string $handle The script's registered handle. * @param bool $display Optional. Whether to print the extra script * instead of just returning it. Default true. * @return bool|string|void Void if no data exists, extra scripts if `$display` is true, * true otherwise. */ 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 ); } /** * Prints extra scripts of a registered script. * * @since 3.3.0 * * @param string $handle The script's registered handle. * @param bool $display Optional. Whether to print the extra script * instead of just returning it. Default true. * @return bool|string|void Void if no data exists, extra scripts if `$display` is true, * true otherwise. */ 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; } /** * Processes a script dependency. * * @since 2.6.0 * @since 2.8.0 Added the `$group` parameter. * * @see WP_Dependencies::do_item() * * @param string $handle The script's registered handle. * @param int|false $group Optional. Group level: level (int), no groups (false). * Default false. * @return bool True on success, false on failure. */ 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 . '&amp;' . $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; } /** * Adds extra code to a registered script. * * @since 4.5.0 * * @param string $handle Name of the script to add the inline script to. * Must be lowercase. * @param string $data String containing the JavaScript to be added. * @param string $position Optional. Whether to add the inline script * before the handle or after. Default 'after'. * @return bool True on success, false on failure. */ 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 ); } /** * Prints inline scripts registered for a specific handle. * * @since 4.5.0 * * @param string $handle Name of the script to add the inline script to. * Must be lowercase. * @param string $position Optional. Whether to add the inline script * before the handle or after. Default 'after'. * @param bool $display Optional. Whether to print the script * instead of just returning it. Default true. * @return string|false Script on success, false otherwise. */ 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; } /** * Localizes a script, only if the script has already been added. * * @since 2.1.0 * * @param string $handle Name of the script to attach data to. * @param string $object_name Name of the variable that will contain the data. * @param array $l10n Array of data to localize. * @return bool True on success, false on failure. */ 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 ); } /** * Sets handle group. * * @since 2.8.0 * * @see WP_Dependencies::set_group() * * @param string $handle Name of the item. Should be unique. * @param bool $recursion Internal flag that calling function was called recursively. * @param int|false $group Optional. Group level: level (int), no groups (false). * Default false. * @return bool Not already in the group or a lower group. */ 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 ); } /** * Sets a translation textdomain. * * @since 5.0.0 * @since 5.1.0 The `$domain` parameter was made optional. * * @param string $handle Name of the script to register a translation domain to. * @param string $domain Optional. Text domain. Default 'default'. * @param string $path Optional. The full file path to the directory containing translation files. * @return bool True if the text domain was registered, false if not. */ 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 ); } /** * Prints translations set for a specific handle. * * @since 5.0.0 * * @param string $handle Name of the script to add the inline script to. * Must be lowercase. * @param bool $display Optional. Whether to print the script * instead of just returning it. Default true. * @return string|false Script on success, false otherwise. */ 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; } /** * Determines script dependencies. * * @since 2.1.0 * * @see WP_Dependencies::all_deps() * * @param string|string[] $handles Item handle (string) or item handles (array of strings). * @param bool $recursion Optional. Internal flag that function is calling itself. * Default false. * @param int|false $group Optional. Group level: level (int), no groups (false). * Default false. * @return bool True on success, false on failure. */ 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; } /** * Processes items and dependencies for the head group. * * @since 2.8.0 * * @see WP_Dependencies::do_items() * * @return string[] Handles of items that have been processed. */ public function do_head_items() { $this->do_items( false, 0 ); return $this->done; } /** * Processes items and dependencies for the footer group. * * @since 2.8.0 * * @see WP_Dependencies::do_items() * * @return string[] Handles of items that have been processed. */ public function do_footer_items() { $this->do_items( false, 1 ); return $this->done; } /** * Whether a handle's source is in a default directory. * * @since 2.8.0 * * @param string $src The source of the enqueued script. * @return bool True if found, false if not. */ 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; } /** * Resets class properties. * * @since 2.8.0 */ public function reset() { $this->do_concat = false; $this->print_code = ''; $this->concat = ''; $this->concat_version = ''; $this->print_html = ''; $this->ext_version = ''; $this->ext_handles = ''; } } ``` | Uses | Description | | --- | --- | | [WP\_Dependencies](wp_dependencies) wp-includes/class-wp-dependencies.php | Core base class extended to register items. | | Version | Description | | --- | --- | | [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
programming_docs
wordpress class Bulk_Upgrader_Skin {} class Bulk\_Upgrader\_Skin {} ============================= Generic Bulk Upgrader Skin for WordPress Upgrades. * [WP\_Upgrader\_Skin](wp_upgrader_skin) * [\_\_construct](bulk_upgrader_skin/__construct) * [add\_strings](bulk_upgrader_skin/add_strings) * [after](bulk_upgrader_skin/after) * [before](bulk_upgrader_skin/before) * [bulk\_footer](bulk_upgrader_skin/bulk_footer) * [bulk\_header](bulk_upgrader_skin/bulk_header) * [error](bulk_upgrader_skin/error) * [feedback](bulk_upgrader_skin/feedback) * [flush\_output](bulk_upgrader_skin/flush_output) * [footer](bulk_upgrader_skin/footer) * [header](bulk_upgrader_skin/header) * [reset](bulk_upgrader_skin/reset) File: `wp-admin/includes/class-bulk-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-bulk-upgrader-skin.php/) ``` class Bulk_Upgrader_Skin extends WP_Upgrader_Skin { public $in_loop = false; /** * @var string|false */ public $error = false; /** * @param array $args */ public function __construct( $args = array() ) { $defaults = array( 'url' => '', 'nonce' => '', ); $args = wp_parse_args( $args, $defaults ); parent::__construct( $args ); } /** */ public function add_strings() { $this->upgrader->strings['skin_upgrade_start'] = __( 'The update process is starting. This process may take a while on some hosts, so please be patient.' ); /* translators: 1: Title of an update, 2: Error message. */ $this->upgrader->strings['skin_update_failed_error'] = __( 'An error occurred while updating %1$s: %2$s' ); /* translators: %s: Title of an update. */ $this->upgrader->strings['skin_update_failed'] = __( 'The update of %s failed.' ); /* translators: %s: Title of an update. */ $this->upgrader->strings['skin_update_successful'] = __( '%s updated successfully.' ); $this->upgrader->strings['skin_upgrade_end'] = __( 'All updates have been completed.' ); } /** * @since 5.9.0 Renamed `$string` (a PHP reserved keyword) to `$feedback` for PHP 8 named parameter support. * * @param string $feedback Message data. * @param mixed ...$args Optional text replacements. */ public function feedback( $feedback, ...$args ) { if ( isset( $this->upgrader->strings[ $feedback ] ) ) { $feedback = $this->upgrader->strings[ $feedback ]; } if ( strpos( $feedback, '%' ) !== false ) { if ( $args ) { $args = array_map( 'strip_tags', $args ); $args = array_map( 'esc_html', $args ); $feedback = vsprintf( $feedback, $args ); } } if ( empty( $feedback ) ) { return; } if ( $this->in_loop ) { echo "$feedback<br />\n"; } else { echo "<p>$feedback</p>\n"; } } /** */ public function header() { // Nothing, This will be displayed within a iframe. } /** */ public function footer() { // Nothing, This will be displayed within a iframe. } /** * @since 5.9.0 Renamed `$error` to `$errors` for PHP 8 named parameter support. * * @param string|WP_Error $errors Errors. */ public function error( $errors ) { if ( is_string( $errors ) && isset( $this->upgrader->strings[ $errors ] ) ) { $this->error = $this->upgrader->strings[ $errors ]; } if ( is_wp_error( $errors ) ) { $messages = array(); foreach ( $errors->get_error_messages() as $emessage ) { if ( $errors->get_error_data() && is_string( $errors->get_error_data() ) ) { $messages[] = $emessage . ' ' . esc_html( strip_tags( $errors->get_error_data() ) ); } else { $messages[] = $emessage; } } $this->error = implode( ', ', $messages ); } echo '<script type="text/javascript">jQuery(\'.waiting-' . esc_js( $this->upgrader->update_current ) . '\').hide();</script>'; } /** */ public function bulk_header() { $this->feedback( 'skin_upgrade_start' ); } /** */ public function bulk_footer() { $this->feedback( 'skin_upgrade_end' ); } /** * @param string $title */ public function before( $title = '' ) { $this->in_loop = true; printf( '<h2>' . $this->upgrader->strings['skin_before_update_header'] . ' <span class="spinner waiting-' . $this->upgrader->update_current . '"></span></h2>', $title, $this->upgrader->update_current, $this->upgrader->update_count ); echo '<script type="text/javascript">jQuery(\'.waiting-' . esc_js( $this->upgrader->update_current ) . '\').css("display", "inline-block");</script>'; // This progress messages div gets moved via JavaScript when clicking on "Show details.". echo '<div class="update-messages hide-if-js" id="progress-' . esc_attr( $this->upgrader->update_current ) . '"><p>'; $this->flush_output(); } /** * @param string $title */ public function after( $title = '' ) { echo '</p></div>'; if ( $this->error || ! $this->result ) { if ( $this->error ) { echo '<div class="error"><p>' . sprintf( $this->upgrader->strings['skin_update_failed_error'], $title, '<strong>' . $this->error . '</strong>' ) . '</p></div>'; } else { echo '<div class="error"><p>' . sprintf( $this->upgrader->strings['skin_update_failed'], $title ) . '</p></div>'; } echo '<script type="text/javascript">jQuery(\'#progress-' . esc_js( $this->upgrader->update_current ) . '\').show();</script>'; } if ( $this->result && ! is_wp_error( $this->result ) ) { if ( ! $this->error ) { echo '<div class="updated js-update-details" data-update-details="progress-' . esc_attr( $this->upgrader->update_current ) . '">' . '<p>' . sprintf( $this->upgrader->strings['skin_update_successful'], $title ) . ' <button type="button" class="hide-if-no-js button-link js-update-details-toggle" aria-expanded="false">' . __( 'Show details.' ) . '</button>' . '</p></div>'; } echo '<script type="text/javascript">jQuery(\'.waiting-' . esc_js( $this->upgrader->update_current ) . '\').hide();</script>'; } $this->reset(); $this->flush_output(); } /** */ public function reset() { $this->in_loop = false; $this->error = false; } /** */ public function flush_output() { wp_ob_end_flush_all(); flush(); } } ``` | Uses | Description | | --- | --- | | [WP\_Upgrader\_Skin](wp_upgrader_skin) wp-admin/includes/class-wp-upgrader-skin.php | Generic Skin for the WordPress Upgrader classes. This skin is designed to be extended for specific purposes. | | Used By | Description | | --- | --- | | [Bulk\_Plugin\_Upgrader\_Skin](bulk_plugin_upgrader_skin) wp-admin/includes/class-bulk-plugin-upgrader-skin.php | Bulk Plugin Upgrader Skin for WordPress Plugin Upgrades. | | [Bulk\_Theme\_Upgrader\_Skin](bulk_theme_upgrader_skin) wp-admin/includes/class-bulk-theme-upgrader-skin.php | Bulk Theme Upgrader Skin for WordPress Theme Upgrades. | | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php. | | [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. | wordpress class WP_Meta_Query {} class WP\_Meta\_Query {} ======================== Core class used to implement meta queries for the Meta API. Used for generating SQL clauses that filter a primary query according to metadata keys and values. [WP\_Meta\_Query](wp_meta_query) is a helper that allows primary query classes, such as [WP\_Query](wp_query) and [WP\_User\_Query](wp_user_query), to filter their results by object metadata, by generating `JOIN` and `WHERE` subclauses to be attached to the primary SQL query string. [WP\_Meta\_Query](wp_meta_query) is a class defined in wp-includes/meta.php that generates the necessary SQL for meta-related queries. It was introduced in Version 3.2.0 and greatly improved the possibility to query posts by custom fields. In the WP core, it’s used in the [WP\_Query](wp_query "Class Reference/WP Query") and [WP\_User\_Query](wp_user_query "Class Reference/WP User Query") classes, and since Version 3.5 in the [WP\_Comment\_Query](wp_comment_query "Class Reference/WP Comment Query") class. Unless you’re writing a custom SQL query, you should look in the \*Custom Field Parameters\* section for the corresponding class. The following arguments can be passed in a key=>value paired array. * **meta\_key** (*string*) – Custom field key. ( You must sanitize this yourself ) * **meta\_value** (*string|array*) – Custom field value. ( You must sanitize this yourself ) * **meta\_type** (*string*) – Custom field type (see **type** below for options). * **meta\_compare** (*string*) – Operator to test the 'meta\_value' (see **compare** below for possible values). * **meta\_query** (*array*) – Contains one or more arrays with the following keys: + **key** (*string*) – Custom field key. + **value** (*string*|*array*) – Custom field value. It can be an array only when **compare** is 'IN', 'NOT IN', 'BETWEEN', or 'NOT BETWEEN'. You don’t have to specify a value when using the 'EXISTS' or 'NOT EXISTS' comparisons in WordPress 3.9 and up. (**Note:** Due to [bug #23268](https://core.trac.wordpress.org/ticket/23268), value was required for NOT EXISTS comparisons to work correctly prior to 3.9. You had to supply *some* string for the value parameter. An empty string or NULL will NOT work. However, any other string will do the trick and will NOT show up in your SQL when using NOT EXISTS. Need inspiration? How about 'bug #23268'.) + **compare** (*string*) – Operator to test. Possible values are β€˜=’, β€˜!=’, β€˜>’, β€˜>=’, β€˜<β€˜, β€˜<=’, β€˜LIKE’, β€˜NOT LIKE’, β€˜IN’, β€˜NOT IN’, β€˜BETWEEN’, β€˜NOT BETWEEN’, β€˜EXISTS’ (only in WP >= 3.5), and β€˜NOT EXISTS’ (also only in WP >= 3.5). Values β€˜REGEXP’, β€˜NOT REGEXP’ and β€˜RLIKE’ were added in WordPress 3.7. Default value is β€˜=’. + **type** (*string*) – Custom field type. Possible values are β€˜NUMERIC’, β€˜BINARY’, β€˜CHAR’, β€˜DATE’, β€˜DATETIME’, β€˜DECIMAL’, β€˜SIGNED’, β€˜TIME’, β€˜UNSIGNED’. Default value is β€˜CHAR’. The 'type' DATE works with the 'compare' value BETWEEN only if the date is stored at the format YYYY-MM-DD and tested with this format. *Note:* The 'meta\_key', 'meta\_value', 'meta\_type' and 'meta\_compare' arguments will only work if you use the second method described below. * [\_\_construct](wp_meta_query/__construct) β€” Constructor. * [find\_compatible\_table\_alias](wp_meta_query/find_compatible_table_alias) β€” Identify an existing table alias that is compatible with the current query clause. * [get\_cast\_for\_type](wp_meta_query/get_cast_for_type) β€” Return the appropriate alias for the given meta type if applicable. * [get\_clauses](wp_meta_query/get_clauses) β€” Get a flattened list of sanitized meta clauses. * [get\_sql](wp_meta_query/get_sql) β€” Generates SQL clauses to be appended to a main query. * [get\_sql\_clauses](wp_meta_query/get_sql_clauses) β€” Generate SQL clauses to be appended to a main query. * [get\_sql\_for\_clause](wp_meta_query/get_sql_for_clause) β€” Generate SQL JOIN and WHERE clauses for a first-order query clause. * [get\_sql\_for\_query](wp_meta_query/get_sql_for_query) β€” Generate SQL clauses for a single query array. * [has\_or\_relation](wp_meta_query/has_or_relation) β€” Checks whether the current query has any OR relations. * [is\_first\_order\_clause](wp_meta_query/is_first_order_clause) β€” Determine whether a query clause is first-order. * [parse\_query\_vars](wp_meta_query/parse_query_vars) β€” Constructs a meta query based on 'meta\_\*' query vars * [sanitize\_query](wp_meta_query/sanitize_query) β€” Ensure the 'meta\_query' argument passed to the class constructor is well-formed. File: `wp-includes/class-wp-meta-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-meta-query.php/) ``` class WP_Meta_Query { /** * Array of metadata queries. * * See WP_Meta_Query::__construct() for information on meta query arguments. * * @since 3.2.0 * @var array */ public $queries = array(); /** * The relation between the queries. Can be one of 'AND' or 'OR'. * * @since 3.2.0 * @var string */ public $relation; /** * Database table to query for the metadata. * * @since 4.1.0 * @var string */ public $meta_table; /** * Column in meta_table that represents the ID of the object the metadata belongs to. * * @since 4.1.0 * @var string */ public $meta_id_column; /** * Database table that where the metadata's objects are stored (eg $wpdb->users). * * @since 4.1.0 * @var string */ public $primary_table; /** * Column in primary_table that represents the ID of the object. * * @since 4.1.0 * @var string */ public $primary_id_column; /** * A flat list of table aliases used in JOIN clauses. * * @since 4.1.0 * @var array */ protected $table_aliases = array(); /** * A flat list of clauses, keyed by clause 'name'. * * @since 4.2.0 * @var array */ protected $clauses = array(); /** * Whether the query contains any OR relations. * * @since 4.3.0 * @var bool */ protected $has_or_relation = false; /** * Constructor. * * @since 3.2.0 * @since 4.2.0 Introduced support for naming query clauses by associative array keys. * @since 5.1.0 Introduced `$compare_key` clause parameter, which enables LIKE key matches. * @since 5.3.0 Increased the number of operators available to `$compare_key`. Introduced `$type_key`, * which enables the `$key` to be cast to a new data type for comparisons. * * @param array $meta_query { * Array of meta query clauses. When first-order clauses or sub-clauses use strings as * their array keys, they may be referenced in the 'orderby' parameter of the parent query. * * @type string $relation Optional. The MySQL keyword used to join the clauses of the query. * Accepts 'AND' or 'OR'. Default 'AND'. * @type array ...$0 { * Optional. An array of first-order clause parameters, or another fully-formed meta query. * * @type string|string[] $key Meta key or keys to filter by. * @type string $compare_key MySQL operator used for comparing the $key. Accepts: * - '=' * - '!=' * - 'LIKE' * - 'NOT LIKE' * - 'IN' * - 'NOT IN' * - 'REGEXP' * - 'NOT REGEXP' * - 'RLIKE', * - 'EXISTS' (alias of '=') * - 'NOT EXISTS' (alias of '!=') * Default is 'IN' when `$key` is an array, '=' otherwise. * @type string $type_key MySQL data type that the meta_key column will be CAST to for * comparisons. Accepts 'BINARY' for case-sensitive regular expression * comparisons. Default is ''. * @type string|string[] $value Meta value or values to filter by. * @type string $compare MySQL operator used for comparing the $value. Accepts: * - '=', * - '!=' * - '>' * - '>=' * - '<' * - '<=' * - 'LIKE' * - 'NOT LIKE' * - 'IN' * - 'NOT IN' * - 'BETWEEN' * - 'NOT BETWEEN' * - 'REGEXP' * - 'NOT REGEXP' * - 'RLIKE' * - 'EXISTS' * - 'NOT EXISTS' * Default is 'IN' when `$value` is an array, '=' otherwise. * @type string $type MySQL data type that the meta_value column will be CAST to for * comparisons. Accepts: * - 'NUMERIC' * - 'BINARY' * - 'CHAR' * - 'DATE' * - 'DATETIME' * - 'DECIMAL' * - 'SIGNED' * - 'TIME' * - 'UNSIGNED' * Default is 'CHAR'. * } * } */ public function __construct( $meta_query = false ) { if ( ! $meta_query ) { return; } if ( isset( $meta_query['relation'] ) && 'OR' === strtoupper( $meta_query['relation'] ) ) { $this->relation = 'OR'; } else { $this->relation = 'AND'; } $this->queries = $this->sanitize_query( $meta_query ); } /** * Ensure the 'meta_query' argument passed to the class constructor is well-formed. * * Eliminates empty items and ensures that a 'relation' is set. * * @since 4.1.0 * * @param array $queries Array of query clauses. * @return array Sanitized array of query clauses. */ public function sanitize_query( $queries ) { $clean_queries = array(); if ( ! is_array( $queries ) ) { return $clean_queries; } foreach ( $queries as $key => $query ) { if ( 'relation' === $key ) { $relation = $query; } elseif ( ! is_array( $query ) ) { continue; // First-order clause. } elseif ( $this->is_first_order_clause( $query ) ) { if ( isset( $query['value'] ) && array() === $query['value'] ) { unset( $query['value'] ); } $clean_queries[ $key ] = $query; // Otherwise, it's a nested query, so we recurse. } else { $cleaned_query = $this->sanitize_query( $query ); if ( ! empty( $cleaned_query ) ) { $clean_queries[ $key ] = $cleaned_query; } } } if ( empty( $clean_queries ) ) { return $clean_queries; } // Sanitize the 'relation' key provided in the query. if ( isset( $relation ) && 'OR' === strtoupper( $relation ) ) { $clean_queries['relation'] = 'OR'; $this->has_or_relation = true; /* * If there is only a single clause, call the relation 'OR'. * This value will not actually be used to join clauses, but it * simplifies the logic around combining key-only queries. */ } elseif ( 1 === count( $clean_queries ) ) { $clean_queries['relation'] = 'OR'; // Default to AND. } else { $clean_queries['relation'] = 'AND'; } return $clean_queries; } /** * Determine whether a query clause is first-order. * * A first-order meta query clause is one that has either a 'key' or * a 'value' array key. * * @since 4.1.0 * * @param array $query Meta query arguments. * @return bool Whether the query clause is a first-order clause. */ protected function is_first_order_clause( $query ) { return isset( $query['key'] ) || isset( $query['value'] ); } /** * Constructs a meta query based on 'meta_*' query vars * * @since 3.2.0 * * @param array $qv The query variables */ public function parse_query_vars( $qv ) { $meta_query = array(); /* * For orderby=meta_value to work correctly, simple query needs to be * first (so that its table join is against an unaliased meta table) and * needs to be its own clause (so it doesn't interfere with the logic of * the rest of the meta_query). */ $primary_meta_query = array(); foreach ( array( 'key', 'compare', 'type', 'compare_key', 'type_key' ) as $key ) { if ( ! empty( $qv[ "meta_$key" ] ) ) { $primary_meta_query[ $key ] = $qv[ "meta_$key" ]; } } // WP_Query sets 'meta_value' = '' by default. if ( isset( $qv['meta_value'] ) && '' !== $qv['meta_value'] && ( ! is_array( $qv['meta_value'] ) || $qv['meta_value'] ) ) { $primary_meta_query['value'] = $qv['meta_value']; } $existing_meta_query = isset( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ? $qv['meta_query'] : array(); if ( ! empty( $primary_meta_query ) && ! empty( $existing_meta_query ) ) { $meta_query = array( 'relation' => 'AND', $primary_meta_query, $existing_meta_query, ); } elseif ( ! empty( $primary_meta_query ) ) { $meta_query = array( $primary_meta_query, ); } elseif ( ! empty( $existing_meta_query ) ) { $meta_query = $existing_meta_query; } $this->__construct( $meta_query ); } /** * Return the appropriate alias for the given meta type if applicable. * * @since 3.7.0 * * @param string $type MySQL type to cast meta_value. * @return string MySQL type. */ public function get_cast_for_type( $type = '' ) { if ( empty( $type ) ) { return 'CHAR'; } $meta_type = strtoupper( $type ); if ( ! preg_match( '/^(?:BINARY|CHAR|DATE|DATETIME|SIGNED|UNSIGNED|TIME|NUMERIC(?:\(\d+(?:,\s?\d+)?\))?|DECIMAL(?:\(\d+(?:,\s?\d+)?\))?)$/', $meta_type ) ) { return 'CHAR'; } if ( 'NUMERIC' === $meta_type ) { $meta_type = 'SIGNED'; } return $meta_type; } /** * Generates SQL clauses to be appended to a main query. * * @since 3.2.0 * * @param string $type Type of meta. Possible values include but are not limited * to 'post', 'comment', 'blog', 'term', and 'user'. * @param string $primary_table Database table where the object being filtered is stored (eg wp_users). * @param string $primary_id_column ID column for the filtered object in $primary_table. * @param object $context Optional. The main query object that corresponds to the type, for * example a `WP_Query`, `WP_User_Query`, or `WP_Site_Query`. * @return string[]|false { * Array containing JOIN and WHERE SQL clauses to append to the main query, * or false if no table exists for the requested meta type. * * @type string $join SQL fragment to append to the main JOIN clause. * @type string $where SQL fragment to append to the main WHERE clause. * } */ public function get_sql( $type, $primary_table, $primary_id_column, $context = null ) { $meta_table = _get_meta_table( $type ); if ( ! $meta_table ) { return false; } $this->table_aliases = array(); $this->meta_table = $meta_table; $this->meta_id_column = sanitize_key( $type . '_id' ); $this->primary_table = $primary_table; $this->primary_id_column = $primary_id_column; $sql = $this->get_sql_clauses(); /* * If any JOINs are LEFT JOINs (as in the case of NOT EXISTS), then all JOINs should * be LEFT. Otherwise posts with no metadata will be excluded from results. */ if ( false !== strpos( $sql['join'], 'LEFT JOIN' ) ) { $sql['join'] = str_replace( 'INNER JOIN', 'LEFT JOIN', $sql['join'] ); } /** * Filters the meta query's generated SQL. * * @since 3.1.0 * * @param string[] $sql Array containing the query's JOIN and WHERE clauses. * @param array $queries Array of meta queries. * @param string $type Type of meta. Possible values include but are not limited * to 'post', 'comment', 'blog', 'term', and 'user'. * @param string $primary_table Primary table. * @param string $primary_id_column Primary column ID. * @param object $context The main query object that corresponds to the type, for * example a `WP_Query`, `WP_User_Query`, or `WP_Site_Query`. */ return apply_filters_ref_array( 'get_meta_sql', array( $sql, $this->queries, $type, $primary_table, $primary_id_column, $context ) ); } /** * Generate SQL clauses to be appended to a main query. * * Called by the public WP_Meta_Query::get_sql(), this method is abstracted * out to maintain parity with the other Query classes. * * @since 4.1.0 * * @return string[] { * Array containing JOIN and WHERE SQL clauses to append to the main query. * * @type string $join SQL fragment to append to the main JOIN clause. * @type string $where SQL fragment to append to the main WHERE clause. * } */ protected function get_sql_clauses() { /* * $queries are passed by reference to get_sql_for_query() for recursion. * To keep $this->queries unaltered, pass a copy. */ $queries = $this->queries; $sql = $this->get_sql_for_query( $queries ); if ( ! empty( $sql['where'] ) ) { $sql['where'] = ' AND ' . $sql['where']; } return $sql; } /** * Generate SQL clauses for a single query array. * * If nested subqueries are found, this method recurses the tree to * produce the properly nested SQL. * * @since 4.1.0 * * @param array $query Query to parse (passed by reference). * @param int $depth Optional. Number of tree levels deep we currently are. * Used to calculate indentation. Default 0. * @return string[] { * Array containing JOIN and WHERE SQL clauses to append to a single query array. * * @type string $join SQL fragment to append to the main JOIN clause. * @type string $where SQL fragment to append to the main WHERE clause. * } */ protected function get_sql_for_query( &$query, $depth = 0 ) { $sql_chunks = array( 'join' => array(), 'where' => array(), ); $sql = array( 'join' => '', 'where' => '', ); $indent = ''; for ( $i = 0; $i < $depth; $i++ ) { $indent .= ' '; } foreach ( $query as $key => &$clause ) { if ( 'relation' === $key ) { $relation = $query['relation']; } elseif ( is_array( $clause ) ) { // This is a first-order clause. if ( $this->is_first_order_clause( $clause ) ) { $clause_sql = $this->get_sql_for_clause( $clause, $query, $key ); $where_count = count( $clause_sql['where'] ); if ( ! $where_count ) { $sql_chunks['where'][] = ''; } elseif ( 1 === $where_count ) { $sql_chunks['where'][] = $clause_sql['where'][0]; } else { $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )'; } $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] ); // This is a subquery, so we recurse. } else { $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 ); $sql_chunks['where'][] = $clause_sql['where']; $sql_chunks['join'][] = $clause_sql['join']; } } } // Filter to remove empties. $sql_chunks['join'] = array_filter( $sql_chunks['join'] ); $sql_chunks['where'] = array_filter( $sql_chunks['where'] ); if ( empty( $relation ) ) { $relation = 'AND'; } // Filter duplicate JOIN clauses and combine into a single string. if ( ! empty( $sql_chunks['join'] ) ) { $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) ); } // Generate a single WHERE clause with proper brackets and indentation. if ( ! empty( $sql_chunks['where'] ) ) { $sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')'; } return $sql; } /** * Generate SQL JOIN and WHERE clauses for a first-order query clause. * * "First-order" means that it's an array with a 'key' or 'value'. * * @since 4.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param array $clause Query clause (passed by reference). * @param array $parent_query Parent query array. * @param string $clause_key Optional. The array key used to name the clause in the original `$meta_query` * parameters. If not provided, a key will be generated automatically. * @return string[] { * Array containing JOIN and WHERE SQL clauses to append to a first-order query. * * @type string $join SQL fragment to append to the main JOIN clause. * @type string $where SQL fragment to append to the main WHERE clause. * } */ public function get_sql_for_clause( &$clause, $parent_query, $clause_key = '' ) { global $wpdb; $sql_chunks = array( 'where' => array(), 'join' => array(), ); if ( isset( $clause['compare'] ) ) { $clause['compare'] = strtoupper( $clause['compare'] ); } else { $clause['compare'] = isset( $clause['value'] ) && is_array( $clause['value'] ) ? 'IN' : '='; } $non_numeric_operators = array( '=', '!=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'EXISTS', 'NOT EXISTS', 'RLIKE', 'REGEXP', 'NOT REGEXP', ); $numeric_operators = array( '>', '>=', '<', '<=', 'BETWEEN', 'NOT BETWEEN', ); if ( ! in_array( $clause['compare'], $non_numeric_operators, true ) && ! in_array( $clause['compare'], $numeric_operators, true ) ) { $clause['compare'] = '='; } if ( isset( $clause['compare_key'] ) ) { $clause['compare_key'] = strtoupper( $clause['compare_key'] ); } else { $clause['compare_key'] = isset( $clause['key'] ) && is_array( $clause['key'] ) ? 'IN' : '='; } if ( ! in_array( $clause['compare_key'], $non_numeric_operators, true ) ) { $clause['compare_key'] = '='; } $meta_compare = $clause['compare']; $meta_compare_key = $clause['compare_key']; // First build the JOIN clause, if one is required. $join = ''; // We prefer to avoid joins if possible. Look for an existing join compatible with this clause. $alias = $this->find_compatible_table_alias( $clause, $parent_query ); if ( false === $alias ) { $i = count( $this->table_aliases ); $alias = $i ? 'mt' . $i : $this->meta_table; // JOIN clauses for NOT EXISTS have their own syntax. if ( 'NOT EXISTS' === $meta_compare ) { $join .= " LEFT JOIN $this->meta_table"; $join .= $i ? " AS $alias" : ''; if ( 'LIKE' === $meta_compare_key ) { $join .= $wpdb->prepare( " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key LIKE %s )", '%' . $wpdb->esc_like( $clause['key'] ) . '%' ); } else { $join .= $wpdb->prepare( " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )", $clause['key'] ); } // All other JOIN clauses. } else { $join .= " INNER JOIN $this->meta_table"; $join .= $i ? " AS $alias" : ''; $join .= " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column )"; } $this->table_aliases[] = $alias; $sql_chunks['join'][] = $join; } // Save the alias to this clause, for future siblings to find. $clause['alias'] = $alias; // Determine the data type. $_meta_type = isset( $clause['type'] ) ? $clause['type'] : ''; $meta_type = $this->get_cast_for_type( $_meta_type ); $clause['cast'] = $meta_type; // Fallback for clause keys is the table alias. Key must be a string. if ( is_int( $clause_key ) || ! $clause_key ) { $clause_key = $clause['alias']; } // Ensure unique clause keys, so none are overwritten. $iterator = 1; $clause_key_base = $clause_key; while ( isset( $this->clauses[ $clause_key ] ) ) { $clause_key = $clause_key_base . '-' . $iterator; $iterator++; } // Store the clause in our flat array. $this->clauses[ $clause_key ] =& $clause; // Next, build the WHERE clause. // meta_key. if ( array_key_exists( 'key', $clause ) ) { if ( 'NOT EXISTS' === $meta_compare ) { $sql_chunks['where'][] = $alias . '.' . $this->meta_id_column . ' IS NULL'; } else { /** * In joined clauses negative operators have to be nested into a * NOT EXISTS clause and flipped, to avoid returning records with * matching post IDs but different meta keys. Here we prepare the * nested clause. */ if ( in_array( $meta_compare_key, array( '!=', 'NOT IN', 'NOT LIKE', 'NOT EXISTS', 'NOT REGEXP' ), true ) ) { // Negative clauses may be reused. $i = count( $this->table_aliases ); $subquery_alias = $i ? 'mt' . $i : $this->meta_table; $this->table_aliases[] = $subquery_alias; $meta_compare_string_start = 'NOT EXISTS ('; $meta_compare_string_start .= "SELECT 1 FROM $wpdb->postmeta $subquery_alias "; $meta_compare_string_start .= "WHERE $subquery_alias.post_ID = $alias.post_ID "; $meta_compare_string_end = 'LIMIT 1'; $meta_compare_string_end .= ')'; } switch ( $meta_compare_key ) { case '=': case 'EXISTS': $where = $wpdb->prepare( "$alias.meta_key = %s", trim( $clause['key'] ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; case 'LIKE': $meta_compare_value = '%' . $wpdb->esc_like( trim( $clause['key'] ) ) . '%'; $where = $wpdb->prepare( "$alias.meta_key LIKE %s", $meta_compare_value ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; case 'IN': $meta_compare_string = "$alias.meta_key IN (" . substr( str_repeat( ',%s', count( $clause['key'] ) ), 1 ) . ')'; $where = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared break; case 'RLIKE': case 'REGEXP': $operator = $meta_compare_key; if ( isset( $clause['type_key'] ) && 'BINARY' === strtoupper( $clause['type_key'] ) ) { $cast = 'BINARY'; $meta_key = "CAST($alias.meta_key AS BINARY)"; } else { $cast = ''; $meta_key = "$alias.meta_key"; } $where = $wpdb->prepare( "$meta_key $operator $cast %s", trim( $clause['key'] ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared break; case '!=': case 'NOT EXISTS': $meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key = %s " . $meta_compare_string_end; $where = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared break; case 'NOT LIKE': $meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key LIKE %s " . $meta_compare_string_end; $meta_compare_value = '%' . $wpdb->esc_like( trim( $clause['key'] ) ) . '%'; $where = $wpdb->prepare( $meta_compare_string, $meta_compare_value ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared break; case 'NOT IN': $array_subclause = '(' . substr( str_repeat( ',%s', count( $clause['key'] ) ), 1 ) . ') '; $meta_compare_string = $meta_compare_string_start . "AND $subquery_alias.meta_key IN " . $array_subclause . $meta_compare_string_end; $where = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared break; case 'NOT REGEXP': $operator = $meta_compare_key; if ( isset( $clause['type_key'] ) && 'BINARY' === strtoupper( $clause['type_key'] ) ) { $cast = 'BINARY'; $meta_key = "CAST($subquery_alias.meta_key AS BINARY)"; } else { $cast = ''; $meta_key = "$subquery_alias.meta_key"; } $meta_compare_string = $meta_compare_string_start . "AND $meta_key REGEXP $cast %s " . $meta_compare_string_end; $where = $wpdb->prepare( $meta_compare_string, $clause['key'] ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared break; } $sql_chunks['where'][] = $where; } } // meta_value. if ( array_key_exists( 'value', $clause ) ) { $meta_value = $clause['value']; if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ), true ) ) { if ( ! is_array( $meta_value ) ) { $meta_value = preg_split( '/[,\s]+/', $meta_value ); } } elseif ( is_string( $meta_value ) ) { $meta_value = trim( $meta_value ); } switch ( $meta_compare ) { case 'IN': case 'NOT IN': $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')'; $where = $wpdb->prepare( $meta_compare_string, $meta_value ); break; case 'BETWEEN': case 'NOT BETWEEN': $where = $wpdb->prepare( '%s AND %s', $meta_value[0], $meta_value[1] ); break; case 'LIKE': case 'NOT LIKE': $meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%'; $where = $wpdb->prepare( '%s', $meta_value ); break; // EXISTS with a value is interpreted as '='. case 'EXISTS': $meta_compare = '='; $where = $wpdb->prepare( '%s', $meta_value ); break; // 'value' is ignored for NOT EXISTS. case 'NOT EXISTS': $where = ''; break; default: $where = $wpdb->prepare( '%s', $meta_value ); break; } if ( $where ) { if ( 'CHAR' === $meta_type ) { $sql_chunks['where'][] = "$alias.meta_value {$meta_compare} {$where}"; } else { $sql_chunks['where'][] = "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$where}"; } } } /* * Multiple WHERE clauses (for meta_key and meta_value) should * be joined in parentheses. */ if ( 1 < count( $sql_chunks['where'] ) ) { $sql_chunks['where'] = array( '( ' . implode( ' AND ', $sql_chunks['where'] ) . ' )' ); } return $sql_chunks; } /** * Get a flattened list of sanitized meta clauses. * * This array should be used for clause lookup, as when the table alias and CAST type must be determined for * a value of 'orderby' corresponding to a meta clause. * * @since 4.2.0 * * @return array Meta clauses. */ public function get_clauses() { return $this->clauses; } /** * Identify an existing table alias that is compatible with the current * query clause. * * We avoid unnecessary table joins by allowing each clause to look for * an existing table alias that is compatible with the query that it * needs to perform. * * An existing alias is compatible if (a) it is a sibling of `$clause` * (ie, it's under the scope of the same relation), and (b) the combination * of operator and relation between the clauses allows for a shared table join. * In the case of WP_Meta_Query, this only applies to 'IN' clauses that are * connected by the relation 'OR'. * * @since 4.1.0 * * @param array $clause Query clause. * @param array $parent_query Parent query of $clause. * @return string|false Table alias if found, otherwise false. */ protected function find_compatible_table_alias( $clause, $parent_query ) { $alias = false; foreach ( $parent_query as $sibling ) { // If the sibling has no alias yet, there's nothing to check. if ( empty( $sibling['alias'] ) ) { continue; } // We're only interested in siblings that are first-order clauses. if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) { continue; } $compatible_compares = array(); // Clauses connected by OR can share joins as long as they have "positive" operators. if ( 'OR' === $parent_query['relation'] ) { $compatible_compares = array( '=', 'IN', 'BETWEEN', 'LIKE', 'REGEXP', 'RLIKE', '>', '>=', '<', '<=' ); // Clauses joined by AND with "negative" operators share a join only if they also share a key. } elseif ( isset( $sibling['key'] ) && isset( $clause['key'] ) && $sibling['key'] === $clause['key'] ) { $compatible_compares = array( '!=', 'NOT IN', 'NOT LIKE' ); } $clause_compare = strtoupper( $clause['compare'] ); $sibling_compare = strtoupper( $sibling['compare'] ); if ( in_array( $clause_compare, $compatible_compares, true ) && in_array( $sibling_compare, $compatible_compares, true ) ) { $alias = preg_replace( '/\W/', '_', $sibling['alias'] ); break; } } /** * Filters the table alias identified as compatible with the current clause. * * @since 4.1.0 * * @param string|false $alias Table alias, or false if none was found. * @param array $clause First-order query clause. * @param array $parent_query Parent of $clause. * @param WP_Meta_Query $query WP_Meta_Query object. */ return apply_filters( 'meta_query_find_compatible_table_alias', $alias, $clause, $parent_query, $this ); } /** * Checks whether the current query has any OR relations. * * In some cases, the presence of an OR relation somewhere in the query will require * the use of a `DISTINCT` or `GROUP BY` keyword in the `SELECT` clause. The current * method can be used in these cases to determine whether such a clause is necessary. * * @since 4.3.0 * * @return bool True if the query contains any `OR` relations, otherwise false. */ public function has_or_relation() { return $this->has_or_relation; } } ``` | Version | Description | | --- | --- | | [3.2.0](https://developer.wordpress.org/reference/since/3.2.0/) | Introduced. |
programming_docs
wordpress class WP_Widget_Factory {} class WP\_Widget\_Factory {} ============================ Singleton that registers and instantiates [WP\_Widget](wp_widget) classes. * [\_\_construct](wp_widget_factory/__construct) β€” PHP5 constructor. * [\_register\_widgets](wp_widget_factory/_register_widgets) β€” Serves as a utility method for adding widgets to the registered widgets global. * [get\_widget\_key](wp_widget_factory/get_widget_key) β€” Returns the registered key for the given widget type. * [get\_widget\_object](wp_widget_factory/get_widget_object) β€” Returns the registered WP\_Widget object for the given widget type. * [register](wp_widget_factory/register) β€” Registers a widget subclass. * [unregister](wp_widget_factory/unregister) β€” Un-registers a widget subclass. * [WP\_Widget\_Factory](wp_widget_factory/wp_widget_factory) β€” PHP4 constructor. β€” deprecated File: `wp-includes/class-wp-widget-factory.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-widget-factory.php/) ``` class WP_Widget_Factory { /** * Widgets array. * * @since 2.8.0 * @var array */ public $widgets = array(); /** * PHP5 constructor. * * @since 4.3.0 */ public function __construct() { add_action( 'widgets_init', array( $this, '_register_widgets' ), 100 ); } /** * PHP4 constructor. * * @since 2.8.0 * @deprecated 4.3.0 Use __construct() instead. * * @see WP_Widget_Factory::__construct() */ public function WP_Widget_Factory() { _deprecated_constructor( 'WP_Widget_Factory', '4.3.0' ); self::__construct(); } /** * Registers a widget subclass. * * @since 2.8.0 * @since 4.6.0 Updated the `$widget` parameter to also accept a WP_Widget instance object * instead of simply a `WP_Widget` subclass name. * * @param string|WP_Widget $widget Either the name of a `WP_Widget` subclass or an instance of a `WP_Widget` subclass. */ public function register( $widget ) { if ( $widget instanceof WP_Widget ) { $this->widgets[ spl_object_hash( $widget ) ] = $widget; } else { $this->widgets[ $widget ] = new $widget(); } } /** * Un-registers a widget subclass. * * @since 2.8.0 * @since 4.6.0 Updated the `$widget` parameter to also accept a WP_Widget instance object * instead of simply a `WP_Widget` subclass name. * * @param string|WP_Widget $widget Either the name of a `WP_Widget` subclass or an instance of a `WP_Widget` subclass. */ public function unregister( $widget ) { if ( $widget instanceof WP_Widget ) { unset( $this->widgets[ spl_object_hash( $widget ) ] ); } else { unset( $this->widgets[ $widget ] ); } } /** * Serves as a utility method for adding widgets to the registered widgets global. * * @since 2.8.0 * * @global array $wp_registered_widgets */ public function _register_widgets() { global $wp_registered_widgets; $keys = array_keys( $this->widgets ); $registered = array_keys( $wp_registered_widgets ); $registered = array_map( '_get_widget_id_base', $registered ); foreach ( $keys as $key ) { // Don't register new widget if old widget with the same id is already registered. if ( in_array( $this->widgets[ $key ]->id_base, $registered, true ) ) { unset( $this->widgets[ $key ] ); continue; } $this->widgets[ $key ]->_register(); } } /** * Returns the registered WP_Widget object for the given widget type. * * @since 5.8.0 * * @param string $id_base Widget type ID. * @return WP_Widget|null */ public function get_widget_object( $id_base ) { $key = $this->get_widget_key( $id_base ); if ( '' === $key ) { return null; } return $this->widgets[ $key ]; } /** * Returns the registered key for the given widget type. * * @since 5.8.0 * * @param string $id_base Widget type ID. * @return string */ public function get_widget_key( $id_base ) { foreach ( $this->widgets as $key => $widget_object ) { if ( $widget_object->id_base === $id_base ) { return $key; } } return ''; } } ``` | Version | Description | | --- | --- | | [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Moved to its own file from wp-includes/widgets.php | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. | wordpress class WP_Widget_Media_Image {} class WP\_Widget\_Media\_Image {} ================================= Core class that implements an image widget. * [WP\_Widget\_Media](wp_widget_media) * [WP\_Widget](wp_widget) * [\_\_construct](wp_widget_media_image/__construct) β€” Constructor. * [enqueue\_admin\_scripts](wp_widget_media_image/enqueue_admin_scripts) β€” Loads the required media files for the media manager and scripts for media widgets. * [get\_instance\_schema](wp_widget_media_image/get_instance_schema) β€” Get schema for properties of a widget instance (item). * [render\_control\_template\_scripts](wp_widget_media_image/render_control_template_scripts) β€” Render form template scripts. * [render\_media](wp_widget_media_image/render_media) β€” Render the media on the frontend. File: `wp-includes/widgets/class-wp-widget-media-image.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-image.php/) ``` class WP_Widget_Media_Image extends WP_Widget_Media { /** * Constructor. * * @since 4.8.0 */ public function __construct() { parent::__construct( 'media_image', __( 'Image' ), array( 'description' => __( 'Displays an image.' ), 'mime_type' => 'image', ) ); $this->l10n = array_merge( $this->l10n, array( 'no_media_selected' => __( 'No image selected' ), 'add_media' => _x( 'Add Image', 'label for button in the image widget' ), 'replace_media' => _x( 'Replace Image', 'label for button in the image widget; should preferably not be longer than ~13 characters long' ), 'edit_media' => _x( 'Edit Image', 'label for button in the image widget; should preferably not be longer than ~13 characters long' ), 'missing_attachment' => sprintf( /* translators: %s: URL to media library. */ __( 'That image cannot be found. Check your <a href="%s">media library</a> and make sure it was not deleted.' ), esc_url( admin_url( 'upload.php' ) ) ), /* translators: %d: Widget count. */ 'media_library_state_multi' => _n_noop( 'Image Widget (%d)', 'Image Widget (%d)' ), 'media_library_state_single' => __( 'Image Widget' ), ) ); } /** * Get schema for properties of a widget instance (item). * * @since 4.8.0 * * @see WP_REST_Controller::get_item_schema() * @see WP_REST_Controller::get_additional_fields() * @link https://core.trac.wordpress.org/ticket/35574 * * @return array Schema for properties. */ public function get_instance_schema() { return array_merge( array( 'size' => array( 'type' => 'string', 'enum' => array_merge( get_intermediate_image_sizes(), array( 'full', 'custom' ) ), 'default' => 'medium', 'description' => __( 'Size' ), ), 'width' => array( // Via 'customWidth', only when size=custom; otherwise via 'width'. 'type' => 'integer', 'minimum' => 0, 'default' => 0, 'description' => __( 'Width' ), ), 'height' => array( // Via 'customHeight', only when size=custom; otherwise via 'height'. 'type' => 'integer', 'minimum' => 0, 'default' => 0, 'description' => __( 'Height' ), ), 'caption' => array( 'type' => 'string', 'default' => '', 'sanitize_callback' => 'wp_kses_post', 'description' => __( 'Caption' ), 'should_preview_update' => false, ), 'alt' => array( 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', 'description' => __( 'Alternative Text' ), ), 'link_type' => array( 'type' => 'string', 'enum' => array( 'none', 'file', 'post', 'custom' ), 'default' => 'custom', 'media_prop' => 'link', 'description' => __( 'Link To' ), 'should_preview_update' => true, ), 'link_url' => array( 'type' => 'string', 'default' => '', 'format' => 'uri', 'media_prop' => 'linkUrl', 'description' => __( 'URL' ), 'should_preview_update' => true, ), 'image_classes' => array( 'type' => 'string', 'default' => '', 'sanitize_callback' => array( $this, 'sanitize_token_list' ), 'media_prop' => 'extraClasses', 'description' => __( 'Image CSS Class' ), 'should_preview_update' => false, ), 'link_classes' => array( 'type' => 'string', 'default' => '', 'sanitize_callback' => array( $this, 'sanitize_token_list' ), 'media_prop' => 'linkClassName', 'should_preview_update' => false, 'description' => __( 'Link CSS Class' ), ), 'link_rel' => array( 'type' => 'string', 'default' => '', 'sanitize_callback' => array( $this, 'sanitize_token_list' ), 'media_prop' => 'linkRel', 'description' => __( 'Link Rel' ), 'should_preview_update' => false, ), 'link_target_blank' => array( 'type' => 'boolean', 'default' => false, 'media_prop' => 'linkTargetBlank', 'description' => __( 'Open link in a new tab' ), 'should_preview_update' => false, ), 'image_title' => array( 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', 'media_prop' => 'title', 'description' => __( 'Image Title Attribute' ), 'should_preview_update' => false, ), /* * There are two additional properties exposed by the PostImage modal * that don't seem to be relevant, as they may only be derived read-only * values: * - originalUrl * - aspectRatio * - height (redundant when size is not custom) * - width (redundant when size is not custom) */ ), parent::get_instance_schema() ); } /** * Render the media on the frontend. * * @since 4.8.0 * * @param array $instance Widget instance props. */ public function render_media( $instance ) { $instance = array_merge( wp_list_pluck( $this->get_instance_schema(), 'default' ), $instance ); $instance = wp_parse_args( $instance, array( 'size' => 'thumbnail', ) ); $attachment = null; if ( $this->is_attachment_with_mime_type( $instance['attachment_id'], $this->widget_options['mime_type'] ) ) { $attachment = get_post( $instance['attachment_id'] ); } if ( $attachment ) { $caption = ''; if ( ! isset( $instance['caption'] ) ) { $caption = $attachment->post_excerpt; } elseif ( trim( $instance['caption'] ) ) { $caption = $instance['caption']; } $image_attributes = array( 'class' => sprintf( 'image wp-image-%d %s', $attachment->ID, $instance['image_classes'] ), 'style' => 'max-width: 100%; height: auto;', ); if ( ! empty( $instance['image_title'] ) ) { $image_attributes['title'] = $instance['image_title']; } if ( $instance['alt'] ) { $image_attributes['alt'] = $instance['alt']; } $size = $instance['size']; if ( 'custom' === $size || ! in_array( $size, array_merge( get_intermediate_image_sizes(), array( 'full' ) ), true ) ) { $size = array( $instance['width'], $instance['height'] ); $width = $instance['width']; } else { $caption_size = _wp_get_image_size_from_meta( $instance['size'], wp_get_attachment_metadata( $attachment->ID ) ); $width = empty( $caption_size[0] ) ? 0 : $caption_size[0]; } $image_attributes['class'] .= sprintf( ' attachment-%1$s size-%1$s', is_array( $size ) ? implode( 'x', $size ) : $size ); $image = wp_get_attachment_image( $attachment->ID, $size, false, $image_attributes ); } else { if ( empty( $instance['url'] ) ) { return; } $instance['size'] = 'custom'; $caption = $instance['caption']; $width = $instance['width']; $classes = 'image ' . $instance['image_classes']; if ( 0 === $instance['width'] ) { $instance['width'] = ''; } if ( 0 === $instance['height'] ) { $instance['height'] = ''; } $image = sprintf( '<img class="%1$s" src="%2$s" alt="%3$s" width="%4$s" height="%5$s" />', esc_attr( $classes ), esc_url( $instance['url'] ), esc_attr( $instance['alt'] ), esc_attr( $instance['width'] ), esc_attr( $instance['height'] ) ); } // End if(). $url = ''; if ( 'file' === $instance['link_type'] ) { $url = $attachment ? wp_get_attachment_url( $attachment->ID ) : $instance['url']; } elseif ( $attachment && 'post' === $instance['link_type'] ) { $url = get_attachment_link( $attachment->ID ); } elseif ( 'custom' === $instance['link_type'] && ! empty( $instance['link_url'] ) ) { $url = $instance['link_url']; } if ( $url ) { $link = sprintf( '<a href="%s"', esc_url( $url ) ); if ( ! empty( $instance['link_classes'] ) ) { $link .= sprintf( ' class="%s"', esc_attr( $instance['link_classes'] ) ); } if ( ! empty( $instance['link_rel'] ) ) { $link .= sprintf( ' rel="%s"', esc_attr( $instance['link_rel'] ) ); } if ( ! empty( $instance['link_target_blank'] ) ) { $link .= ' target="_blank"'; } $link .= '>'; $link .= $image; $link .= '</a>'; $image = wp_targeted_link_rel( $link ); } if ( $caption ) { $image = img_caption_shortcode( array( 'width' => $width, 'caption' => $caption, ), $image ); } echo $image; } /** * Loads the required media files for the media manager and scripts for media widgets. * * @since 4.8.0 */ public function enqueue_admin_scripts() { parent::enqueue_admin_scripts(); $handle = 'media-image-widget'; wp_enqueue_script( $handle ); $exported_schema = array(); foreach ( $this->get_instance_schema() as $field => $field_schema ) { $exported_schema[ $field ] = wp_array_slice_assoc( $field_schema, array( 'type', 'default', 'enum', 'minimum', 'format', 'media_prop', 'should_preview_update' ) ); } wp_add_inline_script( $handle, sprintf( 'wp.mediaWidgets.modelConstructors[ %s ].prototype.schema = %s;', wp_json_encode( $this->id_base ), wp_json_encode( $exported_schema ) ) ); wp_add_inline_script( $handle, sprintf( ' wp.mediaWidgets.controlConstructors[ %1$s ].prototype.mime_type = %2$s; wp.mediaWidgets.controlConstructors[ %1$s ].prototype.l10n = _.extend( {}, wp.mediaWidgets.controlConstructors[ %1$s ].prototype.l10n, %3$s ); ', wp_json_encode( $this->id_base ), wp_json_encode( $this->widget_options['mime_type'] ), wp_json_encode( $this->l10n ) ) ); } /** * Render form template scripts. * * @since 4.8.0 */ public function render_control_template_scripts() { parent::render_control_template_scripts(); ?> <script type="text/html" id="tmpl-wp-media-widget-image-fields"> <# var elementIdPrefix = 'el' + String( Math.random() ) + '_'; #> <# if ( data.url ) { #> <p class="media-widget-image-link"> <label for="{{ elementIdPrefix }}linkUrl"><?php esc_html_e( 'Link to:' ); ?></label> <input id="{{ elementIdPrefix }}linkUrl" type="text" class="widefat link" value="{{ data.link_url }}" placeholder="https://" pattern="((\w+:)?\/\/\w.*|\w+:(?!\/\/$)|\/|\?|#).*"> </p> <# } #> </script> <script type="text/html" id="tmpl-wp-media-widget-image-preview"> <# if ( data.error && 'missing_attachment' === data.error ) { #> <div class="notice notice-error notice-alt notice-missing-attachment"> <p><?php echo $this->l10n['missing_attachment']; ?></p> </div> <# } else if ( data.error ) { #> <div class="notice notice-error notice-alt"> <p><?php _e( 'Unable to preview media due to an unknown error.' ); ?></p> </div> <# } else if ( data.url ) { #> <img class="attachment-thumb" src="{{ data.url }}" draggable="false" alt="{{ data.alt }}" <# if ( ! data.alt && data.currentFilename ) { #> aria-label=" <?php echo esc_attr( sprintf( /* translators: %s: The image file name. */ __( 'The current image has no alternative text. The file name is: %s' ), '{{ data.currentFilename }}' ) ); ?> " <# } #> /> <# } #> </script> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Widget\_Media](wp_widget_media) wp-includes/widgets/class-wp-widget-media.php | Core class that implements a media widget. | | Version | Description | | --- | --- | | [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. | wordpress class WP_REST_Post_Statuses_Controller {} class WP\_REST\_Post\_Statuses\_Controller {} ============================================= Core class used to access post statuses via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_post_statuses_controller/__construct) β€” Constructor. * [check\_read\_permission](wp_rest_post_statuses_controller/check_read_permission) β€” Checks whether a given post status should be visible. * [get\_collection\_params](wp_rest_post_statuses_controller/get_collection_params) β€” Retrieves the query params for collections. * [get\_item](wp_rest_post_statuses_controller/get_item) β€” Retrieves a specific post status. * [get\_item\_permissions\_check](wp_rest_post_statuses_controller/get_item_permissions_check) β€” Checks if a given request has access to read a post status. * [get\_item\_schema](wp_rest_post_statuses_controller/get_item_schema) β€” Retrieves the post status' schema, conforming to JSON Schema. * [get\_items](wp_rest_post_statuses_controller/get_items) β€” Retrieves all post statuses, depending on user context. * [get\_items\_permissions\_check](wp_rest_post_statuses_controller/get_items_permissions_check) β€” Checks whether a given request has permission to read post statuses. * [prepare\_item\_for\_response](wp_rest_post_statuses_controller/prepare_item_for_response) β€” Prepares a post status object for serialization. * [register\_routes](wp_rest_post_statuses_controller/register_routes) β€” Registers the routes for post statuses. File: `wp-includes/rest-api/endpoints/class-wp-rest-post-statuses-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-post-statuses-controller.php/) ``` class WP_REST_Post_Statuses_Controller extends WP_REST_Controller { /** * Constructor. * * @since 4.7.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'statuses'; } /** * Registers the routes for post statuses. * * @since 4.7.0 * * @see register_rest_route() */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => $this->get_collection_params(), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<status>[\w-]+)', array( 'args' => array( 'status' => array( 'description' => __( 'An alphanumeric identifier for the status.' ), 'type' => 'string', ), ), array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'permission_callback' => array( $this, 'get_item_permissions_check' ), 'args' => array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks whether a given request has permission to read post statuses. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { if ( 'edit' === $request['context'] ) { $types = get_post_types( array( 'show_in_rest' => true ), 'objects' ); foreach ( $types as $type ) { if ( current_user_can( $type->cap->edit_posts ) ) { return true; } } return new WP_Error( 'rest_cannot_view', __( 'Sorry, you are not allowed to manage post statuses.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Retrieves all post statuses, depending on user context. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { $data = array(); $statuses = get_post_stati( array( 'internal' => false ), 'object' ); $statuses['trash'] = get_post_status_object( 'trash' ); foreach ( $statuses as $slug => $obj ) { $ret = $this->check_read_permission( $obj ); if ( ! $ret ) { continue; } $status = $this->prepare_item_for_response( $obj, $request ); $data[ $obj->name ] = $this->prepare_response_for_collection( $status ); } return rest_ensure_response( $data ); } /** * Checks if a given request has access to read a post status. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise. */ public function get_item_permissions_check( $request ) { $status = get_post_status_object( $request['status'] ); if ( empty( $status ) ) { return new WP_Error( 'rest_status_invalid', __( 'Invalid status.' ), array( 'status' => 404 ) ); } $check = $this->check_read_permission( $status ); if ( ! $check ) { return new WP_Error( 'rest_cannot_read_status', __( 'Cannot view status.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Checks whether a given post status should be visible. * * @since 4.7.0 * * @param object $status Post status. * @return bool True if the post status is visible, otherwise false. */ protected function check_read_permission( $status ) { if ( true === $status->public ) { return true; } if ( false === $status->internal || 'trash' === $status->name ) { $types = get_post_types( array( 'show_in_rest' => true ), 'objects' ); foreach ( $types as $type ) { if ( current_user_can( $type->cap->edit_posts ) ) { return true; } } } return false; } /** * Retrieves a specific post status. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { $obj = get_post_status_object( $request['status'] ); if ( empty( $obj ) ) { return new WP_Error( 'rest_status_invalid', __( 'Invalid status.' ), array( 'status' => 404 ) ); } $data = $this->prepare_item_for_response( $obj, $request ); return rest_ensure_response( $data ); } /** * Prepares a post status object for serialization. * * @since 4.7.0 * @since 5.9.0 Renamed `$status` to `$item` to match parent class for PHP 8 named parameter support. * * @param stdClass $item Post status data. * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response Post status data. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $status = $item; $fields = $this->get_fields_for_response( $request ); $data = array(); if ( in_array( 'name', $fields, true ) ) { $data['name'] = $status->label; } if ( in_array( 'private', $fields, true ) ) { $data['private'] = (bool) $status->private; } if ( in_array( 'protected', $fields, true ) ) { $data['protected'] = (bool) $status->protected; } if ( in_array( 'public', $fields, true ) ) { $data['public'] = (bool) $status->public; } if ( in_array( 'queryable', $fields, true ) ) { $data['queryable'] = (bool) $status->publicly_queryable; } if ( in_array( 'show_in_list', $fields, true ) ) { $data['show_in_list'] = (bool) $status->show_in_admin_all_list; } if ( in_array( 'slug', $fields, true ) ) { $data['slug'] = $status->name; } if ( in_array( 'date_floating', $fields, true ) ) { $data['date_floating'] = $status->date_floating; } $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 ); $rest_url = rest_url( rest_get_route_for_post_type_items( 'post' ) ); if ( 'publish' === $status->name ) { $response->add_link( 'archives', $rest_url ); } else { $response->add_link( 'archives', add_query_arg( 'status', $status->name, $rest_url ) ); } /** * Filters a post status returned from the REST API. * * Allows modification of the status data right before it is returned. * * @since 4.7.0 * * @param WP_REST_Response $response The response object. * @param object $status The original post status object. * @param WP_REST_Request $request Request used to generate the response. */ return apply_filters( 'rest_prepare_status', $response, $status, $request ); } /** * Retrieves the post status' schema, conforming to JSON Schema. * * @since 4.7.0 * * @return array Item schema data. */ 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' => 'status', 'type' => 'object', 'properties' => array( 'name' => array( 'description' => __( 'The title for the status.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'private' => array( 'description' => __( 'Whether posts with this status should be private.' ), 'type' => 'boolean', 'context' => array( 'edit' ), 'readonly' => true, ), 'protected' => array( 'description' => __( 'Whether posts with this status should be protected.' ), 'type' => 'boolean', 'context' => array( 'edit' ), 'readonly' => true, ), 'public' => array( 'description' => __( 'Whether posts of this status should be shown in the front end of the site.' ), 'type' => 'boolean', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), 'queryable' => array( 'description' => __( 'Whether posts with this status should be publicly-queryable.' ), 'type' => 'boolean', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), 'show_in_list' => array( 'description' => __( 'Whether to include posts in the edit listing for their post type.' ), 'type' => 'boolean', 'context' => array( 'edit' ), 'readonly' => true, ), 'slug' => array( 'description' => __( 'An alphanumeric identifier for the status.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'date_floating' => array( 'description' => __( 'Whether posts of this status may have floating published dates.' ), 'type' => 'boolean', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), ), ); $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the query params for collections. * * @since 4.7.0 * * @return array Collection parameters. */ public function get_collection_params() { return array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Taxonomies_Controller {} class WP\_REST\_Taxonomies\_Controller {} ========================================= Core class used to manage taxonomies via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_taxonomies_controller/__construct) β€” Constructor. * [get\_collection\_params](wp_rest_taxonomies_controller/get_collection_params) β€” Retrieves the query params for collections. * [get\_item](wp_rest_taxonomies_controller/get_item) β€” Retrieves a specific taxonomy. * [get\_item\_permissions\_check](wp_rest_taxonomies_controller/get_item_permissions_check) β€” Checks if a given request has access to a taxonomy. * [get\_item\_schema](wp_rest_taxonomies_controller/get_item_schema) β€” Retrieves the taxonomy's schema, conforming to JSON Schema. * [get\_items](wp_rest_taxonomies_controller/get_items) β€” Retrieves all public taxonomies. * [get\_items\_permissions\_check](wp_rest_taxonomies_controller/get_items_permissions_check) β€” Checks whether a given request has permission to read taxonomies. * [prepare\_item\_for\_response](wp_rest_taxonomies_controller/prepare_item_for_response) β€” Prepares a taxonomy object for serialization. * [prepare\_links](wp_rest_taxonomies_controller/prepare_links) β€” Prepares links for the request. * [register\_routes](wp_rest_taxonomies_controller/register_routes) β€” Registers the routes for taxonomies. File: `wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php/) ``` class WP_REST_Taxonomies_Controller extends WP_REST_Controller { /** * Constructor. * * @since 4.7.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'taxonomies'; } /** * Registers the routes for taxonomies. * * @since 4.7.0 * * @see register_rest_route() */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => $this->get_collection_params(), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<taxonomy>[\w-]+)', array( 'args' => array( 'taxonomy' => array( 'description' => __( 'An alphanumeric identifier for the taxonomy.' ), 'type' => 'string', ), ), array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'permission_callback' => array( $this, 'get_item_permissions_check' ), 'args' => array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks whether a given request has permission to read taxonomies. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { if ( 'edit' === $request['context'] ) { if ( ! empty( $request['type'] ) ) { $taxonomies = get_object_taxonomies( $request['type'], 'objects' ); } else { $taxonomies = get_taxonomies( '', 'objects' ); } foreach ( $taxonomies as $taxonomy ) { if ( ! empty( $taxonomy->show_in_rest ) && current_user_can( $taxonomy->cap->assign_terms ) ) { return true; } } return new WP_Error( 'rest_cannot_view', __( 'Sorry, you are not allowed to manage terms in this taxonomy.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Retrieves all public taxonomies. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { // Retrieve the list of registered collection query parameters. $registered = $this->get_collection_params(); if ( isset( $registered['type'] ) && ! empty( $request['type'] ) ) { $taxonomies = get_object_taxonomies( $request['type'], 'objects' ); } else { $taxonomies = get_taxonomies( '', 'objects' ); } $data = array(); foreach ( $taxonomies as $tax_type => $value ) { if ( empty( $value->show_in_rest ) || ( 'edit' === $request['context'] && ! current_user_can( $value->cap->assign_terms ) ) ) { continue; } $tax = $this->prepare_item_for_response( $value, $request ); $tax = $this->prepare_response_for_collection( $tax ); $data[ $tax_type ] = $tax; } if ( empty( $data ) ) { // Response should still be returned as a JSON object when it is empty. $data = (object) $data; } return rest_ensure_response( $data ); } /** * Checks if a given request has access to a taxonomy. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, otherwise false or WP_Error object. */ public function get_item_permissions_check( $request ) { $tax_obj = get_taxonomy( $request['taxonomy'] ); if ( $tax_obj ) { if ( empty( $tax_obj->show_in_rest ) ) { return false; } if ( 'edit' === $request['context'] && ! current_user_can( $tax_obj->cap->assign_terms ) ) { return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to manage terms in this taxonomy.' ), array( 'status' => rest_authorization_required_code() ) ); } } return true; } /** * Retrieves a specific taxonomy. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { $tax_obj = get_taxonomy( $request['taxonomy'] ); if ( empty( $tax_obj ) ) { return new WP_Error( 'rest_taxonomy_invalid', __( 'Invalid taxonomy.' ), array( 'status' => 404 ) ); } $data = $this->prepare_item_for_response( $tax_obj, $request ); return rest_ensure_response( $data ); } /** * Prepares a taxonomy object for serialization. * * @since 4.7.0 * @since 5.9.0 Renamed `$taxonomy` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Taxonomy $item Taxonomy data. * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response Response object. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $taxonomy = $item; $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; $fields = $this->get_fields_for_response( $request ); $data = array(); if ( in_array( 'name', $fields, true ) ) { $data['name'] = $taxonomy->label; } if ( in_array( 'slug', $fields, true ) ) { $data['slug'] = $taxonomy->name; } if ( in_array( 'capabilities', $fields, true ) ) { $data['capabilities'] = $taxonomy->cap; } if ( in_array( 'description', $fields, true ) ) { $data['description'] = $taxonomy->description; } if ( in_array( 'labels', $fields, true ) ) { $data['labels'] = $taxonomy->labels; } if ( in_array( 'types', $fields, true ) ) { $data['types'] = array_values( $taxonomy->object_type ); } if ( in_array( 'show_cloud', $fields, true ) ) { $data['show_cloud'] = $taxonomy->show_tagcloud; } if ( in_array( 'hierarchical', $fields, true ) ) { $data['hierarchical'] = $taxonomy->hierarchical; } if ( in_array( 'rest_base', $fields, true ) ) { $data['rest_base'] = $base; } if ( in_array( 'rest_namespace', $fields, true ) ) { $data['rest_namespace'] = $taxonomy->rest_namespace; } if ( in_array( 'visibility', $fields, true ) ) { $data['visibility'] = array( 'public' => (bool) $taxonomy->public, 'publicly_queryable' => (bool) $taxonomy->publicly_queryable, 'show_admin_column' => (bool) $taxonomy->show_admin_column, 'show_in_nav_menus' => (bool) $taxonomy->show_in_nav_menus, 'show_in_quick_edit' => (bool) $taxonomy->show_in_quick_edit, 'show_ui' => (bool) $taxonomy->show_ui, ); } $context = ! empty( $request['context'] ) ? $request['context'] : 'view'; $data = $this->add_additional_fields_to_object( $data, $request ); $data = $this->filter_response_by_context( $data, $context ); // Wrap the data in a response object. $response = rest_ensure_response( $data ); if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { $response->add_links( $this->prepare_links( $taxonomy ) ); } /** * Filters a taxonomy returned from the REST API. * * Allows modification of the taxonomy data right before it is returned. * * @since 4.7.0 * * @param WP_REST_Response $response The response object. * @param WP_Taxonomy $item The original taxonomy object. * @param WP_REST_Request $request Request used to generate the response. */ return apply_filters( 'rest_prepare_taxonomy', $response, $taxonomy, $request ); } /** * Prepares links for the request. * * @since 6.1.0 * * @param WP_Taxonomy $taxonomy The taxonomy. * @return array Links for the given taxonomy. */ protected function prepare_links( $taxonomy ) { return array( 'collection' => array( 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ), ), 'https://api.w.org/items' => array( 'href' => rest_url( rest_get_route_for_taxonomy_items( $taxonomy->name ) ), ), ); } /** * Retrieves the taxonomy's schema, conforming to JSON Schema. * * @since 4.7.0 * @since 5.0.0 The `visibility` property was added. * @since 5.9.0 The `rest_namespace` property was added. * * @return array Item schema data. */ public function get_item_schema() { if ( $this->schema ) { return $this->add_additional_fields_schema( $this->schema ); } $schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'taxonomy', 'type' => 'object', 'properties' => array( 'capabilities' => array( 'description' => __( 'All capabilities used by the taxonomy.' ), 'type' => 'object', 'context' => array( 'edit' ), 'readonly' => true, ), 'description' => array( 'description' => __( 'A human-readable description of the taxonomy.' ), 'type' => 'string', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), 'hierarchical' => array( 'description' => __( 'Whether or not the taxonomy should have children.' ), 'type' => 'boolean', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), 'labels' => array( 'description' => __( 'Human-readable labels for the taxonomy for various contexts.' ), 'type' => 'object', 'context' => array( 'edit' ), 'readonly' => true, ), 'name' => array( 'description' => __( 'The title for the taxonomy.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'slug' => array( 'description' => __( 'An alphanumeric identifier for the taxonomy.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'show_cloud' => array( 'description' => __( 'Whether or not the term cloud should be displayed.' ), 'type' => 'boolean', 'context' => array( 'edit' ), 'readonly' => true, ), 'types' => array( 'description' => __( 'Types associated with the taxonomy.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), 'context' => array( 'view', 'edit' ), 'readonly' => true, ), 'rest_base' => array( 'description' => __( 'REST base route for the taxonomy.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'rest_namespace' => array( 'description' => __( 'REST namespace route for the taxonomy.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'visibility' => array( 'description' => __( 'The visibility settings for the taxonomy.' ), 'type' => 'object', 'context' => array( 'edit' ), 'readonly' => true, 'properties' => array( 'public' => array( 'description' => __( 'Whether a taxonomy is intended for use publicly either via the admin interface or by front-end users.' ), 'type' => 'boolean', ), 'publicly_queryable' => array( 'description' => __( 'Whether the taxonomy is publicly queryable.' ), 'type' => 'boolean', ), 'show_ui' => array( 'description' => __( 'Whether to generate a default UI for managing this taxonomy.' ), 'type' => 'boolean', ), 'show_admin_column' => array( 'description' => __( 'Whether to allow automatic creation of taxonomy columns on associated post-types table.' ), 'type' => 'boolean', ), 'show_in_nav_menus' => array( 'description' => __( 'Whether to make the taxonomy available for selection in navigation menus.' ), 'type' => 'boolean', ), 'show_in_quick_edit' => array( 'description' => __( 'Whether to show the taxonomy in the quick/bulk edit panel.' ), 'type' => 'boolean', ), ), ), ), ); $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the query params for collections. * * @since 4.7.0 * * @return array Collection parameters. */ public function get_collection_params() { $new_params = array(); $new_params['context'] = $this->get_context_param( array( 'default' => 'view' ) ); $new_params['type'] = array( 'description' => __( 'Limit results to taxonomies associated with a specific post type.' ), 'type' => 'string', ); return $new_params; } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. | wordpress class Requests_Exception_Transport {} class Requests\_Exception\_Transport {} ======================================= File: `wp-includes/Requests/Exception/Transport.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/transport.php/) ``` class Requests_Exception_Transport extends Requests_Exception { } ``` | Uses | Description | | --- | --- | | [Requests\_Exception](requests_exception) wp-includes/Requests/Exception.php | Exception for HTTP requests | | Used By | Description | | --- | --- | | [Requests\_Exception\_Transport\_cURL](requests_exception_transport_curl) wp-includes/Requests/Exception/Transport/cURL.php | | wordpress class WP_REST_Block_Patterns_Controller {} class WP\_REST\_Block\_Patterns\_Controller {} ============================================== Core class used to access block patterns via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_block_patterns_controller/__construct) β€” Constructs the controller. * [get\_item\_schema](wp_rest_block_patterns_controller/get_item_schema) β€” Retrieves the block pattern schema, conforming to JSON Schema. * [get\_items](wp_rest_block_patterns_controller/get_items) β€” Retrieves all block patterns. * [get\_items\_permissions\_check](wp_rest_block_patterns_controller/get_items_permissions_check) β€” Checks whether a given request has permission to read block patterns. * [prepare\_item\_for\_response](wp_rest_block_patterns_controller/prepare_item_for_response) β€” Prepare a raw block pattern before it gets output in a REST API response. * [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/) ``` class WP_REST_Block_Patterns_Controller extends WP_REST_Controller { /** * Defines whether remote patterns should be loaded. * * @since 6.0.0 * @var bool */ private $remote_patterns_loaded; /** * Constructs the controller. * * @since 6.0.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'block-patterns/patterns'; } /** * Registers the routes for the objects of the controller. * * @since 6.0.0 */ 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' ), ) ); } /** * Checks whether a given request has permission to read block patterns. * * @since 6.0.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ 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() ) ); } /** * Retrieves all block patterns. * * @since 6.0.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ 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 ); } /** * Prepare a raw block pattern before it gets output in a REST API response. * * @since 6.0.0 * * @param array $item Raw pattern as registered, before any changes. * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ 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 ); } /** * Retrieves the block pattern schema, conforming to JSON Schema. * * @since 6.0.0 * * @return array Item schema data. */ 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 | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
programming_docs
wordpress AtomEntry AtomEntry ========= **Class:** Structure that store Atom Entry Properties Source: wp-includes/atomlib.php:45 Used by [0 functions](atomentry#used-by) | Uses [0 functions](atomentry#uses) wordpress class WP_Sitemaps_Renderer {} class WP\_Sitemaps\_Renderer {} =============================== Class [WP\_Sitemaps\_Renderer](wp_sitemaps_renderer) * [\_\_construct](wp_sitemaps_renderer/__construct) β€” WP\_Sitemaps\_Renderer constructor. * [check\_for\_simple\_xml\_availability](wp_sitemaps_renderer/check_for_simple_xml_availability) β€” Checks for the availability of the SimpleXML extension and errors if missing. * [get\_sitemap\_index\_stylesheet\_url](wp_sitemaps_renderer/get_sitemap_index_stylesheet_url) β€” Gets the URL for the sitemap index stylesheet. * [get\_sitemap\_index\_xml](wp_sitemaps_renderer/get_sitemap_index_xml) β€” Gets XML for a sitemap index. * [get\_sitemap\_stylesheet\_url](wp_sitemaps_renderer/get_sitemap_stylesheet_url) β€” Gets the URL for the sitemap stylesheet. * [get\_sitemap\_xml](wp_sitemaps_renderer/get_sitemap_xml) β€” Gets XML for a sitemap. * [render\_index](wp_sitemaps_renderer/render_index) β€” Renders a sitemap index. * [render\_sitemap](wp_sitemaps_renderer/render_sitemap) β€” Renders a sitemap. File: `wp-includes/sitemaps/class-wp-sitemaps-renderer.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps-renderer.php/) ``` class WP_Sitemaps_Renderer { /** * XSL stylesheet for styling a sitemap for web browsers. * * @since 5.5.0 * * @var string */ protected $stylesheet = ''; /** * XSL stylesheet for styling a sitemap for web browsers. * * @since 5.5.0 * * @var string */ protected $stylesheet_index = ''; /** * WP_Sitemaps_Renderer constructor. * * @since 5.5.0 */ public function __construct() { $stylesheet_url = $this->get_sitemap_stylesheet_url(); if ( $stylesheet_url ) { $this->stylesheet = '<?xml-stylesheet type="text/xsl" href="' . esc_url( $stylesheet_url ) . '" ?>'; } $stylesheet_index_url = $this->get_sitemap_index_stylesheet_url(); if ( $stylesheet_index_url ) { $this->stylesheet_index = '<?xml-stylesheet type="text/xsl" href="' . esc_url( $stylesheet_index_url ) . '" ?>'; } } /** * Gets the URL for the sitemap stylesheet. * * @since 5.5.0 * * @global WP_Rewrite $wp_rewrite WordPress rewrite component. * * @return string The sitemap stylesheet URL. */ public function get_sitemap_stylesheet_url() { global $wp_rewrite; $sitemap_url = home_url( '/wp-sitemap.xsl' ); if ( ! $wp_rewrite->using_permalinks() ) { $sitemap_url = home_url( '/?sitemap-stylesheet=sitemap' ); } /** * Filters the URL for the sitemap stylesheet. * * If a falsey value is returned, no stylesheet will be used and * the "raw" XML of the sitemap will be displayed. * * @since 5.5.0 * * @param string $sitemap_url Full URL for the sitemaps XSL file. */ return apply_filters( 'wp_sitemaps_stylesheet_url', $sitemap_url ); } /** * Gets the URL for the sitemap index stylesheet. * * @since 5.5.0 * * @global WP_Rewrite $wp_rewrite WordPress rewrite component. * * @return string The sitemap index stylesheet URL. */ public function get_sitemap_index_stylesheet_url() { global $wp_rewrite; $sitemap_url = home_url( '/wp-sitemap-index.xsl' ); if ( ! $wp_rewrite->using_permalinks() ) { $sitemap_url = home_url( '/?sitemap-stylesheet=index' ); } /** * Filters the URL for the sitemap index stylesheet. * * If a falsey value is returned, no stylesheet will be used and * the "raw" XML of the sitemap index will be displayed. * * @since 5.5.0 * * @param string $sitemap_url Full URL for the sitemaps index XSL file. */ return apply_filters( 'wp_sitemaps_stylesheet_index_url', $sitemap_url ); } /** * Renders a sitemap index. * * @since 5.5.0 * * @param array $sitemaps Array of sitemap URLs. */ public function render_index( $sitemaps ) { header( 'Content-type: application/xml; charset=UTF-8' ); $this->check_for_simple_xml_availability(); $index_xml = $this->get_sitemap_index_xml( $sitemaps ); if ( ! empty( $index_xml ) ) { // All output is escaped within get_sitemap_index_xml(). // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo $index_xml; } } /** * Gets XML for a sitemap index. * * @since 5.5.0 * * @param array $sitemaps Array of sitemap URLs. * @return string|false A well-formed XML string for a sitemap index. False on error. */ public function get_sitemap_index_xml( $sitemaps ) { $sitemap_index = new SimpleXMLElement( sprintf( '%1$s%2$s%3$s', '<?xml version="1.0" encoding="UTF-8" ?>', $this->stylesheet_index, '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" />' ) ); foreach ( $sitemaps as $entry ) { $sitemap = $sitemap_index->addChild( 'sitemap' ); // Add each element as a child node to the <sitemap> entry. foreach ( $entry as $name => $value ) { if ( 'loc' === $name ) { $sitemap->addChild( $name, esc_url( $value ) ); } elseif ( 'lastmod' === $name ) { $sitemap->addChild( $name, esc_xml( $value ) ); } else { _doing_it_wrong( __METHOD__, sprintf( /* translators: %s: List of element names. */ __( 'Fields other than %s are not currently supported for the sitemap index.' ), implode( ',', array( 'loc', 'lastmod' ) ) ), '5.5.0' ); } } } return $sitemap_index->asXML(); } /** * Renders a sitemap. * * @since 5.5.0 * * @param array $url_list Array of URLs for a sitemap. */ public function render_sitemap( $url_list ) { header( 'Content-type: application/xml; charset=UTF-8' ); $this->check_for_simple_xml_availability(); $sitemap_xml = $this->get_sitemap_xml( $url_list ); if ( ! empty( $sitemap_xml ) ) { // All output is escaped within get_sitemap_xml(). // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo $sitemap_xml; } } /** * Gets XML for a sitemap. * * @since 5.5.0 * * @param array $url_list Array of URLs for a sitemap. * @return string|false A well-formed XML string for a sitemap index. False on error. */ public function get_sitemap_xml( $url_list ) { $urlset = new SimpleXMLElement( sprintf( '%1$s%2$s%3$s', '<?xml version="1.0" encoding="UTF-8" ?>', $this->stylesheet, '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" />' ) ); foreach ( $url_list as $url_item ) { $url = $urlset->addChild( 'url' ); // Add each element as a child node to the <url> entry. foreach ( $url_item as $name => $value ) { if ( 'loc' === $name ) { $url->addChild( $name, esc_url( $value ) ); } elseif ( in_array( $name, array( 'lastmod', 'changefreq', 'priority' ), true ) ) { $url->addChild( $name, esc_xml( $value ) ); } else { _doing_it_wrong( __METHOD__, sprintf( /* translators: %s: List of element names. */ __( 'Fields other than %s are not currently supported for sitemaps.' ), implode( ',', array( 'loc', 'lastmod', 'changefreq', 'priority' ) ) ), '5.5.0' ); } } } return $urlset->asXML(); } /** * Checks for the availability of the SimpleXML extension and errors if missing. * * @since 5.5.0 */ private function check_for_simple_xml_availability() { if ( ! class_exists( 'SimpleXMLElement' ) ) { add_filter( 'wp_die_handler', static function () { return '_xml_wp_die_handler'; } ); wp_die( sprintf( /* translators: %s: SimpleXML */ esc_xml( __( 'Could not generate XML sitemap due to missing %s extension' ) ), 'SimpleXML' ), esc_xml( __( 'WordPress &rsaquo; Error' ) ), array( 'response' => 501, // "Not implemented". ) ); } } } ``` | Version | Description | | --- | --- | | [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. | wordpress class WP_Role {} class WP\_Role {} ================= Core class used to extend the user roles API. * [\_\_construct](wp_role/__construct) β€” Constructor - Set up object properties. * [add\_cap](wp_role/add_cap) β€” Assign role a capability. * [has\_cap](wp_role/has_cap) β€” Determines whether the role has the given capability. * [remove\_cap](wp_role/remove_cap) β€” Removes a capability from a role. File: `wp-includes/class-wp-role.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-role.php/) ``` class WP_Role { /** * Role name. * * @since 2.0.0 * @var string */ public $name; /** * List of capabilities the role contains. * * @since 2.0.0 * @var bool[] Array of key/value pairs where keys represent a capability name and boolean values * represent whether the role has that capability. */ public $capabilities; /** * Constructor - Set up object properties. * * The list of capabilities must have the key as the name of the capability * and the value a boolean of whether it is granted to the role. * * @since 2.0.0 * * @param string $role Role name. * @param bool[] $capabilities Array of key/value pairs where keys represent a capability name and boolean values * represent whether the role has that capability. */ public function __construct( $role, $capabilities ) { $this->name = $role; $this->capabilities = $capabilities; } /** * Assign role a capability. * * @since 2.0.0 * * @param string $cap Capability name. * @param bool $grant Whether role has capability privilege. */ public function add_cap( $cap, $grant = true ) { $this->capabilities[ $cap ] = $grant; wp_roles()->add_cap( $this->name, $cap, $grant ); } /** * Removes a capability from a role. * * @since 2.0.0 * * @param string $cap Capability name. */ public function remove_cap( $cap ) { unset( $this->capabilities[ $cap ] ); wp_roles()->remove_cap( $this->name, $cap ); } /** * Determines whether the role has the given capability. * * @since 2.0.0 * * @param string $cap Capability name. * @return bool Whether the role has the given capability. */ public function has_cap( $cap ) { /** * Filters which capabilities a role has. * * @since 2.0.0 * * @param bool[] $capabilities Array of key/value pairs where keys represent a capability name and boolean values * represent whether the role has that capability. * @param string $cap Capability name. * @param string $name Role name. */ $capabilities = apply_filters( 'role_has_cap', $this->capabilities, $cap, $this->name ); if ( ! empty( $capabilities[ $cap ] ) ) { return $capabilities[ $cap ]; } else { return false; } } } ``` | Version | Description | | --- | --- | | [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. | wordpress class Walker_Nav_Menu_Edit {} class Walker\_Nav\_Menu\_Edit {} ================================ Create HTML list of nav menu input items. * [Walker\_Nav\_Menu](walker_nav_menu) * [end\_lvl](walker_nav_menu_edit/end_lvl) β€” Ends the list of after the elements are added. * [start\_el](walker_nav_menu_edit/start_el) β€” Start the element output. * [start\_lvl](walker_nav_menu_edit/start_lvl) β€” Starts the list before the elements are added. File: `wp-admin/includes/class-walker-nav-menu-edit.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-walker-nav-menu-edit.php/) ``` class Walker_Nav_Menu_Edit extends Walker_Nav_Menu { /** * Starts the list before the elements are added. * * @see Walker_Nav_Menu::start_lvl() * * @since 3.0.0 * * @param string $output Passed by reference. * @param int $depth Depth of menu item. Used for padding. * @param stdClass $args Not used. */ public function start_lvl( &$output, $depth = 0, $args = null ) {} /** * Ends the list of after the elements are added. * * @see Walker_Nav_Menu::end_lvl() * * @since 3.0.0 * * @param string $output Passed by reference. * @param int $depth Depth of menu item. Used for padding. * @param stdClass $args Not used. */ public function end_lvl( &$output, $depth = 0, $args = null ) {} /** * Start the element output. * * @see Walker_Nav_Menu::start_el() * @since 3.0.0 * @since 5.9.0 Renamed `$item` to `$data_object` and `$id` to `$current_object_id` * to match parent class for PHP 8 named parameter support. * * @global int $_wp_nav_menu_max_depth * * @param string $output Used to append additional content (passed by reference). * @param WP_Post $data_object Menu item data object. * @param int $depth Depth of menu item. Used for padding. * @param stdClass $args Not used. * @param int $current_object_id Optional. ID of the current menu item. Default 0. */ public function start_el( &$output, $data_object, $depth = 0, $args = null, $current_object_id = 0 ) { global $_wp_nav_menu_max_depth; // Restores the more descriptive, specific name for use within this method. $menu_item = $data_object; $_wp_nav_menu_max_depth = $depth > $_wp_nav_menu_max_depth ? $depth : $_wp_nav_menu_max_depth; ob_start(); $item_id = esc_attr( $menu_item->ID ); $removed_args = array( 'action', 'customlink-tab', 'edit-menu-item', 'menu-item', 'page-tab', '_wpnonce', ); $original_title = false; if ( 'taxonomy' === $menu_item->type ) { $original_object = get_term( (int) $menu_item->object_id, $menu_item->object ); if ( $original_object && ! is_wp_error( $original_object ) ) { $original_title = $original_object->name; } } elseif ( 'post_type' === $menu_item->type ) { $original_object = get_post( $menu_item->object_id ); if ( $original_object ) { $original_title = get_the_title( $original_object->ID ); } } elseif ( 'post_type_archive' === $menu_item->type ) { $original_object = get_post_type_object( $menu_item->object ); if ( $original_object ) { $original_title = $original_object->labels->archives; } } $classes = array( 'menu-item menu-item-depth-' . $depth, 'menu-item-' . esc_attr( $menu_item->object ), 'menu-item-edit-' . ( ( isset( $_GET['edit-menu-item'] ) && $item_id === $_GET['edit-menu-item'] ) ? 'active' : 'inactive' ), ); $title = $menu_item->title; if ( ! empty( $menu_item->_invalid ) ) { $classes[] = 'menu-item-invalid'; /* translators: %s: Title of an invalid menu item. */ $title = sprintf( __( '%s (Invalid)' ), $menu_item->title ); } elseif ( isset( $menu_item->post_status ) && 'draft' === $menu_item->post_status ) { $classes[] = 'pending'; /* translators: %s: Title of a menu item in draft status. */ $title = sprintf( __( '%s (Pending)' ), $menu_item->title ); } $title = ( ! isset( $menu_item->label ) || '' === $menu_item->label ) ? $title : $menu_item->label; $submenu_text = ''; if ( 0 === $depth ) { $submenu_text = 'style="display: none;"'; } ?> <li id="menu-item-<?php echo $item_id; ?>" class="<?php echo implode( ' ', $classes ); ?>"> <div class="menu-item-bar"> <div class="menu-item-handle"> <label class="item-title" for="menu-item-checkbox-<?php echo $item_id; ?>"> <input id="menu-item-checkbox-<?php echo $item_id; ?>" type="checkbox" class="menu-item-checkbox" data-menu-item-id="<?php echo $item_id; ?>" disabled="disabled" /> <span class="menu-item-title"><?php echo esc_html( $title ); ?></span> <span class="is-submenu" <?php echo $submenu_text; ?>><?php _e( 'sub item' ); ?></span> </label> <span class="item-controls"> <span class="item-type"><?php echo esc_html( $menu_item->type_label ); ?></span> <span class="item-order hide-if-js"> <?php printf( '<a href="%s" class="item-move-up" aria-label="%s">&#8593;</a>', wp_nonce_url( add_query_arg( array( 'action' => 'move-up-menu-item', 'menu-item' => $item_id, ), remove_query_arg( $removed_args, admin_url( 'nav-menus.php' ) ) ), 'move-menu_item' ), esc_attr__( 'Move up' ) ); ?> | <?php printf( '<a href="%s" class="item-move-down" aria-label="%s">&#8595;</a>', wp_nonce_url( add_query_arg( array( 'action' => 'move-down-menu-item', 'menu-item' => $item_id, ), remove_query_arg( $removed_args, admin_url( 'nav-menus.php' ) ) ), 'move-menu_item' ), esc_attr__( 'Move down' ) ); ?> </span> <?php if ( isset( $_GET['edit-menu-item'] ) && $item_id === $_GET['edit-menu-item'] ) { $edit_url = admin_url( 'nav-menus.php' ); } else { $edit_url = add_query_arg( array( 'edit-menu-item' => $item_id, ), remove_query_arg( $removed_args, admin_url( 'nav-menus.php#menu-item-settings-' . $item_id ) ) ); } printf( '<a class="item-edit" id="edit-%s" href="%s" aria-label="%s"><span class="screen-reader-text">%s</span></a>', $item_id, $edit_url, esc_attr__( 'Edit menu item' ), __( 'Edit' ) ); ?> </span> </div> </div> <div class="menu-item-settings wp-clearfix" id="menu-item-settings-<?php echo $item_id; ?>"> <?php if ( 'custom' === $menu_item->type ) : ?> <p class="field-url description description-wide"> <label for="edit-menu-item-url-<?php echo $item_id; ?>"> <?php _e( 'URL' ); ?><br /> <input type="text" id="edit-menu-item-url-<?php echo $item_id; ?>" class="widefat code edit-menu-item-url" name="menu-item-url[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->url ); ?>" /> </label> </p> <?php endif; ?> <p class="description description-wide"> <label for="edit-menu-item-title-<?php echo $item_id; ?>"> <?php _e( 'Navigation Label' ); ?><br /> <input type="text" id="edit-menu-item-title-<?php echo $item_id; ?>" class="widefat edit-menu-item-title" name="menu-item-title[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->title ); ?>" /> </label> </p> <p class="field-title-attribute field-attr-title description description-wide"> <label for="edit-menu-item-attr-title-<?php echo $item_id; ?>"> <?php _e( 'Title Attribute' ); ?><br /> <input type="text" id="edit-menu-item-attr-title-<?php echo $item_id; ?>" class="widefat edit-menu-item-attr-title" name="menu-item-attr-title[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->post_excerpt ); ?>" /> </label> </p> <p class="field-link-target description"> <label for="edit-menu-item-target-<?php echo $item_id; ?>"> <input type="checkbox" id="edit-menu-item-target-<?php echo $item_id; ?>" value="_blank" name="menu-item-target[<?php echo $item_id; ?>]"<?php checked( $menu_item->target, '_blank' ); ?> /> <?php _e( 'Open link in a new tab' ); ?> </label> </p> <p class="field-css-classes description description-thin"> <label for="edit-menu-item-classes-<?php echo $item_id; ?>"> <?php _e( 'CSS Classes (optional)' ); ?><br /> <input type="text" id="edit-menu-item-classes-<?php echo $item_id; ?>" class="widefat code edit-menu-item-classes" name="menu-item-classes[<?php echo $item_id; ?>]" value="<?php echo esc_attr( implode( ' ', $menu_item->classes ) ); ?>" /> </label> </p> <p class="field-xfn description description-thin"> <label for="edit-menu-item-xfn-<?php echo $item_id; ?>"> <?php _e( 'Link Relationship (XFN)' ); ?><br /> <input type="text" id="edit-menu-item-xfn-<?php echo $item_id; ?>" class="widefat code edit-menu-item-xfn" name="menu-item-xfn[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->xfn ); ?>" /> </label> </p> <p class="field-description description description-wide"> <label for="edit-menu-item-description-<?php echo $item_id; ?>"> <?php _e( 'Description' ); ?><br /> <textarea id="edit-menu-item-description-<?php echo $item_id; ?>" class="widefat edit-menu-item-description" rows="3" cols="20" name="menu-item-description[<?php echo $item_id; ?>]"><?php echo esc_html( $menu_item->description ); // textarea_escaped ?></textarea> <span class="description"><?php _e( 'The description will be displayed in the menu if the active theme supports it.' ); ?></span> </label> </p> <?php /** * Fires just before the move buttons of a nav menu item in the menu editor. * * @since 5.4.0 * * @param string $item_id Menu item ID as a numeric string. * @param WP_Post $menu_item Menu item data object. * @param int $depth Depth of menu item. Used for padding. * @param stdClass|null $args An object of menu item arguments. * @param int $current_object_id Nav menu ID. */ do_action( 'wp_nav_menu_item_custom_fields', $item_id, $menu_item, $depth, $args, $current_object_id ); ?> <fieldset class="field-move hide-if-no-js description description-wide"> <span class="field-move-visual-label" aria-hidden="true"><?php _e( 'Move' ); ?></span> <button type="button" class="button-link menus-move menus-move-up" data-dir="up"><?php _e( 'Up one' ); ?></button> <button type="button" class="button-link menus-move menus-move-down" data-dir="down"><?php _e( 'Down one' ); ?></button> <button type="button" class="button-link menus-move menus-move-left" data-dir="left"></button> <button type="button" class="button-link menus-move menus-move-right" data-dir="right"></button> <button type="button" class="button-link menus-move menus-move-top" data-dir="top"><?php _e( 'To the top' ); ?></button> </fieldset> <div class="menu-item-actions description-wide submitbox"> <?php if ( 'custom' !== $menu_item->type && false !== $original_title ) : ?> <p class="link-to-original"> <?php /* translators: %s: Link to menu item's original object. */ printf( __( 'Original: %s' ), '<a href="' . esc_url( $menu_item->url ) . '">' . esc_html( $original_title ) . '</a>' ); ?> </p> <?php endif; ?> <?php printf( '<a class="item-delete submitdelete deletion" id="delete-%s" href="%s">%s</a>', $item_id, wp_nonce_url( add_query_arg( array( 'action' => 'delete-menu-item', 'menu-item' => $item_id, ), admin_url( 'nav-menus.php' ) ), 'delete-menu_item_' . $item_id ), __( 'Remove' ) ); ?> <span class="meta-sep hide-if-no-js"> | </span> <?php printf( '<a class="item-cancel submitcancel hide-if-no-js" id="cancel-%s" href="%s#menu-item-settings-%s">%s</a>', $item_id, esc_url( add_query_arg( array( 'edit-menu-item' => $item_id, 'cancel' => time(), ), admin_url( 'nav-menus.php' ) ) ), $item_id, __( 'Cancel' ) ); ?> </div> <input class="menu-item-data-db-id" type="hidden" name="menu-item-db-id[<?php echo $item_id; ?>]" value="<?php echo $item_id; ?>" /> <input class="menu-item-data-object-id" type="hidden" name="menu-item-object-id[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->object_id ); ?>" /> <input class="menu-item-data-object" type="hidden" name="menu-item-object[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->object ); ?>" /> <input class="menu-item-data-parent-id" type="hidden" name="menu-item-parent-id[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->menu_item_parent ); ?>" /> <input class="menu-item-data-position" type="hidden" name="menu-item-position[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->menu_order ); ?>" /> <input class="menu-item-data-type" type="hidden" name="menu-item-type[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->type ); ?>" /> </div><!-- .menu-item-settings--> <ul class="menu-item-transport"></ul> <?php $output .= ob_get_clean(); } } ``` | Uses | Description | | --- | --- | | [Walker\_Nav\_Menu](walker_nav_menu) wp-includes/class-walker-nav-menu.php | Core class used to implement an HTML list of nav menu items. | | Version | Description | | --- | --- | | [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
programming_docs
wordpress class WP_Customize_Upload_Control {} class WP\_Customize\_Upload\_Control {} ======================================= Customize Upload Control Class. * [WP\_Customize\_Media\_Control](wp_customize_media_control) This class is used with the [Theme Customization API](https://codex.wordpress.org/Theme_Customization_API "Theme Customization API") to allow a user to upload a file on the Theme Customizer in [WordPress 3.4](https://wordpress.org/support/wordpress-version/version-3-4/ "Version 3.4") or newer. or more information on available Theme Customizer controls, see the codex entry for [WP\_Customize\_Manager::add\_control()](wp_customize_manager/add_control "Class Reference/WP Customize Manager/add control") To force a specific image size see: [WP\_Customize\_Cropped\_Image\_Control](wp_customize_cropped_image_control) * [to\_json](wp_customize_upload_control/to_json) β€” Refresh the parameters passed to the JavaScript via JSON. File: `wp-includes/customize/class-wp-customize-upload-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-upload-control.php/) ``` class WP_Customize_Upload_Control extends WP_Customize_Media_Control { /** * Control type. * * @since 3.4.0 * @var string */ public $type = 'upload'; /** * Media control mime type. * * @since 4.1.0 * @var string */ public $mime_type = ''; /** * Button labels. * * @since 4.1.0 * @var array */ public $button_labels = array(); public $removed = ''; // Unused. public $context; // Unused. public $extensions = array(); // Unused. /** * Refresh the parameters passed to the JavaScript via JSON. * * @since 3.4.0 * * @uses WP_Customize_Media_Control::to_json() */ public function to_json() { parent::to_json(); $value = $this->value(); if ( $value ) { // Get the attachment model for the existing file. $attachment_id = attachment_url_to_postid( $value ); if ( $attachment_id ) { $this->json['attachment'] = wp_prepare_attachment_for_js( $attachment_id ); } } } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Media\_Control](wp_customize_media_control) wp-includes/customize/class-wp-customize-media-control.php | Customize Media Control class. | | Used By | Description | | --- | --- | | [WP\_Customize\_Image\_Control](wp_customize_image_control) wp-includes/customize/class-wp-customize-image-control.php | Customize Image Control class. | | Version | Description | | --- | --- | | [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. | wordpress class WP_Sitemaps_Index {} class WP\_Sitemaps\_Index {} ============================ Class [WP\_Sitemaps\_Index](wp_sitemaps_index). Builds the sitemap index page that lists the links to all of the sitemaps. * [\_\_construct](wp_sitemaps_index/__construct) β€” WP\_Sitemaps\_Index constructor. * [get\_index\_url](wp_sitemaps_index/get_index_url) β€” Builds the URL for the sitemap index. * [get\_sitemap\_list](wp_sitemaps_index/get_sitemap_list) β€” Gets a sitemap list for the index. File: `wp-includes/sitemaps/class-wp-sitemaps-index.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps-index.php/) ``` class WP_Sitemaps_Index { /** * The main registry of supported sitemaps. * * @since 5.5.0 * @var WP_Sitemaps_Registry */ protected $registry; /** * Maximum number of sitemaps to include in an index. * * @since 5.5.0 * * @var int Maximum number of sitemaps. */ private $max_sitemaps = 50000; /** * WP_Sitemaps_Index constructor. * * @since 5.5.0 * * @param WP_Sitemaps_Registry $registry Sitemap provider registry. */ public function __construct( WP_Sitemaps_Registry $registry ) { $this->registry = $registry; } /** * Gets a sitemap list for the index. * * @since 5.5.0 * * @return array[] Array of all sitemaps. */ public function get_sitemap_list() { $sitemaps = array(); $providers = $this->registry->get_providers(); /* @var WP_Sitemaps_Provider $provider */ foreach ( $providers as $name => $provider ) { $sitemap_entries = $provider->get_sitemap_entries(); // Prevent issues with array_push and empty arrays on PHP < 7.3. if ( ! $sitemap_entries ) { continue; } // Using array_push is more efficient than array_merge in a loop. array_push( $sitemaps, ...$sitemap_entries ); if ( count( $sitemaps ) >= $this->max_sitemaps ) { break; } } return array_slice( $sitemaps, 0, $this->max_sitemaps, true ); } /** * Builds the URL for the sitemap index. * * @since 5.5.0 * * @global WP_Rewrite $wp_rewrite WordPress rewrite component. * * @return string The sitemap index URL. */ public function get_index_url() { global $wp_rewrite; if ( ! $wp_rewrite->using_permalinks() ) { return home_url( '/?sitemap=index' ); } return home_url( '/wp-sitemap.xml' ); } } ``` | Version | Description | | --- | --- | | [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. | wordpress class Requests_Exception_HTTP_401 {} class Requests\_Exception\_HTTP\_401 {} ======================================= Exception for 401 Unauthorized responses File: `wp-includes/Requests/Exception/HTTP/401.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/401.php/) ``` class Requests_Exception_HTTP_401 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 401; /** * Reason phrase * * @var string */ protected $reason = 'Unauthorized'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_Widget_Pages {} class WP\_Widget\_Pages {} ========================== Core class used to implement a Pages widget. * [WP\_Widget](wp_widget) * [\_\_construct](wp_widget_pages/__construct) β€” Sets up a new Pages widget instance. * [form](wp_widget_pages/form) β€” Outputs the settings form for the Pages widget. * [update](wp_widget_pages/update) β€” Handles updating settings for the current Pages widget instance. * [widget](wp_widget_pages/widget) β€” Outputs the content for the current Pages widget instance. File: `wp-includes/widgets/class-wp-widget-pages.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-pages.php/) ``` class WP_Widget_Pages extends WP_Widget { /** * Sets up a new Pages widget instance. * * @since 2.8.0 */ public function __construct() { $widget_ops = array( 'classname' => 'widget_pages', 'description' => __( 'A list of your site&#8217;s Pages.' ), 'customize_selective_refresh' => true, 'show_instance_in_rest' => true, ); parent::__construct( 'pages', __( 'Pages' ), $widget_ops ); } /** * Outputs the content for the current Pages widget instance. * * @since 2.8.0 * * @param array $args Display arguments including 'before_title', 'after_title', * 'before_widget', and 'after_widget'. * @param array $instance Settings for the current Pages widget instance. */ public function widget( $args, $instance ) { $default_title = __( 'Pages' ); $title = ! empty( $instance['title'] ) ? $instance['title'] : $default_title; /** * Filters the widget title. * * @since 2.6.0 * * @param string $title The widget title. Default 'Pages'. * @param array $instance Array of settings for the current widget. * @param mixed $id_base The widget ID. */ $title = apply_filters( 'widget_title', $title, $instance, $this->id_base ); $sortby = empty( $instance['sortby'] ) ? 'menu_order' : $instance['sortby']; $exclude = empty( $instance['exclude'] ) ? '' : $instance['exclude']; if ( 'menu_order' === $sortby ) { $sortby = 'menu_order, post_title'; } $output = wp_list_pages( /** * Filters the arguments for the Pages widget. * * @since 2.8.0 * @since 4.9.0 Added the `$instance` parameter. * * @see wp_list_pages() * * @param array $args An array of arguments to retrieve the pages list. * @param array $instance Array of settings for the current widget. */ apply_filters( 'widget_pages_args', array( 'title_li' => '', 'echo' => 0, 'sort_column' => $sortby, 'exclude' => $exclude, ), $instance ) ); if ( ! empty( $output ) ) { 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 ) . '">'; } ?> <ul> <?php echo $output; ?> </ul> <?php if ( 'html5' === $format ) { echo '</nav>'; } echo $args['after_widget']; } } /** * Handles updating settings for the current Pages widget instance. * * @since 2.8.0 * * @param array $new_instance New settings for this instance as input by the user via * WP_Widget::form(). * @param array $old_instance Old settings for this instance. * @return array Updated settings to save. */ public function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = sanitize_text_field( $new_instance['title'] ); if ( in_array( $new_instance['sortby'], array( 'post_title', 'menu_order', 'ID' ), true ) ) { $instance['sortby'] = $new_instance['sortby']; } else { $instance['sortby'] = 'menu_order'; } $instance['exclude'] = sanitize_text_field( $new_instance['exclude'] ); return $instance; } /** * Outputs the settings form for the Pages widget. * * @since 2.8.0 * * @param array $instance Current settings. */ public function form( $instance ) { // Defaults. $instance = wp_parse_args( (array) $instance, array( 'sortby' => 'post_title', 'title' => '', 'exclude' => '', ) ); ?> <p> <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $instance['title'] ); ?>" /> </p> <p> <label for="<?php echo esc_attr( $this->get_field_id( 'sortby' ) ); ?>"><?php _e( 'Sort by:' ); ?></label> <select name="<?php echo esc_attr( $this->get_field_name( 'sortby' ) ); ?>" id="<?php echo esc_attr( $this->get_field_id( 'sortby' ) ); ?>" class="widefat"> <option value="post_title"<?php selected( $instance['sortby'], 'post_title' ); ?>><?php _e( 'Page title' ); ?></option> <option value="menu_order"<?php selected( $instance['sortby'], 'menu_order' ); ?>><?php _e( 'Page order' ); ?></option> <option value="ID"<?php selected( $instance['sortby'], 'ID' ); ?>><?php _e( 'Page ID' ); ?></option> </select> </p> <p> <label for="<?php echo esc_attr( $this->get_field_id( 'exclude' ) ); ?>"><?php _e( 'Exclude:' ); ?></label> <input type="text" value="<?php echo esc_attr( $instance['exclude'] ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'exclude' ) ); ?>" id="<?php echo esc_attr( $this->get_field_id( 'exclude' ) ); ?>" class="widefat" /> <br /> <small><?php _e( 'Page IDs, separated by commas.' ); ?></small> </p> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Widget](wp_widget) wp-includes/class-wp-widget.php | Core base class extended to register widgets. | | Version | Description | | --- | --- | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. | wordpress class WP_Customize_Nav_Menu_Auto_Add_Control {} class WP\_Customize\_Nav\_Menu\_Auto\_Add\_Control {} ===================================================== Customize control to represent the auto\_add field for a given menu. * [WP\_Customize\_Control](wp_customize_control) * [content\_template](wp_customize_nav_menu_auto_add_control/content_template) β€” Render the Underscore template for this control. * [render\_content](wp_customize_nav_menu_auto_add_control/render_content) β€” No-op since we're using JS template. File: `wp-includes/customize/class-wp-customize-nav-menu-auto-add-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-auto-add-control.php/) ``` class WP_Customize_Nav_Menu_Auto_Add_Control extends WP_Customize_Control { /** * Type of control, used by JS. * * @since 4.3.0 * @var string */ public $type = 'nav_menu_auto_add'; /** * No-op since we're using JS template. * * @since 4.3.0 */ protected function render_content() {} /** * Render the Underscore template for this control. * * @since 4.3.0 */ protected function content_template() { ?> <# var elementId = _.uniqueId( 'customize-nav-menu-auto-add-control-' ); #> <span class="customize-control-title"><?php _e( 'Menu Options' ); ?></span> <span class="customize-inside-control-row"> <input id="{{ elementId }}" type="checkbox" class="auto_add" /> <label for="{{ elementId }}"> <?php _e( 'Automatically add new top-level pages to this menu' ); ?> </label> </span> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Control](wp_customize_control) wp-includes/class-wp-customize-control.php | Customize Control class. | | Version | Description | | --- | --- | | [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. | wordpress class WP_REST_Settings_Controller {} class WP\_REST\_Settings\_Controller {} ======================================= Core class used to manage a site’s settings via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_settings_controller/__construct) β€” Constructor. * [get\_item](wp_rest_settings_controller/get_item) β€” Retrieves the settings. * [get\_item\_permissions\_check](wp_rest_settings_controller/get_item_permissions_check) β€” Checks if a given request has access to read and manage settings. * [get\_item\_schema](wp_rest_settings_controller/get_item_schema) β€” Retrieves the site setting schema, conforming to JSON Schema. * [get\_registered\_options](wp_rest_settings_controller/get_registered_options) β€” Retrieves all of the registered options for the Settings API. * [prepare\_value](wp_rest_settings_controller/prepare_value) β€” Prepares a value for output based off a schema array. * [register\_routes](wp_rest_settings_controller/register_routes) β€” Registers the routes for the site's settings. * [sanitize\_callback](wp_rest_settings_controller/sanitize_callback) β€” Custom sanitize callback used for all options to allow the use of 'null'. * [set\_additional\_properties\_to\_false](wp_rest_settings_controller/set_additional_properties_to_false) β€” Recursively add additionalProperties = false to all objects in a schema if no additionalProperties setting is specified. β€” deprecated * [update\_item](wp_rest_settings_controller/update_item) β€” Updates settings for the settings object. File: `wp-includes/rest-api/endpoints/class-wp-rest-settings-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-settings-controller.php/) ``` class WP_REST_Settings_Controller extends WP_REST_Controller { /** * Constructor. * * @since 4.7.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'settings'; } /** * Registers the routes for the site's settings. * * @since 4.7.0 * * @see register_rest_route() */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'args' => array(), 'permission_callback' => array( $this, 'get_item_permissions_check' ), ), array( 'methods' => WP_REST_Server::EDITABLE, 'callback' => array( $this, 'update_item' ), 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ), 'permission_callback' => array( $this, 'get_item_permissions_check' ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks if a given request has access to read and manage settings. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return bool True if the request has read access for the item, otherwise false. */ public function get_item_permissions_check( $request ) { return current_user_can( 'manage_options' ); } /** * Retrieves the settings. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return array|WP_Error Array on success, or WP_Error object on failure. */ public function get_item( $request ) { $options = $this->get_registered_options(); $response = array(); foreach ( $options as $name => $args ) { /** * Filters the value of a setting recognized by the REST API. * * Allow hijacking the setting value and overriding the built-in behavior by returning a * non-null value. The returned value will be presented as the setting value instead. * * @since 4.7.0 * * @param mixed $result Value to use for the requested setting. Can be a scalar * matching the registered schema for the setting, or null to * follow the default get_option() behavior. * @param string $name Setting name (as shown in REST API responses). * @param array $args Arguments passed to register_setting() for this setting. */ $response[ $name ] = apply_filters( 'rest_pre_get_setting', null, $name, $args ); if ( is_null( $response[ $name ] ) ) { // Default to a null value as "null" in the response means "not set". $response[ $name ] = get_option( $args['option_name'], $args['schema']['default'] ); } /* * Because get_option() is lossy, we have to * cast values to the type they are registered with. */ $response[ $name ] = $this->prepare_value( $response[ $name ], $args['schema'] ); } return $response; } /** * Prepares a value for output based off a schema array. * * @since 4.7.0 * * @param mixed $value Value to prepare. * @param array $schema Schema to match. * @return mixed The prepared value. */ protected function prepare_value( $value, $schema ) { /* * If the value is not valid by the schema, set the value to null. * Null values are specifically non-destructive, so this will not cause * overwriting the current invalid value to null. */ if ( is_wp_error( rest_validate_value_from_schema( $value, $schema ) ) ) { return null; } return rest_sanitize_value_from_schema( $value, $schema ); } /** * Updates settings for the settings object. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return array|WP_Error Array on success, or error object on failure. */ public function update_item( $request ) { $options = $this->get_registered_options(); $params = $request->get_params(); foreach ( $options as $name => $args ) { if ( ! array_key_exists( $name, $params ) ) { continue; } /** * Filters whether to preempt a setting value update via the REST API. * * Allows hijacking the setting update logic and overriding the built-in behavior by * returning true. * * @since 4.7.0 * * @param bool $result Whether to override the default behavior for updating the * value of a setting. * @param string $name Setting name (as shown in REST API responses). * @param mixed $value Updated setting value. * @param array $args Arguments passed to register_setting() for this setting. */ $updated = apply_filters( 'rest_pre_update_setting', false, $name, $request[ $name ], $args ); if ( $updated ) { continue; } /* * A null value for an option would have the same effect as * deleting the option from the database, and relying on the * default value. */ if ( is_null( $request[ $name ] ) ) { /* * A null value is returned in the response for any option * that has a non-scalar value. * * To protect clients from accidentally including the null * values from a response object in a request, we do not allow * options with values that don't pass validation to be updated to null. * Without this added protection a client could mistakenly * delete all options that have invalid values from the * database. */ if ( is_wp_error( rest_validate_value_from_schema( get_option( $args['option_name'], false ), $args['schema'] ) ) ) { return new WP_Error( 'rest_invalid_stored_value', /* translators: %s: Property name. */ sprintf( __( 'The %s property has an invalid stored value, and cannot be updated to null.' ), $name ), array( 'status' => 500 ) ); } delete_option( $args['option_name'] ); } else { update_option( $args['option_name'], $request[ $name ] ); } } return $this->get_item( $request ); } /** * Retrieves all of the registered options for the Settings API. * * @since 4.7.0 * * @return array Array of registered options. */ protected function get_registered_options() { $rest_options = array(); foreach ( get_registered_settings() as $name => $args ) { if ( empty( $args['show_in_rest'] ) ) { continue; } $rest_args = array(); if ( is_array( $args['show_in_rest'] ) ) { $rest_args = $args['show_in_rest']; } $defaults = array( 'name' => ! empty( $rest_args['name'] ) ? $rest_args['name'] : $name, 'schema' => array(), ); $rest_args = array_merge( $defaults, $rest_args ); $default_schema = array( 'type' => empty( $args['type'] ) ? null : $args['type'], 'description' => empty( $args['description'] ) ? '' : $args['description'], 'default' => isset( $args['default'] ) ? $args['default'] : null, ); $rest_args['schema'] = array_merge( $default_schema, $rest_args['schema'] ); $rest_args['option_name'] = $name; // Skip over settings that don't have a defined type in the schema. if ( empty( $rest_args['schema']['type'] ) ) { continue; } /* * Allow the supported types for settings, as we don't want invalid types * to be updated with arbitrary values that we can't do decent sanitizing for. */ if ( ! in_array( $rest_args['schema']['type'], array( 'number', 'integer', 'string', 'boolean', 'array', 'object' ), true ) ) { continue; } $rest_args['schema'] = rest_default_additional_properties_to_false( $rest_args['schema'] ); $rest_options[ $rest_args['name'] ] = $rest_args; } return $rest_options; } /** * Retrieves the site setting schema, conforming to JSON Schema. * * @since 4.7.0 * * @return array Item schema data. */ public function get_item_schema() { if ( $this->schema ) { return $this->add_additional_fields_schema( $this->schema ); } $options = $this->get_registered_options(); $schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'settings', 'type' => 'object', 'properties' => array(), ); foreach ( $options as $option_name => $option ) { $schema['properties'][ $option_name ] = $option['schema']; $schema['properties'][ $option_name ]['arg_options'] = array( 'sanitize_callback' => array( $this, 'sanitize_callback' ), ); } $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * Custom sanitize callback used for all options to allow the use of 'null'. * * By default, the schema of settings will throw an error if a value is set to * `null` as it's not a valid value for something like "type => string". We * provide a wrapper sanitizer to allow the use of `null`. * * @since 4.7.0 * * @param mixed $value The value for the setting. * @param WP_REST_Request $request The request object. * @param string $param The parameter name. * @return mixed|WP_Error */ public function sanitize_callback( $value, $request, $param ) { if ( is_null( $value ) ) { return $value; } return rest_parse_request_arg( $value, $request, $param ); } /** * Recursively add additionalProperties = false to all objects in a schema * if no additionalProperties setting is specified. * * This is needed to restrict properties of objects in settings values to only * registered items, as the REST API will allow additional properties by * default. * * @since 4.9.0 * @deprecated 6.1.0 Use {@see rest_default_additional_properties_to_false()} instead. * * @param array $schema The schema array. * @return array */ protected function set_additional_properties_to_false( $schema ) { _deprecated_function( __METHOD__, '6.1.0', 'rest_default_additional_properties_to_false()' ); return rest_default_additional_properties_to_false( $schema ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
programming_docs
wordpress class WP_Widget_Calendar {} class WP\_Widget\_Calendar {} ============================= Core class used to implement the Calendar widget. * [WP\_Widget](wp_widget) * [\_\_construct](wp_widget_calendar/__construct) β€” Sets up a new Calendar widget instance. * [form](wp_widget_calendar/form) β€” Outputs the settings form for the Calendar widget. * [update](wp_widget_calendar/update) β€” Handles updating settings for the current Calendar widget instance. * [widget](wp_widget_calendar/widget) β€” Outputs the content for the current Calendar widget instance. File: `wp-includes/widgets/class-wp-widget-calendar.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-calendar.php/) ``` class WP_Widget_Calendar extends WP_Widget { /** * Ensure that the ID attribute only appears in the markup once * * @since 4.4.0 * @var int */ private static $instance = 0; /** * Sets up a new Calendar widget instance. * * @since 2.8.0 */ public function __construct() { $widget_ops = array( 'classname' => 'widget_calendar', 'description' => __( 'A calendar of your site’s posts.' ), 'customize_selective_refresh' => true, 'show_instance_in_rest' => true, ); parent::__construct( 'calendar', __( 'Calendar' ), $widget_ops ); } /** * Outputs the content for the current Calendar widget instance. * * @since 2.8.0 * * @param array $args Display arguments including 'before_title', 'after_title', * 'before_widget', and 'after_widget'. * @param array $instance The settings for the particular instance of the widget. */ public function widget( $args, $instance ) { $title = ! empty( $instance['title'] ) ? $instance['title'] : ''; /** 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']; } if ( 0 === self::$instance ) { echo '<div id="calendar_wrap" class="calendar_wrap">'; } else { echo '<div class="calendar_wrap">'; } get_calendar(); echo '</div>'; echo $args['after_widget']; self::$instance++; } /** * Handles updating settings for the current Calendar widget instance. * * @since 2.8.0 * * @param array $new_instance New settings for this instance as input by the user via * WP_Widget::form(). * @param array $old_instance Old settings for this instance. * @return array Updated settings to save. */ public function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = sanitize_text_field( $new_instance['title'] ); return $instance; } /** * Outputs the settings form for the Calendar widget. * * @since 2.8.0 * * @param array $instance Current settings. */ public function form( $instance ) { $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) ); ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $instance['title'] ); ?>" /> </p> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Widget](wp_widget) wp-includes/class-wp-widget.php | Core base class extended to register widgets. | | Version | Description | | --- | --- | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. | wordpress class WP_Widget_Custom_HTML {} class WP\_Widget\_Custom\_HTML {} ================================= Core class used to implement a Custom HTML widget. * [WP\_Widget](wp_widget) * [\_\_construct](wp_widget_custom_html/__construct) β€” Sets up a new Custom HTML widget instance. * [\_filter\_gallery\_shortcode\_attrs](wp_widget_custom_html/_filter_gallery_shortcode_attrs) β€” Filters gallery shortcode attributes. * [\_register\_one](wp_widget_custom_html/_register_one) β€” Add hooks for enqueueing assets when registering all widget instances of this widget class. * [add\_help\_text](wp_widget_custom_html/add_help_text) β€” Add help text to widgets admin screen. * [enqueue\_admin\_scripts](wp_widget_custom_html/enqueue_admin_scripts) β€” Loads the required scripts and styles for the widget control. * [form](wp_widget_custom_html/form) β€” Outputs the Custom HTML widget settings form. * [render\_control\_template\_scripts](wp_widget_custom_html/render_control_template_scripts) β€” Render form template scripts. * [update](wp_widget_custom_html/update) β€” Handles updating settings for the current Custom HTML widget instance. * [widget](wp_widget_custom_html/widget) β€” Outputs the content 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/) ``` class WP_Widget_Custom_HTML extends WP_Widget { /** * Whether or not the widget has been registered yet. * * @since 4.9.0 * @var bool */ protected $registered = false; /** * Default instance. * * @since 4.8.1 * @var array */ protected $default_instance = array( 'title' => '', 'content' => '', ); /** * Sets up a new Custom HTML widget instance. * * @since 4.8.1 */ 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 ); } /** * Add hooks for enqueueing assets when registering all widget instances of this widget class. * * @since 4.9.0 * * @param int $number Optional. The unique order number of this widget instance * compared to other instances of the same class. Default -1. */ 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' ) ); } /** * 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. * * @since 4.9.0 * * @param array $attrs Attributes. * @return array Attributes. */ public function _filter_gallery_shortcode_attrs( $attrs ) { if ( ! is_singular() && empty( $attrs['id'] ) && empty( $attrs['include'] ) ) { $attrs['id'] = -1; } return $attrs; } /** * Outputs the content for the current Custom HTML widget instance. * * @since 4.8.1 * * @global WP_Post $post Global post object. * * @param array $args Display arguments including 'before_title', 'after_title', * 'before_widget', and 'after_widget'. * @param array $instance Settings for the current Custom HTML widget instance. */ 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']; } /** * Handles updating settings for the current Custom HTML widget instance. * * @since 4.8.1 * * @param array $new_instance New settings for this instance as input by the user via * WP_Widget::form(). * @param array $old_instance Old settings for this instance. * @return array Settings to save or bool false to cancel saving. */ 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; } /** * Loads the required scripts and styles for the widget control. * * @since 4.9.0 */ 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' ); } /** * Outputs the Custom HTML widget settings form. * * @since 4.8.1 * @since 4.9.0 The form contains only hidden sync inputs. For the control UI, see `WP_Widget_Custom_HTML::render_control_template_scripts()`. * * @see WP_Widget_Custom_HTML::render_control_template_scripts() * * @param array $instance Current instance. */ 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 } /** * Render form template scripts. * * @since 4.9.0 */ 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 } /** * Add help text to widgets admin screen. * * @since 4.9.0 */ 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 | | --- | --- | | [WP\_Widget](wp_widget) wp-includes/class-wp-widget.php | Core base class extended to register widgets. | | Version | Description | | --- | --- | | [4.8.1](https://developer.wordpress.org/reference/since/4.8.1/) | Introduced. | wordpress class WP_Widget {} class WP\_Widget {} =================== Core base class extended to register widgets. This class must be extended for each widget, and [WP\_Widget::widget()](wp_widget/widget) must be overridden. If adding widget options, [WP\_Widget::update()](wp_widget/update) and [WP\_Widget::form()](wp_widget/form) should also be overridden. * [\_\_construct](wp_widget/__construct) β€” PHP5 constructor. * [\_get\_display\_callback](wp_widget/_get_display_callback) β€” Retrieves the widget display callback. * [\_get\_form\_callback](wp_widget/_get_form_callback) β€” Retrieves the form callback. * [\_get\_update\_callback](wp_widget/_get_update_callback) β€” Retrieves the widget update callback. * [\_register](wp_widget/_register) β€” Register all widget instances of this widget class. * [\_register\_one](wp_widget/_register_one) β€” Registers an instance of the widget class. * [\_set](wp_widget/_set) β€” Sets the internal order number for the widget instance. * [display\_callback](wp_widget/display_callback) β€” Generates the actual widget content (Do NOT override). * [form](wp_widget/form) β€” Outputs the settings update form. * [form\_callback](wp_widget/form_callback) β€” Generates the widget control form (Do NOT override). * [get\_field\_id](wp_widget/get_field_id) β€” Constructs id attributes for use in WP\_Widget::form() fields. * [get\_field\_name](wp_widget/get_field_name) β€” Constructs name attributes for use in form() fields * [get\_settings](wp_widget/get_settings) β€” Retrieves the settings for all instances of the widget class. * [is\_preview](wp_widget/is_preview) β€” Determines whether the current request is inside the Customizer preview. * [save\_settings](wp_widget/save_settings) β€” Saves the settings for all instances of the widget class. * [update](wp_widget/update) β€” Updates a particular instance of a widget. * [update\_callback](wp_widget/update_callback) β€” Handles changed settings (Do NOT override). * [widget](wp_widget/widget) β€” Echoes the widget content. * [WP\_Widget](wp_widget/wp_widget) β€” PHP4 constructor. β€” deprecated File: `wp-includes/class-wp-widget.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-widget.php/) ``` class WP_Widget { /** * Root ID for all widgets of this type. * * @since 2.8.0 * @var mixed|string */ public $id_base; /** * Name for this widget type. * * @since 2.8.0 * @var string */ public $name; /** * Option name for this widget type. * * @since 2.8.0 * @var string */ public $option_name; /** * Alt option name for this widget type. * * @since 2.8.0 * @var string */ public $alt_option_name; /** * Option array passed to wp_register_sidebar_widget(). * * @since 2.8.0 * @var array */ public $widget_options; /** * Option array passed to wp_register_widget_control(). * * @since 2.8.0 * @var array */ public $control_options; /** * Unique ID number of the current instance. * * @since 2.8.0 * @var bool|int */ public $number = false; /** * Unique ID string of the current instance (id_base-number). * * @since 2.8.0 * @var bool|string */ public $id = false; /** * Whether the widget data has been updated. * * Set to true when the data is updated after a POST submit - ensures it does * not happen twice. * * @since 2.8.0 * @var bool */ public $updated = false; // // Member functions that must be overridden by subclasses. // /** * Echoes the widget content. * * Subclasses should override this function to generate their widget code. * * @since 2.8.0 * * @param array $args Display arguments including 'before_title', 'after_title', * 'before_widget', and 'after_widget'. * @param array $instance The settings for the particular instance of the widget. */ public function widget( $args, $instance ) { die( 'function WP_Widget::widget() must be overridden in a subclass.' ); } /** * Updates a particular instance of a widget. * * This function should check that `$new_instance` is set correctly. The newly-calculated * value of `$instance` should be returned. If false is returned, the instance won't be * saved/updated. * * @since 2.8.0 * * @param array $new_instance New settings for this instance as input by the user via * WP_Widget::form(). * @param array $old_instance Old settings for this instance. * @return array Settings to save or bool false to cancel saving. */ public function update( $new_instance, $old_instance ) { return $new_instance; } /** * Outputs the settings update form. * * @since 2.8.0 * * @param array $instance Current settings. * @return string Default return is 'noform'. */ public function form( $instance ) { echo '<p class="no-options-widget">' . __( 'There are no options for this widget.' ) . '</p>'; return 'noform'; } // Functions you'll need to call. /** * PHP5 constructor. * * @since 2.8.0 * * @param string $id_base Optional. Base ID for the widget, lowercase and unique. If left empty, * a portion of the widget's PHP class name will be used. Has to be unique. * @param string $name Name for the widget displayed on the configuration page. * @param array $widget_options Optional. Widget options. See wp_register_sidebar_widget() for * information on accepted arguments. Default empty array. * @param array $control_options Optional. Widget control options. See wp_register_widget_control() for * information on accepted arguments. Default empty array. */ public function __construct( $id_base, $name, $widget_options = array(), $control_options = array() ) { if ( ! empty( $id_base ) ) { $id_base = strtolower( $id_base ); } else { $id_base = preg_replace( '/(wp_)?widget_/', '', strtolower( get_class( $this ) ) ); } $this->id_base = $id_base; $this->name = $name; $this->option_name = 'widget_' . $this->id_base; $this->widget_options = wp_parse_args( $widget_options, array( 'classname' => str_replace( '\\', '_', $this->option_name ), 'customize_selective_refresh' => false, ) ); $this->control_options = wp_parse_args( $control_options, array( 'id_base' => $this->id_base ) ); } /** * PHP4 constructor. * * @since 2.8.0 * @deprecated 4.3.0 Use __construct() instead. * * @see WP_Widget::__construct() * * @param string $id_base Optional. Base ID for the widget, lowercase and unique. If left empty, * a portion of the widget's PHP class name will be used. Has to be unique. * @param string $name Name for the widget displayed on the configuration page. * @param array $widget_options Optional. Widget options. See wp_register_sidebar_widget() for * information on accepted arguments. Default empty array. * @param array $control_options Optional. Widget control options. See wp_register_widget_control() for * information on accepted arguments. Default empty array. */ public function WP_Widget( $id_base, $name, $widget_options = array(), $control_options = array() ) { _deprecated_constructor( 'WP_Widget', '4.3.0', get_class( $this ) ); WP_Widget::__construct( $id_base, $name, $widget_options, $control_options ); } /** * Constructs name attributes for use in form() fields * * This function should be used in form() methods to create name attributes for fields * to be saved by update() * * @since 2.8.0 * @since 4.4.0 Array format field names are now accepted. * * @param string $field_name Field name. * @return string Name attribute for `$field_name`. */ public function get_field_name( $field_name ) { $pos = strpos( $field_name, '[' ); if ( false !== $pos ) { // Replace the first occurrence of '[' with ']['. $field_name = '[' . substr_replace( $field_name, '][', $pos, strlen( '[' ) ); } else { $field_name = '[' . $field_name . ']'; } return 'widget-' . $this->id_base . '[' . $this->number . ']' . $field_name; } /** * Constructs id attributes for use in WP_Widget::form() fields. * * This function should be used in form() methods to create id attributes * for fields to be saved by WP_Widget::update(). * * @since 2.8.0 * @since 4.4.0 Array format field IDs are now accepted. * * @param string $field_name Field name. * @return string ID attribute for `$field_name`. */ public function get_field_id( $field_name ) { $field_name = str_replace( array( '[]', '[', ']' ), array( '', '-', '' ), $field_name ); $field_name = trim( $field_name, '-' ); return 'widget-' . $this->id_base . '-' . $this->number . '-' . $field_name; } /** * Register all widget instances of this widget class. * * @since 2.8.0 */ public function _register() { $settings = $this->get_settings(); $empty = true; // When $settings is an array-like object, get an intrinsic array for use with array_keys(). if ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) { $settings = $settings->getArrayCopy(); } if ( is_array( $settings ) ) { foreach ( array_keys( $settings ) as $number ) { if ( is_numeric( $number ) ) { $this->_set( $number ); $this->_register_one( $number ); $empty = false; } } } if ( $empty ) { // If there are none, we register the widget's existence with a generic template. $this->_set( 1 ); $this->_register_one(); } } /** * Sets the internal order number for the widget instance. * * @since 2.8.0 * * @param int $number The unique order number of this widget instance compared to other * instances of the same class. */ public function _set( $number ) { $this->number = $number; $this->id = $this->id_base . '-' . $number; } /** * Retrieves the widget display callback. * * @since 2.8.0 * * @return callable Display callback. */ public function _get_display_callback() { return array( $this, 'display_callback' ); } /** * Retrieves the widget update callback. * * @since 2.8.0 * * @return callable Update callback. */ public function _get_update_callback() { return array( $this, 'update_callback' ); } /** * Retrieves the form callback. * * @since 2.8.0 * * @return callable Form callback. */ public function _get_form_callback() { return array( $this, 'form_callback' ); } /** * Determines whether the current request is inside the Customizer preview. * * If true -- the current request is inside the Customizer preview, then * the object cache gets suspended and widgets should check this to decide * whether they should store anything persistently to the object cache, * to transients, or anywhere else. * * @since 3.9.0 * * @global WP_Customize_Manager $wp_customize * * @return bool True if within the Customizer preview, false if not. */ public function is_preview() { global $wp_customize; return ( isset( $wp_customize ) && $wp_customize->is_preview() ); } /** * Generates the actual widget content (Do NOT override). * * Finds the instance and calls WP_Widget::widget(). * * @since 2.8.0 * * @param array $args Display arguments. See WP_Widget::widget() for information * on accepted arguments. * @param int|array $widget_args { * Optional. Internal order number of the widget instance, or array of multi-widget arguments. * Default 1. * * @type int $number Number increment used for multiples of the same widget. * } */ public function display_callback( $args, $widget_args = 1 ) { if ( is_numeric( $widget_args ) ) { $widget_args = array( 'number' => $widget_args ); } $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) ); $this->_set( $widget_args['number'] ); $instances = $this->get_settings(); if ( isset( $instances[ $this->number ] ) ) { $instance = $instances[ $this->number ]; /** * Filters the settings for a particular widget instance. * * Returning false will effectively short-circuit display of the widget. * * @since 2.8.0 * * @param array $instance The current widget instance's settings. * @param WP_Widget $widget The current widget instance. * @param array $args An array of default widget arguments. */ $instance = apply_filters( 'widget_display_callback', $instance, $this, $args ); if ( false === $instance ) { return; } $was_cache_addition_suspended = wp_suspend_cache_addition(); if ( $this->is_preview() && ! $was_cache_addition_suspended ) { wp_suspend_cache_addition( true ); } $this->widget( $args, $instance ); if ( $this->is_preview() ) { wp_suspend_cache_addition( $was_cache_addition_suspended ); } } } /** * Handles changed settings (Do NOT override). * * @since 2.8.0 * * @global array $wp_registered_widgets * * @param int $deprecated Not used. */ public function update_callback( $deprecated = 1 ) { global $wp_registered_widgets; $all_instances = $this->get_settings(); // We need to update the data. if ( $this->updated ) { return; } if ( isset( $_POST['delete_widget'] ) && $_POST['delete_widget'] ) { // Delete the settings for this instance of the widget. if ( isset( $_POST['the-widget-id'] ) ) { $del_id = $_POST['the-widget-id']; } else { return; } if ( isset( $wp_registered_widgets[ $del_id ]['params'][0]['number'] ) ) { $number = $wp_registered_widgets[ $del_id ]['params'][0]['number']; if ( $this->id_base . '-' . $number == $del_id ) { unset( $all_instances[ $number ] ); } } } else { if ( isset( $_POST[ 'widget-' . $this->id_base ] ) && is_array( $_POST[ 'widget-' . $this->id_base ] ) ) { $settings = $_POST[ 'widget-' . $this->id_base ]; } elseif ( isset( $_POST['id_base'] ) && $_POST['id_base'] == $this->id_base ) { $num = $_POST['multi_number'] ? (int) $_POST['multi_number'] : (int) $_POST['widget_number']; $settings = array( $num => array() ); } else { return; } foreach ( $settings as $number => $new_instance ) { $new_instance = stripslashes_deep( $new_instance ); $this->_set( $number ); $old_instance = isset( $all_instances[ $number ] ) ? $all_instances[ $number ] : array(); $was_cache_addition_suspended = wp_suspend_cache_addition(); if ( $this->is_preview() && ! $was_cache_addition_suspended ) { wp_suspend_cache_addition( true ); } $instance = $this->update( $new_instance, $old_instance ); if ( $this->is_preview() ) { wp_suspend_cache_addition( $was_cache_addition_suspended ); } /** * Filters a widget's settings before saving. * * Returning false will effectively short-circuit the widget's ability * to update settings. * * @since 2.8.0 * * @param array $instance The current widget instance's settings. * @param array $new_instance Array of new widget settings. * @param array $old_instance Array of old widget settings. * @param WP_Widget $widget The current widget instance. */ $instance = apply_filters( 'widget_update_callback', $instance, $new_instance, $old_instance, $this ); if ( false !== $instance ) { $all_instances[ $number ] = $instance; } break; // Run only once. } } $this->save_settings( $all_instances ); $this->updated = true; } /** * Generates the widget control form (Do NOT override). * * @since 2.8.0 * * @param int|array $widget_args { * Optional. Internal order number of the widget instance, or array of multi-widget arguments. * Default 1. * * @type int $number Number increment used for multiples of the same widget. * } * @return string|null */ public function form_callback( $widget_args = 1 ) { if ( is_numeric( $widget_args ) ) { $widget_args = array( 'number' => $widget_args ); } $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) ); $all_instances = $this->get_settings(); if ( -1 == $widget_args['number'] ) { // We echo out a form where 'number' can be set later. $this->_set( '__i__' ); $instance = array(); } else { $this->_set( $widget_args['number'] ); $instance = $all_instances[ $widget_args['number'] ]; } /** * Filters the widget instance's settings before displaying the control form. * * Returning false effectively short-circuits display of the control form. * * @since 2.8.0 * * @param array $instance The current widget instance's settings. * @param WP_Widget $widget The current widget instance. */ $instance = apply_filters( 'widget_form_callback', $instance, $this ); $return = null; if ( false !== $instance ) { $return = $this->form( $instance ); /** * Fires at the end of the widget control form. * * Use this hook to add extra fields to the widget form. The hook * is only fired if the value passed to the 'widget_form_callback' * hook is not false. * * Note: If the widget has no form, the text echoed from the default * form method can be hidden using CSS. * * @since 2.8.0 * * @param WP_Widget $widget The widget instance (passed by reference). * @param null $return Return null if new fields are added. * @param array $instance An array of the widget's settings. */ do_action_ref_array( 'in_widget_form', array( &$this, &$return, $instance ) ); } return $return; } /** * Registers an instance of the widget class. * * @since 2.8.0 * * @param int $number Optional. The unique order number of this widget instance * compared to other instances of the same class. Default -1. */ public function _register_one( $number = -1 ) { wp_register_sidebar_widget( $this->id, $this->name, $this->_get_display_callback(), $this->widget_options, array( 'number' => $number ) ); _register_widget_update_callback( $this->id_base, $this->_get_update_callback(), $this->control_options, array( 'number' => -1 ) ); _register_widget_form_callback( $this->id, $this->name, $this->_get_form_callback(), $this->control_options, array( 'number' => $number ) ); } /** * Saves the settings for all instances of the widget class. * * @since 2.8.0 * * @param array $settings Multi-dimensional array of widget instance settings. */ public function save_settings( $settings ) { $settings['_multiwidget'] = 1; update_option( $this->option_name, $settings ); } /** * Retrieves the settings for all instances of the widget class. * * @since 2.8.0 * * @return array Multi-dimensional array of widget instance settings. */ public function get_settings() { $settings = get_option( $this->option_name ); if ( false === $settings ) { $settings = array(); if ( isset( $this->alt_option_name ) ) { // Get settings from alternative (legacy) option. $settings = get_option( $this->alt_option_name, array() ); // Delete the alternative (legacy) option as the new option will be created using `$this->option_name`. delete_option( $this->alt_option_name ); } // Save an option so it can be autoloaded next time. $this->save_settings( $settings ); } if ( ! is_array( $settings ) && ! ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) ) { $settings = array(); } if ( ! empty( $settings ) && ! isset( $settings['_multiwidget'] ) ) { // Old format, convert if single widget. $settings = wp_convert_widget_settings( $this->id_base, $this->option_name, $settings ); } unset( $settings['_multiwidget'], $settings['__i__'] ); return $settings; } } ``` | Used By | Description | | --- | --- | | [WP\_Widget\_Block](wp_widget_block) wp-includes/widgets/class-wp-widget-block.php | Core class used to implement a Block widget. | | [WP\_Widget\_Custom\_HTML](wp_widget_custom_html) wp-includes/widgets/class-wp-widget-custom-html.php | Core class used to implement a Custom HTML widget. | | [WP\_Widget\_Media](wp_widget_media) wp-includes/widgets/class-wp-widget-media.php | Core class that implements a media widget. | | [WP\_Widget\_RSS](wp_widget_rss) wp-includes/widgets/class-wp-widget-rss.php | Core class used to implement a RSS widget. | | [WP\_Widget\_Tag\_Cloud](wp_widget_tag_cloud) wp-includes/widgets/class-wp-widget-tag-cloud.php | Core class used to implement a Tag cloud widget. | | [WP\_Nav\_Menu\_Widget](wp_nav_menu_widget) wp-includes/widgets/class-wp-nav-menu-widget.php | Core class used to implement the Navigation Menu widget. | | [WP\_Widget\_Recent\_Posts](wp_widget_recent_posts) wp-includes/widgets/class-wp-widget-recent-posts.php | Core class used to implement a Recent Posts widget. | | [WP\_Widget\_Recent\_Comments](wp_widget_recent_comments) wp-includes/widgets/class-wp-widget-recent-comments.php | Core class used to implement a Recent Comments widget. | | [WP\_Widget\_Calendar](wp_widget_calendar) wp-includes/widgets/class-wp-widget-calendar.php | Core class used to implement the Calendar widget. | | [WP\_Widget\_Text](wp_widget_text) wp-includes/widgets/class-wp-widget-text.php | Core class used to implement a Text widget. | | [WP\_Widget\_Categories](wp_widget_categories) wp-includes/widgets/class-wp-widget-categories.php | Core class used to implement a Categories widget. | | [WP\_Widget\_Archives](wp_widget_archives) wp-includes/widgets/class-wp-widget-archives.php | Core class used to implement the Archives widget. | | [WP\_Widget\_Meta](wp_widget_meta) wp-includes/widgets/class-wp-widget-meta.php | Core class used to implement a Meta widget. | | [WP\_Widget\_Pages](wp_widget_pages) wp-includes/widgets/class-wp-widget-pages.php | Core class used to implement a Pages widget. | | [WP\_Widget\_Links](wp_widget_links) wp-includes/widgets/class-wp-widget-links.php | Core class used to implement a Links widget. | | [WP\_Widget\_Search](wp_widget_search) wp-includes/widgets/class-wp-widget-search.php | Core class used to implement a Search widget. | | Version | Description | | --- | --- | | [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Moved to its own file from wp-includes/widgets.php | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
programming_docs
wordpress class Requests_Exception_HTTP_Unknown {} class Requests\_Exception\_HTTP\_Unknown {} =========================================== Exception for unknown status responses * [\_\_construct](requests_exception_http_unknown/__construct) β€” Create a new exception File: `wp-includes/Requests/Exception/HTTP/Unknown.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/unknown.php/) ``` class Requests_Exception_HTTP_Unknown extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer|bool Code if available, false if an error occurred */ protected $code = 0; /** * Reason phrase * * @var string */ protected $reason = 'Unknown'; /** * Create a new exception * * If `$data` is an instance of {@see Requests_Response}, uses the status * code from it. Otherwise, sets as 0 * * @param string|null $reason Reason phrase * @param mixed $data Associated data */ public function __construct($reason = null, $data = null) { if ($data instanceof Requests_Response) { $this->code = $data->status_code; } parent::__construct($reason, $data); } } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class Requests_Exception_HTTP_505 {} class Requests\_Exception\_HTTP\_505 {} ======================================= Exception for 505 HTTP Version Not Supported responses File: `wp-includes/Requests/Exception/HTTP/505.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/505.php/) ``` class Requests_Exception_HTTP_505 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 505; /** * Reason phrase * * @var string */ protected $reason = 'HTTP Version Not Supported'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_HTTP_Requests_Hooks {} class WP\_HTTP\_Requests\_Hooks {} ================================== Bridge to connect Requests internal hooks to WordPress actions. * [Requests\_Hooks](requests_hooks) * [\_\_construct](wp_http_requests_hooks/__construct) β€” Constructor. * [dispatch](wp_http_requests_hooks/dispatch) β€” Dispatch a Requests hook to a native WordPress action. File: `wp-includes/class-wp-http-requests-hooks.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-hooks.php/) ``` class WP_HTTP_Requests_Hooks extends Requests_Hooks { /** * Requested URL. * * @var string Requested URL. */ protected $url; /** * WordPress WP_HTTP request data. * * @var array Request data in WP_Http format. */ protected $request = array(); /** * Constructor. * * @param string $url URL to request. * @param array $request Request data in WP_Http format. */ public function __construct( $url, $request ) { $this->url = $url; $this->request = $request; } /** * Dispatch a Requests hook to a native WordPress action. * * @param string $hook Hook name. * @param array $parameters Parameters to pass to callbacks. * @return bool True if hooks were run, false if nothing was hooked. */ public function dispatch( $hook, $parameters = array() ) { $result = parent::dispatch( $hook, $parameters ); // Handle back-compat actions. switch ( $hook ) { case 'curl.before_send': /** This action is documented in wp-includes/class-wp-http-curl.php */ do_action_ref_array( 'http_api_curl', array( &$parameters[0], $this->request, $this->url ) ); break; } /** * Transforms a native Request hook to a WordPress action. * * This action maps Requests internal hook to a native WordPress action. * * @see https://github.com/WordPress/Requests/blob/master/docs/hooks.md * * @since 4.7.0 * * @param array $parameters Parameters from Requests internal hook. * @param array $request Request data in WP_Http format. * @param string $url URL to request. */ do_action_ref_array( "requests-{$hook}", $parameters, $this->request, $this->url ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores return $result; } } ``` | Uses | Description | | --- | --- | | [Requests\_Hooks](requests_hooks) wp-includes/Requests/Hooks.php | Handles adding and dispatching events | | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. | wordpress class WP_Media_List_Table {} class WP\_Media\_List\_Table {} =============================== Core class used to implement displaying media items in a list table. * [WP\_List\_Table](wp_list_table) * [\_\_construct](wp_media_list_table/__construct) β€” Constructor. * [\_get\_row\_actions](wp_media_list_table/_get_row_actions) * [ajax\_user\_can](wp_media_list_table/ajax_user_can) * [column\_author](wp_media_list_table/column_author) β€” Handles the author column output. * [column\_cb](wp_media_list_table/column_cb) β€” Handles the checkbox column output. * [column\_comments](wp_media_list_table/column_comments) β€” Handles the comments column output. * [column\_date](wp_media_list_table/column_date) β€” Handles the date column output. * [column\_default](wp_media_list_table/column_default) β€” Handles output for the default column. * [column\_desc](wp_media_list_table/column_desc) β€” Handles the description column output. * [column\_parent](wp_media_list_table/column_parent) β€” Handles the parent column output. * [column\_title](wp_media_list_table/column_title) β€” Handles the title column output. * [current\_action](wp_media_list_table/current_action) * [display\_rows](wp_media_list_table/display_rows) * [extra\_tablenav](wp_media_list_table/extra_tablenav) * [get\_bulk\_actions](wp_media_list_table/get_bulk_actions) * [get\_columns](wp_media_list_table/get_columns) * [get\_default\_primary\_column\_name](wp_media_list_table/get_default_primary_column_name) β€” Gets the name of the default primary column. * [get\_sortable\_columns](wp_media_list_table/get_sortable_columns) * [get\_views](wp_media_list_table/get_views) * [handle\_row\_actions](wp_media_list_table/handle_row_actions) β€” Generates and displays row action links. * [has\_items](wp_media_list_table/has_items) * [no\_items](wp_media_list_table/no_items) * [prepare\_items](wp_media_list_table/prepare_items) * [views](wp_media_list_table/views) β€” Override parent views so we can use the filter bar display. File: `wp-admin/includes/class-wp-media-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-media-list-table.php/) ``` class WP_Media_List_Table extends WP_List_Table { /** * Holds the number of pending comments for each post. * * @since 4.4.0 * @var array */ protected $comment_pending_count = array(); private $detached; private $is_trash; /** * Constructor. * * @since 3.1.0 * * @see WP_List_Table::__construct() for more information on default arguments. * * @param array $args An associative array of arguments. */ public function __construct( $args = array() ) { $this->detached = ( isset( $_REQUEST['attachment-filter'] ) && 'detached' === $_REQUEST['attachment-filter'] ); $this->modes = array( 'list' => __( 'List view' ), 'grid' => __( 'Grid view' ), ); parent::__construct( array( 'plural' => 'media', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); } /** * @return bool */ public function ajax_user_can() { return current_user_can( 'upload_files' ); } /** * @global string $mode List table view mode. * @global WP_Query $wp_query WordPress Query object. * @global array $post_mime_types * @global array $avail_post_mime_types */ public function prepare_items() { global $mode, $wp_query, $post_mime_types, $avail_post_mime_types; $mode = empty( $_REQUEST['mode'] ) ? 'list' : $_REQUEST['mode']; /* * Exclude attachments scheduled for deletion in the next two hours * if they are for zip packages for interrupted or failed updates. * See File_Upload_Upgrader class. */ $not_in = array(); $crons = _get_cron_array(); if ( is_array( $crons ) ) { foreach ( $crons as $cron ) { if ( isset( $cron['upgrader_scheduled_cleanup'] ) ) { $details = reset( $cron['upgrader_scheduled_cleanup'] ); if ( ! empty( $details['args'][0] ) ) { $not_in[] = (int) $details['args'][0]; } } } } if ( ! empty( $_REQUEST['post__not_in'] ) && is_array( $_REQUEST['post__not_in'] ) ) { $not_in = array_merge( array_values( $_REQUEST['post__not_in'] ), $not_in ); } if ( ! empty( $not_in ) ) { $_REQUEST['post__not_in'] = $not_in; } list( $post_mime_types, $avail_post_mime_types ) = wp_edit_attachments_query( $_REQUEST ); $this->is_trash = isset( $_REQUEST['attachment-filter'] ) && 'trash' === $_REQUEST['attachment-filter']; $this->set_pagination_args( array( 'total_items' => $wp_query->found_posts, 'total_pages' => $wp_query->max_num_pages, 'per_page' => $wp_query->query_vars['posts_per_page'], ) ); update_post_parent_caches( $wp_query->posts ); } /** * @global array $post_mime_types * @global array $avail_post_mime_types * @return array */ protected function get_views() { global $post_mime_types, $avail_post_mime_types; $type_links = array(); $filter = empty( $_GET['attachment-filter'] ) ? '' : $_GET['attachment-filter']; $type_links['all'] = sprintf( '<option value=""%s>%s</option>', selected( $filter, true, false ), __( 'All media items' ) ); foreach ( $post_mime_types as $mime_type => $label ) { if ( ! wp_match_mime_types( $mime_type, $avail_post_mime_types ) ) { continue; } $selected = selected( $filter && 0 === strpos( $filter, 'post_mime_type:' ) && wp_match_mime_types( $mime_type, str_replace( 'post_mime_type:', '', $filter ) ), true, false ); $type_links[ $mime_type ] = sprintf( '<option value="post_mime_type:%s"%s>%s</option>', esc_attr( $mime_type ), $selected, $label[0] ); } $type_links['detached'] = '<option value="detached"' . ( $this->detached ? ' selected="selected"' : '' ) . '>' . _x( 'Unattached', 'media items' ) . '</option>'; $type_links['mine'] = sprintf( '<option value="mine"%s>%s</option>', selected( 'mine' === $filter, true, false ), _x( 'Mine', 'media items' ) ); if ( $this->is_trash || ( defined( 'MEDIA_TRASH' ) && MEDIA_TRASH ) ) { $type_links['trash'] = sprintf( '<option value="trash"%s>%s</option>', selected( 'trash' === $filter, true, false ), _x( 'Trash', 'attachment filter' ) ); } return $type_links; } /** * @return array */ protected function get_bulk_actions() { $actions = array(); if ( MEDIA_TRASH ) { if ( $this->is_trash ) { $actions['untrash'] = __( 'Restore' ); $actions['delete'] = __( 'Delete permanently' ); } else { $actions['trash'] = __( 'Move to Trash' ); } } else { $actions['delete'] = __( 'Delete permanently' ); } if ( $this->detached ) { $actions['attach'] = __( 'Attach' ); } return $actions; } /** * @param string $which */ protected function extra_tablenav( $which ) { if ( 'bar' !== $which ) { return; } ?> <div class="actions"> <?php if ( ! $this->is_trash ) { $this->months_dropdown( 'attachment' ); } /** This action is documented in wp-admin/includes/class-wp-posts-list-table.php */ do_action( 'restrict_manage_posts', $this->screen->post_type, $which ); submit_button( __( 'Filter' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) ); if ( $this->is_trash && $this->has_items() && current_user_can( 'edit_others_posts' ) ) { submit_button( __( 'Empty Trash' ), 'apply', 'delete_all', false ); } ?> </div> <?php } /** * @return string */ public function current_action() { if ( isset( $_REQUEST['found_post_id'] ) && isset( $_REQUEST['media'] ) ) { return 'attach'; } if ( isset( $_REQUEST['parent_post_id'] ) && isset( $_REQUEST['media'] ) ) { return 'detach'; } if ( isset( $_REQUEST['delete_all'] ) || isset( $_REQUEST['delete_all2'] ) ) { return 'delete_all'; } return parent::current_action(); } /** * @return bool */ public function has_items() { return have_posts(); } /** */ public function no_items() { if ( $this->is_trash ) { _e( 'No media files found in Trash.' ); } else { _e( 'No media files found.' ); } } /** * Override parent views so we can use the filter bar display. * * @global string $mode List table view mode. */ public function views() { global $mode; $views = $this->get_views(); $this->screen->render_screen_reader_content( 'heading_views' ); ?> <div class="wp-filter"> <div class="filter-items"> <?php $this->view_switcher( $mode ); ?> <label for="attachment-filter" class="screen-reader-text"><?php _e( 'Filter by type' ); ?></label> <select class="attachment-filters" name="attachment-filter" id="attachment-filter"> <?php if ( ! empty( $views ) ) { foreach ( $views as $class => $view ) { echo "\t$view\n"; } } ?> </select> <?php $this->extra_tablenav( 'bar' ); /** This filter is documented in wp-admin/inclues/class-wp-list-table.php */ $views = apply_filters( "views_{$this->screen->id}", array() ); // Back compat for pre-4.0 view links. if ( ! empty( $views ) ) { echo '<ul class="filter-links">'; foreach ( $views as $class => $view ) { echo "<li class='$class'>$view</li>"; } echo '</ul>'; } ?> </div> <div class="search-form"> <label for="media-search-input" class="media-search-input-label"><?php esc_html_e( 'Search' ); ?></label> <input type="search" id="media-search-input" class="search" name="s" value="<?php _admin_search_query(); ?>"> </div> </div> <?php } /** * @return array */ public function get_columns() { $posts_columns = array(); $posts_columns['cb'] = '<input type="checkbox" />'; /* translators: Column name. */ $posts_columns['title'] = _x( 'File', 'column name' ); $posts_columns['author'] = __( 'Author' ); $taxonomies = get_taxonomies_for_attachments( 'objects' ); $taxonomies = wp_filter_object_list( $taxonomies, array( 'show_admin_column' => true ), 'and', 'name' ); /** * Filters the taxonomy columns for attachments in the Media list table. * * @since 3.5.0 * * @param string[] $taxonomies An array of registered taxonomy names to show for attachments. * @param string $post_type The post type. Default 'attachment'. */ $taxonomies = apply_filters( 'manage_taxonomies_for_attachment_columns', $taxonomies, 'attachment' ); $taxonomies = array_filter( $taxonomies, 'taxonomy_exists' ); foreach ( $taxonomies as $taxonomy ) { if ( 'category' === $taxonomy ) { $column_key = 'categories'; } elseif ( 'post_tag' === $taxonomy ) { $column_key = 'tags'; } else { $column_key = 'taxonomy-' . $taxonomy; } $posts_columns[ $column_key ] = get_taxonomy( $taxonomy )->labels->name; } /* translators: Column name. */ if ( ! $this->detached ) { $posts_columns['parent'] = _x( 'Uploaded to', 'column name' ); if ( post_type_supports( 'attachment', 'comments' ) ) { $posts_columns['comments'] = sprintf( '<span class="vers comment-grey-bubble" title="%1$s" aria-hidden="true"></span><span class="screen-reader-text">%2$s</span>', esc_attr__( 'Comments' ), __( 'Comments' ) ); } } /* translators: Column name. */ $posts_columns['date'] = _x( 'Date', 'column name' ); /** * Filters the Media list table columns. * * @since 2.5.0 * * @param string[] $posts_columns An array of columns displayed in the Media list table. * @param bool $detached Whether the list table contains media not attached * to any posts. Default true. */ return apply_filters( 'manage_media_columns', $posts_columns, $this->detached ); } /** * @return array */ protected function get_sortable_columns() { return array( 'title' => 'title', 'author' => 'author', 'parent' => 'parent', 'comments' => 'comment_count', 'date' => array( 'date', true ), ); } /** * Handles the checkbox column output. * * @since 4.3.0 * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Post $item The current WP_Post object. */ public function column_cb( $item ) { // Restores the more descriptive, specific name for use within this method. $post = $item; if ( current_user_can( 'edit_post', $post->ID ) ) { ?> <label class="screen-reader-text" for="cb-select-<?php echo $post->ID; ?>"> <?php /* translators: %s: Attachment title. */ printf( __( 'Select %s' ), _draft_or_post_title() ); ?> </label> <input type="checkbox" name="media[]" id="cb-select-<?php echo $post->ID; ?>" value="<?php echo $post->ID; ?>" /> <?php } } /** * Handles the title column output. * * @since 4.3.0 * * @param WP_Post $post The current WP_Post object. */ public function column_title( $post ) { list( $mime ) = explode( '/', $post->post_mime_type ); $title = _draft_or_post_title(); $thumb = wp_get_attachment_image( $post->ID, array( 60, 60 ), true, array( 'alt' => '' ) ); $link_start = ''; $link_end = ''; if ( current_user_can( 'edit_post', $post->ID ) && ! $this->is_trash ) { $link_start = sprintf( '<a href="%s" aria-label="%s">', get_edit_post_link( $post->ID ), /* translators: %s: Attachment title. */ esc_attr( sprintf( __( '&#8220;%s&#8221; (Edit)' ), $title ) ) ); $link_end = '</a>'; } $class = $thumb ? ' class="has-media-icon"' : ''; ?> <strong<?php echo $class; ?>> <?php echo $link_start; if ( $thumb ) : ?> <span class="media-icon <?php echo sanitize_html_class( $mime . '-icon' ); ?>"><?php echo $thumb; ?></span> <?php endif; echo $title . $link_end; _media_states( $post ); ?> </strong> <p class="filename"> <span class="screen-reader-text"><?php _e( 'File name:' ); ?> </span> <?php $file = get_attached_file( $post->ID ); echo esc_html( wp_basename( $file ) ); ?> </p> <?php } /** * Handles the author column output. * * @since 4.3.0 * * @param WP_Post $post The current WP_Post object. */ public function column_author( $post ) { printf( '<a href="%s">%s</a>', esc_url( add_query_arg( array( 'author' => get_the_author_meta( 'ID' ) ), 'upload.php' ) ), get_the_author() ); } /** * Handles the description column output. * * @since 4.3.0 * * @param WP_Post $post The current WP_Post object. */ public function column_desc( $post ) { echo has_excerpt() ? $post->post_excerpt : ''; } /** * Handles the date column output. * * @since 4.3.0 * * @param WP_Post $post The current WP_Post object. */ public function column_date( $post ) { if ( '0000-00-00 00:00:00' === $post->post_date ) { $h_time = __( 'Unpublished' ); } else { $time = get_post_timestamp( $post ); $time_diff = time() - $time; if ( $time && $time_diff > 0 && $time_diff < DAY_IN_SECONDS ) { /* translators: %s: Human-readable time difference. */ $h_time = sprintf( __( '%s ago' ), human_time_diff( $time ) ); } else { $h_time = get_the_time( __( 'Y/m/d' ), $post ); } } /** * Filters the published time of an attachment displayed in the Media list table. * * @since 6.0.0 * * @param string $h_time The published time. * @param WP_Post $post Attachment object. * @param string $column_name The column name. */ echo apply_filters( 'media_date_column_time', $h_time, $post, 'date' ); } /** * Handles the parent column output. * * @since 4.3.0 * * @param WP_Post $post The current WP_Post object. */ public function column_parent( $post ) { $user_can_edit = current_user_can( 'edit_post', $post->ID ); if ( $post->post_parent > 0 ) { $parent = get_post( $post->post_parent ); } else { $parent = false; } if ( $parent ) { $title = _draft_or_post_title( $post->post_parent ); $parent_type = get_post_type_object( $parent->post_type ); if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $post->post_parent ) ) { printf( '<strong><a href="%s">%s</a></strong>', get_edit_post_link( $post->post_parent ), $title ); } elseif ( $parent_type && current_user_can( 'read_post', $post->post_parent ) ) { printf( '<strong>%s</strong>', $title ); } else { _e( '(Private post)' ); } if ( $user_can_edit ) : $detach_url = add_query_arg( array( 'parent_post_id' => $post->post_parent, 'media[]' => $post->ID, '_wpnonce' => wp_create_nonce( 'bulk-' . $this->_args['plural'] ), ), 'upload.php' ); printf( '<br /><a href="%s" class="hide-if-no-js detach-from-parent" aria-label="%s">%s</a>', $detach_url, /* translators: %s: Title of the post the attachment is attached to. */ esc_attr( sprintf( __( 'Detach from &#8220;%s&#8221;' ), $title ) ), __( 'Detach' ) ); endif; } else { _e( '(Unattached)' ); ?> <?php if ( $user_can_edit ) { $title = _draft_or_post_title( $post->post_parent ); printf( '<br /><a href="#the-list" onclick="findPosts.open( \'media[]\', \'%s\' ); return false;" class="hide-if-no-js aria-button-if-js" aria-label="%s">%s</a>', $post->ID, /* translators: %s: Attachment title. */ esc_attr( sprintf( __( 'Attach &#8220;%s&#8221; to existing content' ), $title ) ), __( 'Attach' ) ); } } } /** * Handles the comments column output. * * @since 4.3.0 * * @param WP_Post $post The current WP_Post object. */ public function column_comments( $post ) { echo '<div class="post-com-count-wrapper">'; if ( isset( $this->comment_pending_count[ $post->ID ] ) ) { $pending_comments = $this->comment_pending_count[ $post->ID ]; } else { $pending_comments = get_pending_comments_num( $post->ID ); } $this->comments_bubble( $post->ID, $pending_comments ); echo '</div>'; } /** * Handles output for the default column. * * @since 4.3.0 * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Post $item The current WP_Post object. * @param string $column_name Current column name. */ public function column_default( $item, $column_name ) { // Restores the more descriptive, specific name for use within this method. $post = $item; if ( 'categories' === $column_name ) { $taxonomy = 'category'; } elseif ( 'tags' === $column_name ) { $taxonomy = 'post_tag'; } elseif ( 0 === strpos( $column_name, 'taxonomy-' ) ) { $taxonomy = substr( $column_name, 9 ); } else { $taxonomy = false; } if ( $taxonomy ) { $terms = get_the_terms( $post->ID, $taxonomy ); if ( is_array( $terms ) ) { $output = array(); foreach ( $terms as $t ) { $posts_in_term_qv = array(); $posts_in_term_qv['taxonomy'] = $taxonomy; $posts_in_term_qv['term'] = $t->slug; $output[] = sprintf( '<a href="%s">%s</a>', esc_url( add_query_arg( $posts_in_term_qv, 'upload.php' ) ), esc_html( sanitize_term_field( 'name', $t->name, $t->term_id, $taxonomy, 'display' ) ) ); } echo implode( wp_get_list_item_separator(), $output ); } else { echo '<span aria-hidden="true">&#8212;</span><span class="screen-reader-text">' . get_taxonomy( $taxonomy )->labels->no_terms . '</span>'; } return; } /** * Fires for each custom column in the Media list table. * * Custom columns are registered using the {@see 'manage_media_columns'} filter. * * @since 2.5.0 * * @param string $column_name Name of the custom column. * @param int $post_id Attachment ID. */ do_action( 'manage_media_custom_column', $column_name, $post->ID ); } /** * @global WP_Post $post Global post object. */ public function display_rows() { global $post, $wp_query; $post_ids = wp_list_pluck( $wp_query->posts, 'ID' ); reset( $wp_query->posts ); $this->comment_pending_count = get_pending_comments_num( $post_ids ); add_filter( 'the_title', 'esc_html' ); while ( have_posts() ) : the_post(); if ( $this->is_trash && 'trash' !== $post->post_status || ! $this->is_trash && 'trash' === $post->post_status ) { continue; } $post_owner = ( get_current_user_id() === (int) $post->post_author ) ? 'self' : 'other'; ?> <tr id="post-<?php echo $post->ID; ?>" class="<?php echo trim( ' author-' . $post_owner . ' status-' . $post->post_status ); ?>"> <?php $this->single_row_columns( $post ); ?> </tr> <?php endwhile; } /** * Gets the name of the default primary column. * * @since 4.3.0 * * @return string Name of the default primary column, in this case, 'title'. */ protected function get_default_primary_column_name() { return 'title'; } /** * @param WP_Post $post * @param string $att_title * @return array */ private function _get_row_actions( $post, $att_title ) { $actions = array(); if ( $this->detached ) { if ( current_user_can( 'edit_post', $post->ID ) ) { $actions['edit'] = sprintf( '<a href="%s" aria-label="%s">%s</a>', get_edit_post_link( $post->ID ), /* translators: %s: Attachment title. */ esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $att_title ) ), __( 'Edit' ) ); } if ( current_user_can( 'delete_post', $post->ID ) ) { if ( EMPTY_TRASH_DAYS && MEDIA_TRASH ) { $actions['trash'] = sprintf( '<a href="%s" class="submitdelete aria-button-if-js" aria-label="%s">%s</a>', wp_nonce_url( "post.php?action=trash&amp;post=$post->ID", 'trash-post_' . $post->ID ), /* translators: %s: Attachment title. */ esc_attr( sprintf( __( 'Move &#8220;%s&#8221; to the Trash' ), $att_title ) ), _x( 'Trash', 'verb' ) ); } else { $delete_ays = ! MEDIA_TRASH ? " onclick='return showNotice.warn();'" : ''; $actions['delete'] = sprintf( '<a href="%s" class="submitdelete aria-button-if-js"%s aria-label="%s">%s</a>', wp_nonce_url( "post.php?action=delete&amp;post=$post->ID", 'delete-post_' . $post->ID ), $delete_ays, /* translators: %s: Attachment title. */ esc_attr( sprintf( __( 'Delete &#8220;%s&#8221; permanently' ), $att_title ) ), __( 'Delete Permanently' ) ); } } $actions['view'] = sprintf( '<a href="%s" aria-label="%s" rel="bookmark">%s</a>', get_permalink( $post->ID ), /* translators: %s: Attachment title. */ esc_attr( sprintf( __( 'View &#8220;%s&#8221;' ), $att_title ) ), __( 'View' ) ); if ( current_user_can( 'edit_post', $post->ID ) ) { $actions['attach'] = sprintf( '<a href="#the-list" onclick="findPosts.open( \'media[]\', \'%s\' ); return false;" class="hide-if-no-js aria-button-if-js" aria-label="%s">%s</a>', $post->ID, /* translators: %s: Attachment title. */ esc_attr( sprintf( __( 'Attach &#8220;%s&#8221; to existing content' ), $att_title ) ), __( 'Attach' ) ); } } else { if ( current_user_can( 'edit_post', $post->ID ) && ! $this->is_trash ) { $actions['edit'] = sprintf( '<a href="%s" aria-label="%s">%s</a>', get_edit_post_link( $post->ID ), /* translators: %s: Attachment title. */ esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $att_title ) ), __( 'Edit' ) ); } if ( current_user_can( 'delete_post', $post->ID ) ) { if ( $this->is_trash ) { $actions['untrash'] = sprintf( '<a href="%s" class="submitdelete aria-button-if-js" aria-label="%s">%s</a>', wp_nonce_url( "post.php?action=untrash&amp;post=$post->ID", 'untrash-post_' . $post->ID ), /* translators: %s: Attachment title. */ esc_attr( sprintf( __( 'Restore &#8220;%s&#8221; from the Trash' ), $att_title ) ), __( 'Restore' ) ); } elseif ( EMPTY_TRASH_DAYS && MEDIA_TRASH ) { $actions['trash'] = sprintf( '<a href="%s" class="submitdelete aria-button-if-js" aria-label="%s">%s</a>', wp_nonce_url( "post.php?action=trash&amp;post=$post->ID", 'trash-post_' . $post->ID ), /* translators: %s: Attachment title. */ esc_attr( sprintf( __( 'Move &#8220;%s&#8221; to the Trash' ), $att_title ) ), _x( 'Trash', 'verb' ) ); } if ( $this->is_trash || ! EMPTY_TRASH_DAYS || ! MEDIA_TRASH ) { $delete_ays = ( ! $this->is_trash && ! MEDIA_TRASH ) ? " onclick='return showNotice.warn();'" : ''; $actions['delete'] = sprintf( '<a href="%s" class="submitdelete aria-button-if-js"%s aria-label="%s">%s</a>', wp_nonce_url( "post.php?action=delete&amp;post=$post->ID", 'delete-post_' . $post->ID ), $delete_ays, /* translators: %s: Attachment title. */ esc_attr( sprintf( __( 'Delete &#8220;%s&#8221; permanently' ), $att_title ) ), __( 'Delete Permanently' ) ); } } if ( ! $this->is_trash ) { $actions['view'] = sprintf( '<a href="%s" aria-label="%s" rel="bookmark">%s</a>', get_permalink( $post->ID ), /* translators: %s: Attachment title. */ esc_attr( sprintf( __( 'View &#8220;%s&#8221;' ), $att_title ) ), __( 'View' ) ); $actions['copy'] = sprintf( '<span class="copy-to-clipboard-container"><button type="button" class="button-link copy-attachment-url media-library" data-clipboard-text="%s" aria-label="%s">%s</button><span class="success hidden" aria-hidden="true">%s</span></span>', esc_url( wp_get_attachment_url( $post->ID ) ), /* translators: %s: Attachment title. */ esc_attr( sprintf( __( 'Copy &#8220;%s&#8221; URL to clipboard' ), $att_title ) ), __( 'Copy URL to clipboard' ), __( 'Copied!' ) ); } } /** * Filters the action links for each attachment in the Media list table. * * @since 2.8.0 * * @param string[] $actions An array of action links for each attachment. * Default 'Edit', 'Delete Permanently', 'View'. * @param WP_Post $post WP_Post object for the current attachment. * @param bool $detached Whether the list table contains media not attached * to any posts. Default true. */ return apply_filters( 'media_row_actions', $actions, $post, $this->detached ); } /** * Generates and displays row action links. * * @since 4.3.0 * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Post $item Attachment being acted upon. * @param string $column_name Current column name. * @param string $primary Primary column name. * @return string Row actions output for media attachments, or an empty string * if the current column is not the primary column. */ protected function handle_row_actions( $item, $column_name, $primary ) { if ( $primary !== $column_name ) { return ''; } $att_title = _draft_or_post_title(); $actions = $this->_get_row_actions( $item, // WP_Post object for an attachment. $att_title ); return $this->row_actions( $actions ); } } ``` | Uses | Description | | --- | --- | | [WP\_List\_Table](wp_list_table) wp-admin/includes/class-wp-list-table.php | Base class for displaying a list of items in an ajaxified HTML table. | | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Posts_Controller {} class WP\_REST\_Posts\_Controller {} ==================================== Core class to access posts via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_posts_controller/__construct) β€” Constructor. * [can\_access\_password\_content](wp_rest_posts_controller/can_access_password_content) β€” Checks if the user can access password-protected content. * [check\_assign\_terms\_permission](wp_rest_posts_controller/check_assign_terms_permission) β€” Checks whether current user can assign all terms sent with the current request. * [check\_create\_permission](wp_rest_posts_controller/check_create_permission) β€” Checks if a post can be created. * [check\_delete\_permission](wp_rest_posts_controller/check_delete_permission) β€” Checks if a post can be deleted. * [check\_is\_post\_type\_allowed](wp_rest_posts_controller/check_is_post_type_allowed) β€” Checks if a given post type can be viewed or managed. * [check\_password\_required](wp_rest_posts_controller/check_password_required) β€” Overrides the result of the post password check for REST requested posts. * [check\_read\_permission](wp_rest_posts_controller/check_read_permission) β€” Checks if a post can be read. * [check\_status](wp_rest_posts_controller/check_status) β€” Checks whether the status is valid for the given post. * [check\_template](wp_rest_posts_controller/check_template) β€” Checks whether the template is valid for the given post. * [check\_update\_permission](wp_rest_posts_controller/check_update_permission) β€” Checks if a post can be edited. * [create\_item](wp_rest_posts_controller/create_item) β€” Creates a single post. * [create\_item\_permissions\_check](wp_rest_posts_controller/create_item_permissions_check) β€” Checks if a given request has access to create a post. * [delete\_item](wp_rest_posts_controller/delete_item) β€” Deletes a single post. * [delete\_item\_permissions\_check](wp_rest_posts_controller/delete_item_permissions_check) β€” Checks if a given request has access to delete a post. * [get\_available\_actions](wp_rest_posts_controller/get_available_actions) β€” Gets the link relations available for the post and current user. * [get\_collection\_params](wp_rest_posts_controller/get_collection_params) β€” Retrieves the query params for the posts collection. * [get\_item](wp_rest_posts_controller/get_item) β€” Retrieves a single post. * [get\_item\_permissions\_check](wp_rest_posts_controller/get_item_permissions_check) β€” Checks if a given request has access to read a post. * [get\_item\_schema](wp_rest_posts_controller/get_item_schema) β€” Retrieves the post's schema, conforming to JSON Schema. * [get\_items](wp_rest_posts_controller/get_items) β€” Retrieves a collection of posts. * [get\_items\_permissions\_check](wp_rest_posts_controller/get_items_permissions_check) β€” Checks if a given request has access to read posts. * [get\_post](wp_rest_posts_controller/get_post) β€” Gets the post, if the ID is valid. * [get\_schema\_links](wp_rest_posts_controller/get_schema_links) β€” Retrieves Link Description Objects that should be added to the Schema for the posts collection. * [handle\_featured\_media](wp_rest_posts_controller/handle_featured_media) β€” Determines the featured media based on a request param. * [handle\_status\_param](wp_rest_posts_controller/handle_status_param) β€” Determines validity and normalizes the given status parameter. * [handle\_template](wp_rest_posts_controller/handle_template) β€” Sets the template for a post. * [handle\_terms](wp_rest_posts_controller/handle_terms) β€” Updates the post's terms from a REST request. * [prepare\_date\_response](wp_rest_posts_controller/prepare_date_response) β€” Checks the post\_date\_gmt or modified\_gmt and prepare any post or modified date for single post output. * [prepare\_item\_for\_database](wp_rest_posts_controller/prepare_item_for_database) β€” Prepares a single post for create or update. * [prepare\_item\_for\_response](wp_rest_posts_controller/prepare_item_for_response) β€” Prepares a single post output for response. * [prepare\_items\_query](wp_rest_posts_controller/prepare_items_query) β€” Determines the allowed query\_vars for a get\_items() response and prepares them for WP\_Query. * [prepare\_links](wp_rest_posts_controller/prepare_links) β€” Prepares links for the request. * [prepare\_tax\_query](wp_rest_posts_controller/prepare_tax_query) β€” Prepares the 'tax\_query' for a collection of posts. * [prepare\_taxonomy\_limit\_schema](wp_rest_posts_controller/prepare_taxonomy_limit_schema) β€” Prepares the collection schema for including and excluding items by terms. * [protected\_title\_format](wp_rest_posts_controller/protected_title_format) β€” Overwrites the default protected title format. * [register\_routes](wp_rest_posts_controller/register_routes) β€” Registers the routes for posts. * [sanitize\_post\_statuses](wp_rest_posts_controller/sanitize_post_statuses) β€” Sanitizes and validates the list of post statuses, including whether the user can query private statuses. * [update\_item](wp_rest_posts_controller/update_item) β€” Updates a single post. * [update\_item\_permissions\_check](wp_rest_posts_controller/update_item_permissions_check) β€” Checks if a given request has access to update a post. File: `wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php/) ``` class WP_REST_Posts_Controller extends WP_REST_Controller { /** * Post type. * * @since 4.7.0 * @var string */ protected $post_type; /** * Instance of a post meta fields object. * * @since 4.7.0 * @var WP_REST_Post_Meta_Fields */ protected $meta; /** * Passwordless post access permitted. * * @since 5.7.1 * @var int[] */ protected $password_check_passed = array(); /** * Whether the controller supports batching. * * @since 5.9.0 * @var array */ protected $allow_batch = array( 'v1' => true ); /** * Constructor. * * @since 4.7.0 * * @param string $post_type Post type. */ public function __construct( $post_type ) { $this->post_type = $post_type; $obj = get_post_type_object( $post_type ); $this->rest_base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name; $this->namespace = ! empty( $obj->rest_namespace ) ? $obj->rest_namespace : 'wp/v2'; $this->meta = new WP_REST_Post_Meta_Fields( $this->post_type ); } /** * Registers the routes for posts. * * @since 4.7.0 * * @see register_rest_route() */ 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' ), ) ); $schema = $this->get_item_schema(); $get_item_args = array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ); if ( isset( $schema['properties']['password'] ) ) { $get_item_args['password'] = array( 'description' => __( 'The password for the post if it is password protected.' ), 'type' => 'string', ); } register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)', array( 'args' => array( 'id' => array( 'description' => __( 'Unique identifier for the post.' ), 'type' => 'integer', ), ), array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'permission_callback' => array( $this, 'get_item_permissions_check' ), 'args' => $get_item_args, ), 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' => __( 'Whether to bypass Trash and force deletion.' ), ), ), ), 'allow_batch' => $this->allow_batch, 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks if a given request has access to read posts. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { $post_type = get_post_type_object( $this->post_type ); if ( 'edit' === $request['context'] && ! current_user_can( $post_type->cap->edit_posts ) ) { return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit posts in this post type.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Overrides the result of the post password check for REST requested posts. * * Allow users to read the content of password protected posts if they have * previously passed a permission check or if they have the `edit_post` capability * for the post being checked. * * @since 5.7.1 * * @param bool $required Whether the post requires a password check. * @param WP_Post $post The post been password checked. * @return bool Result of password check taking in to account REST API considerations. */ public function check_password_required( $required, $post ) { if ( ! $required ) { return $required; } $post = get_post( $post ); if ( ! $post ) { return $required; } if ( ! empty( $this->password_check_passed[ $post->ID ] ) ) { // Password previously checked and approved. return false; } return ! current_user_can( 'edit_post', $post->ID ); } /** * Retrieves a collection of posts. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { // Ensure a search string is set in case the orderby is set to 'relevance'. if ( ! empty( $request['orderby'] ) && 'relevance' === $request['orderby'] && empty( $request['search'] ) ) { return new WP_Error( 'rest_no_search_term_defined', __( 'You need to define a search term to order by relevance.' ), array( 'status' => 400 ) ); } // Ensure an include parameter is set in case the orderby is set to 'include'. if ( ! empty( $request['orderby'] ) && 'include' === $request['orderby'] && empty( $request['include'] ) ) { return new WP_Error( 'rest_orderby_include_missing_include', __( 'You need to define an include parameter to order by include.' ), array( 'status' => 400 ) ); } // Retrieve the list of registered collection query parameters. $registered = $this->get_collection_params(); $args = array(); /* * 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( 'author' => 'author__in', 'author_exclude' => 'author__not_in', 'exclude' => 'post__not_in', 'include' => 'post__in', 'menu_order' => 'menu_order', 'offset' => 'offset', 'order' => 'order', 'orderby' => 'orderby', 'page' => 'paged', 'parent' => 'post_parent__in', 'parent_exclude' => 'post_parent__not_in', 'search' => 's', 'slug' => 'post_name__in', 'status' => 'post_status', ); /* * For each known parameter which is both registered and present in the request, * set the parameter's value on the query $args. */ foreach ( $parameter_mappings as $api_param => $wp_param ) { if ( isset( $registered[ $api_param ], $request[ $api_param ] ) ) { $args[ $wp_param ] = $request[ $api_param ]; } } // Check for & assign any parameters which require special handling or setting. $args['date_query'] = array(); if ( isset( $registered['before'], $request['before'] ) ) { $args['date_query'][] = array( 'before' => $request['before'], 'column' => 'post_date', ); } if ( isset( $registered['modified_before'], $request['modified_before'] ) ) { $args['date_query'][] = array( 'before' => $request['modified_before'], 'column' => 'post_modified', ); } if ( isset( $registered['after'], $request['after'] ) ) { $args['date_query'][] = array( 'after' => $request['after'], 'column' => 'post_date', ); } if ( isset( $registered['modified_after'], $request['modified_after'] ) ) { $args['date_query'][] = array( 'after' => $request['modified_after'], 'column' => 'post_modified', ); } // Ensure our per_page parameter overrides any provided posts_per_page filter. if ( isset( $registered['per_page'] ) ) { $args['posts_per_page'] = $request['per_page']; } if ( isset( $registered['sticky'], $request['sticky'] ) ) { $sticky_posts = get_option( 'sticky_posts', array() ); if ( ! is_array( $sticky_posts ) ) { $sticky_posts = array(); } if ( $request['sticky'] ) { /* * As post__in will be used to only get sticky posts, * we have to support the case where post__in was already * specified. */ $args['post__in'] = $args['post__in'] ? array_intersect( $sticky_posts, $args['post__in'] ) : $sticky_posts; /* * If we intersected, but there are no post IDs in common, * WP_Query won't return "no posts" for post__in = array() * so we have to fake it a bit. */ if ( ! $args['post__in'] ) { $args['post__in'] = array( 0 ); } } elseif ( $sticky_posts ) { /* * As post___not_in will be used to only get posts that * are not sticky, we have to support the case where post__not_in * was already specified. */ $args['post__not_in'] = array_merge( $args['post__not_in'], $sticky_posts ); } } $args = $this->prepare_tax_query( $args, $request ); // Force the post_type argument, since it's not a user input variable. $args['post_type'] = $this->post_type; /** * Filters WP_Query arguments when querying posts via the REST API. * * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. * * Possible hook names include: * * - `rest_post_query` * - `rest_page_query` * - `rest_attachment_query` * * Enables adding extra arguments or setting defaults for a post collection request. * * @since 4.7.0 * @since 5.7.0 Moved after the `tax_query` query arg is generated. * * @link https://developer.wordpress.org/reference/classes/wp_query/ * * @param array $args Array of arguments for WP_Query. * @param WP_REST_Request $request The REST API request. */ $args = apply_filters( "rest_{$this->post_type}_query", $args, $request ); $query_args = $this->prepare_items_query( $args, $request ); $posts_query = new WP_Query(); $query_result = $posts_query->query( $query_args ); // Allow access to all password protected posts if the context is edit. if ( 'edit' === $request['context'] ) { add_filter( 'post_password_required', array( $this, 'check_password_required' ), 10, 2 ); } $posts = array(); update_post_author_caches( $query_result ); update_post_parent_caches( $query_result ); if ( post_type_supports( $this->post_type, 'thumbnail' ) ) { update_post_thumbnail_cache( $posts_query ); } foreach ( $query_result as $post ) { if ( ! $this->check_read_permission( $post ) ) { continue; } $data = $this->prepare_item_for_response( $post, $request ); $posts[] = $this->prepare_response_for_collection( $data ); } // Reset filter. if ( 'edit' === $request['context'] ) { remove_filter( 'post_password_required', array( $this, 'check_password_required' ) ); } $page = (int) $query_args['paged']; $total_posts = $posts_query->found_posts; if ( $total_posts < 1 && $page > 1 ) { // Out-of-bounds, run the query again without LIMIT for total count. unset( $query_args['paged'] ); $count_query = new WP_Query(); $count_query->query( $query_args ); $total_posts = $count_query->found_posts; } $max_pages = ceil( $total_posts / (int) $posts_query->query_vars['posts_per_page'] ); if ( $page > $max_pages && $total_posts > 0 ) { return new WP_Error( 'rest_post_invalid_page_number', __( 'The page number requested is larger than the number of pages available.' ), array( 'status' => 400 ) ); } $response = rest_ensure_response( $posts ); $response->header( 'X-WP-Total', (int) $total_posts ); $response->header( 'X-WP-TotalPages', (int) $max_pages ); $request_params = $request->get_query_params(); $collection_url = rest_url( rest_get_route_for_post_type_items( $this->post_type ) ); $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; } /** * Gets the post, if the ID is valid. * * @since 4.7.2 * * @param int $id Supplied ID. * @return WP_Post|WP_Error Post object if ID is valid, WP_Error otherwise. */ protected function get_post( $id ) { $error = new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) ); if ( (int) $id <= 0 ) { return $error; } $post = get_post( (int) $id ); if ( empty( $post ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) { return $error; } return $post; } /** * Checks if a given request has access to read a post. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise. */ 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 post.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( $post && ! empty( $request['password'] ) ) { // Check post password, and return error if invalid. if ( ! hash_equals( $post->post_password, $request['password'] ) ) { return new WP_Error( 'rest_post_incorrect_password', __( 'Incorrect post password.' ), array( 'status' => 403 ) ); } } // Allow access to all password protected posts if the context is edit. if ( 'edit' === $request['context'] ) { add_filter( 'post_password_required', array( $this, 'check_password_required' ), 10, 2 ); } if ( $post ) { return $this->check_read_permission( $post ); } return true; } /** * Checks if the user can access password-protected content. * * This method determines whether we need to override the regular password * check in core with a filter. * * @since 4.7.0 * * @param WP_Post $post Post to check against. * @param WP_REST_Request $request Request data to check. * @return bool True if the user can access password-protected content, otherwise false. */ public function can_access_password_content( $post, $request ) { if ( empty( $post->post_password ) ) { // No filter required. return false; } /* * Users always gets access to password protected content in the edit * context if they have the `edit_post` meta capability. */ if ( 'edit' === $request['context'] && current_user_can( 'edit_post', $post->ID ) ) { return true; } // No password, no auth. if ( empty( $request['password'] ) ) { return false; } // Double-check the request password. return hash_equals( $post->post_password, $request['password'] ); } /** * Retrieves a single post. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { $post = $this->get_post( $request['id'] ); if ( is_wp_error( $post ) ) { return $post; } $data = $this->prepare_item_for_response( $post, $request ); $response = rest_ensure_response( $data ); if ( is_post_type_viewable( get_post_type_object( $post->post_type ) ) ) { $response->link_header( 'alternate', get_permalink( $post->ID ), array( 'type' => 'text/html' ) ); } return $response; } /** * Checks if a given request has access to create a post. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise. */ public function create_item_permissions_check( $request ) { if ( ! empty( $request['id'] ) ) { return new WP_Error( 'rest_post_exists', __( 'Cannot create existing post.' ), array( 'status' => 400 ) ); } $post_type = get_post_type_object( $this->post_type ); if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) { return new WP_Error( 'rest_cannot_edit_others', __( 'Sorry, you are not allowed to create posts as this user.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) && ! current_user_can( $post_type->cap->publish_posts ) ) { return new WP_Error( 'rest_cannot_assign_sticky', __( 'Sorry, you are not allowed to make posts sticky.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( ! current_user_can( $post_type->cap->create_posts ) ) { return new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to create posts as this user.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( ! $this->check_assign_terms_permission( $request ) ) { return new WP_Error( 'rest_cannot_assign_term', __( 'Sorry, you are not allowed to assign the provided terms.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Creates a single post. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function create_item( $request ) { if ( ! empty( $request['id'] ) ) { return new WP_Error( 'rest_post_exists', __( 'Cannot create existing post.' ), array( 'status' => 400 ) ); } $prepared_post = $this->prepare_item_for_database( $request ); if ( is_wp_error( $prepared_post ) ) { return $prepared_post; } $prepared_post->post_type = $this->post_type; if ( ! empty( $prepared_post->post_name ) && ! empty( $prepared_post->post_status ) && in_array( $prepared_post->post_status, array( 'draft', 'pending' ), true ) ) { /* * `wp_unique_post_slug()` returns the same * slug for 'draft' or 'pending' posts. * * To ensure that a unique slug is generated, * pass the post data with the 'publish' status. */ $prepared_post->post_name = wp_unique_post_slug( $prepared_post->post_name, $prepared_post->id, 'publish', $prepared_post->post_type, $prepared_post->post_parent ); } $post_id = wp_insert_post( wp_slash( (array) $prepared_post ), true, false ); if ( is_wp_error( $post_id ) ) { if ( 'db_insert_error' === $post_id->get_error_code() ) { $post_id->add_data( array( 'status' => 500 ) ); } else { $post_id->add_data( array( 'status' => 400 ) ); } return $post_id; } $post = get_post( $post_id ); /** * Fires after a single post is created or updated via the REST API. * * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. * * Possible hook names include: * * - `rest_insert_post` * - `rest_insert_page` * - `rest_insert_attachment` * * @since 4.7.0 * * @param WP_Post $post Inserted or updated post object. * @param WP_REST_Request $request Request object. * @param bool $creating True when creating a post, false when updating. */ do_action( "rest_insert_{$this->post_type}", $post, $request, true ); $schema = $this->get_item_schema(); if ( ! empty( $schema['properties']['sticky'] ) ) { if ( ! empty( $request['sticky'] ) ) { stick_post( $post_id ); } else { unstick_post( $post_id ); } } if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) { $this->handle_featured_media( $request['featured_media'], $post_id ); } if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) { set_post_format( $post, $request['format'] ); } if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) { $this->handle_template( $request['template'], $post_id, true ); } $terms_update = $this->handle_terms( $post_id, $request ); if ( is_wp_error( $terms_update ) ) { return $terms_update; } if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { $meta_update = $this->meta->update_value( $request['meta'], $post_id ); if ( is_wp_error( $meta_update ) ) { return $meta_update; } } $post = get_post( $post_id ); $fields_update = $this->update_additional_fields_for_object( $post, $request ); if ( is_wp_error( $fields_update ) ) { return $fields_update; } $request->set_param( 'context', 'edit' ); /** * Fires after a single post is completely created or updated via the REST API. * * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. * * Possible hook names include: * * - `rest_after_insert_post` * - `rest_after_insert_page` * - `rest_after_insert_attachment` * * @since 5.0.0 * * @param WP_Post $post Inserted or updated post object. * @param WP_REST_Request $request Request object. * @param bool $creating True when creating a post, false when updating. */ do_action( "rest_after_insert_{$this->post_type}", $post, $request, true ); wp_after_insert_post( $post, false, null ); $response = $this->prepare_item_for_response( $post, $request ); $response = rest_ensure_response( $response ); $response->set_status( 201 ); $response->header( 'Location', rest_url( rest_get_route_for_post( $post ) ) ); return $response; } /** * Checks if a given request has access to update a post. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise. */ public function update_item_permissions_check( $request ) { $post = $this->get_post( $request['id'] ); if ( is_wp_error( $post ) ) { return $post; } $post_type = get_post_type_object( $this->post_type ); if ( $post && ! $this->check_update_permission( $post ) ) { return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this post.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( ! empty( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( $post_type->cap->edit_others_posts ) ) { return new WP_Error( 'rest_cannot_edit_others', __( 'Sorry, you are not allowed to update posts as this user.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( ! empty( $request['sticky'] ) && ! current_user_can( $post_type->cap->edit_others_posts ) && ! current_user_can( $post_type->cap->publish_posts ) ) { return new WP_Error( 'rest_cannot_assign_sticky', __( 'Sorry, you are not allowed to make posts sticky.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( ! $this->check_assign_terms_permission( $request ) ) { return new WP_Error( 'rest_cannot_assign_term', __( 'Sorry, you are not allowed to assign the provided terms.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Updates a single post. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function update_item( $request ) { $valid_check = $this->get_post( $request['id'] ); if ( is_wp_error( $valid_check ) ) { return $valid_check; } $post_before = get_post( $request['id'] ); $post = $this->prepare_item_for_database( $request ); if ( is_wp_error( $post ) ) { return $post; } if ( ! empty( $post->post_status ) ) { $post_status = $post->post_status; } else { $post_status = $post_before->post_status; } /* * `wp_unique_post_slug()` returns the same * slug for 'draft' or 'pending' posts. * * To ensure that a unique slug is generated, * pass the post data with the 'publish' status. */ if ( ! empty( $post->post_name ) && in_array( $post_status, array( 'draft', 'pending' ), true ) ) { $post_parent = ! empty( $post->post_parent ) ? $post->post_parent : 0; $post->post_name = wp_unique_post_slug( $post->post_name, $post->ID, 'publish', $post->post_type, $post_parent ); } // Convert the post object to an array, otherwise wp_update_post() will expect non-escaped input. $post_id = wp_update_post( wp_slash( (array) $post ), true, false ); if ( is_wp_error( $post_id ) ) { if ( 'db_update_error' === $post_id->get_error_code() ) { $post_id->add_data( array( 'status' => 500 ) ); } else { $post_id->add_data( array( 'status' => 400 ) ); } return $post_id; } $post = get_post( $post_id ); /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */ do_action( "rest_insert_{$this->post_type}", $post, $request, false ); $schema = $this->get_item_schema(); if ( ! empty( $schema['properties']['format'] ) && ! empty( $request['format'] ) ) { set_post_format( $post, $request['format'] ); } if ( ! empty( $schema['properties']['featured_media'] ) && isset( $request['featured_media'] ) ) { $this->handle_featured_media( $request['featured_media'], $post_id ); } if ( ! empty( $schema['properties']['sticky'] ) && isset( $request['sticky'] ) ) { if ( ! empty( $request['sticky'] ) ) { stick_post( $post_id ); } else { unstick_post( $post_id ); } } if ( ! empty( $schema['properties']['template'] ) && isset( $request['template'] ) ) { $this->handle_template( $request['template'], $post->ID ); } $terms_update = $this->handle_terms( $post->ID, $request ); if ( is_wp_error( $terms_update ) ) { return $terms_update; } if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { $meta_update = $this->meta->update_value( $request['meta'], $post->ID ); if ( is_wp_error( $meta_update ) ) { return $meta_update; } } $post = get_post( $post_id ); $fields_update = $this->update_additional_fields_for_object( $post, $request ); if ( is_wp_error( $fields_update ) ) { return $fields_update; } $request->set_param( 'context', 'edit' ); // Filter is fired in WP_REST_Attachments_Controller subclass. if ( 'attachment' === $this->post_type ) { $response = $this->prepare_item_for_response( $post, $request ); return rest_ensure_response( $response ); } /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */ do_action( "rest_after_insert_{$this->post_type}", $post, $request, false ); wp_after_insert_post( $post, true, $post_before ); $response = $this->prepare_item_for_response( $post, $request ); return rest_ensure_response( $response ); } /** * Checks if a given request has access to delete a post. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise. */ public function delete_item_permissions_check( $request ) { $post = $this->get_post( $request['id'] ); if ( is_wp_error( $post ) ) { return $post; } if ( $post && ! $this->check_delete_permission( $post ) ) { return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this post.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Deletes a single post. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function delete_item( $request ) { $post = $this->get_post( $request['id'] ); if ( is_wp_error( $post ) ) { return $post; } $id = $post->ID; $force = (bool) $request['force']; $supports_trash = ( EMPTY_TRASH_DAYS > 0 ); if ( 'attachment' === $post->post_type ) { $supports_trash = $supports_trash && MEDIA_TRASH; } /** * Filters whether a post is trashable. * * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. * * Possible hook names include: * * - `rest_post_trashable` * - `rest_page_trashable` * - `rest_attachment_trashable` * * Pass false to disable Trash support for the post. * * @since 4.7.0 * * @param bool $supports_trash Whether the post type support trashing. * @param WP_Post $post The Post object being considered for trashing support. */ $supports_trash = apply_filters( "rest_{$this->post_type}_trashable", $supports_trash, $post ); if ( ! $this->check_delete_permission( $post ) ) { return new WP_Error( 'rest_user_cannot_delete_post', __( 'Sorry, you are not allowed to delete this post.' ), array( 'status' => rest_authorization_required_code() ) ); } $request->set_param( 'context', 'edit' ); // If we're forcing, then delete permanently. if ( $force ) { $previous = $this->prepare_item_for_response( $post, $request ); $result = wp_delete_post( $id, true ); $response = new WP_REST_Response(); $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data(), ) ); } else { // If we don't support trashing for this type, error out. if ( ! $supports_trash ) { return new WP_Error( 'rest_trash_not_supported', /* translators: %s: force=true */ sprintf( __( "The post does not support trashing. Set '%s' to delete." ), 'force=true' ), array( 'status' => 501 ) ); } // Otherwise, only trash if we haven't already. if ( 'trash' === $post->post_status ) { return new WP_Error( 'rest_already_trashed', __( 'The post has already been deleted.' ), array( 'status' => 410 ) ); } // (Note that internally this falls through to `wp_delete_post()` // if the Trash is disabled.) $result = wp_trash_post( $id ); $post = get_post( $id ); $response = $this->prepare_item_for_response( $post, $request ); } if ( ! $result ) { return new WP_Error( 'rest_cannot_delete', __( 'The post cannot be deleted.' ), array( 'status' => 500 ) ); } /** * Fires immediately after a single post is deleted or trashed via the REST API. * * They dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. * * Possible hook names include: * * - `rest_delete_post` * - `rest_delete_page` * - `rest_delete_attachment` * * @since 4.7.0 * * @param WP_Post $post The deleted or trashed post. * @param WP_REST_Response $response The response data. * @param WP_REST_Request $request The request sent to the API. */ do_action( "rest_delete_{$this->post_type}", $post, $response, $request ); return $response; } /** * Determines the allowed query_vars for a get_items() response and prepares * them for WP_Query. * * @since 4.7.0 * * @param array $prepared_args Optional. Prepared WP_Query arguments. Default empty array. * @param WP_REST_Request $request Optional. Full details about the request. * @return array Items query arguments. */ protected function prepare_items_query( $prepared_args = array(), $request = null ) { $query_args = array(); foreach ( $prepared_args as $key => $value ) { /** * Filters the query_vars used in get_items() for the constructed query. * * The dynamic portion of the hook name, `$key`, refers to the query_var key. * * @since 4.7.0 * * @param string $value The query_var value. */ $query_args[ $key ] = apply_filters( "rest_query_var-{$key}", $value ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores } if ( 'post' !== $this->post_type || ! isset( $query_args['ignore_sticky_posts'] ) ) { $query_args['ignore_sticky_posts'] = true; } // Map to proper WP_Query orderby param. if ( isset( $query_args['orderby'] ) && isset( $request['orderby'] ) ) { $orderby_mappings = array( 'id' => 'ID', 'include' => 'post__in', 'slug' => 'post_name', 'include_slugs' => 'post_name__in', ); if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) { $query_args['orderby'] = $orderby_mappings[ $request['orderby'] ]; } } return $query_args; } /** * Checks the post_date_gmt or modified_gmt and prepare any post or * modified date for single post output. * * @since 4.7.0 * * @param string $date_gmt GMT publication time. * @param string|null $date Optional. Local publication time. Default null. * @return string|null ISO8601/RFC3339 formatted datetime. */ protected function prepare_date_response( $date_gmt, $date = null ) { // Use the date if passed. if ( isset( $date ) ) { return mysql_to_rfc3339( $date ); } // Return null if $date_gmt is empty/zeros. if ( '0000-00-00 00:00:00' === $date_gmt ) { return null; } // Return the formatted datetime. return mysql_to_rfc3339( $date_gmt ); } /** * Prepares a single post for create or update. * * @since 4.7.0 * * @param WP_REST_Request $request Request object. * @return stdClass|WP_Error Post object or WP_Error. */ protected function prepare_item_for_database( $request ) { $prepared_post = new stdClass(); $current_status = ''; // Post ID. if ( isset( $request['id'] ) ) { $existing_post = $this->get_post( $request['id'] ); if ( is_wp_error( $existing_post ) ) { return $existing_post; } $prepared_post->ID = $existing_post->ID; $current_status = $existing_post->post_status; } $schema = $this->get_item_schema(); // Post title. if ( ! empty( $schema['properties']['title'] ) && isset( $request['title'] ) ) { if ( is_string( $request['title'] ) ) { $prepared_post->post_title = $request['title']; } elseif ( ! empty( $request['title']['raw'] ) ) { $prepared_post->post_title = $request['title']['raw']; } } // Post content. if ( ! empty( $schema['properties']['content'] ) && isset( $request['content'] ) ) { if ( is_string( $request['content'] ) ) { $prepared_post->post_content = $request['content']; } elseif ( isset( $request['content']['raw'] ) ) { $prepared_post->post_content = $request['content']['raw']; } } // Post excerpt. if ( ! empty( $schema['properties']['excerpt'] ) && isset( $request['excerpt'] ) ) { if ( is_string( $request['excerpt'] ) ) { $prepared_post->post_excerpt = $request['excerpt']; } elseif ( isset( $request['excerpt']['raw'] ) ) { $prepared_post->post_excerpt = $request['excerpt']['raw']; } } // Post type. if ( empty( $request['id'] ) ) { // Creating new post, use default type for the controller. $prepared_post->post_type = $this->post_type; } else { // Updating a post, use previous type. $prepared_post->post_type = get_post_type( $request['id'] ); } $post_type = get_post_type_object( $prepared_post->post_type ); // Post status. if ( ! empty( $schema['properties']['status'] ) && isset( $request['status'] ) && ( ! $current_status || $current_status !== $request['status'] ) ) { $status = $this->handle_status_param( $request['status'], $post_type ); if ( is_wp_error( $status ) ) { return $status; } $prepared_post->post_status = $status; } // Post date. if ( ! empty( $schema['properties']['date'] ) && ! empty( $request['date'] ) ) { $current_date = isset( $prepared_post->ID ) ? get_post( $prepared_post->ID )->post_date : false; $date_data = rest_get_date_with_gmt( $request['date'] ); if ( ! empty( $date_data ) && $current_date !== $date_data[0] ) { list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data; $prepared_post->edit_date = true; } } elseif ( ! empty( $schema['properties']['date_gmt'] ) && ! empty( $request['date_gmt'] ) ) { $current_date = isset( $prepared_post->ID ) ? get_post( $prepared_post->ID )->post_date_gmt : false; $date_data = rest_get_date_with_gmt( $request['date_gmt'], true ); if ( ! empty( $date_data ) && $current_date !== $date_data[1] ) { list( $prepared_post->post_date, $prepared_post->post_date_gmt ) = $date_data; $prepared_post->edit_date = true; } } // Sending a null date or date_gmt value resets date and date_gmt to their // default values (`0000-00-00 00:00:00`). if ( ( ! empty( $schema['properties']['date_gmt'] ) && $request->has_param( 'date_gmt' ) && null === $request['date_gmt'] ) || ( ! empty( $schema['properties']['date'] ) && $request->has_param( 'date' ) && null === $request['date'] ) ) { $prepared_post->post_date_gmt = null; $prepared_post->post_date = null; } // Post slug. if ( ! empty( $schema['properties']['slug'] ) && isset( $request['slug'] ) ) { $prepared_post->post_name = $request['slug']; } // Author. if ( ! empty( $schema['properties']['author'] ) && ! empty( $request['author'] ) ) { $post_author = (int) $request['author']; if ( get_current_user_id() !== $post_author ) { $user_obj = get_userdata( $post_author ); if ( ! $user_obj ) { return new WP_Error( 'rest_invalid_author', __( 'Invalid author ID.' ), array( 'status' => 400 ) ); } } $prepared_post->post_author = $post_author; } // Post password. if ( ! empty( $schema['properties']['password'] ) && isset( $request['password'] ) ) { $prepared_post->post_password = $request['password']; if ( '' !== $request['password'] ) { if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) { return new WP_Error( 'rest_invalid_field', __( 'A post can not be sticky and have a password.' ), array( 'status' => 400 ) ); } if ( ! empty( $prepared_post->ID ) && is_sticky( $prepared_post->ID ) ) { return new WP_Error( 'rest_invalid_field', __( 'A sticky post can not be password protected.' ), array( 'status' => 400 ) ); } } } if ( ! empty( $schema['properties']['sticky'] ) && ! empty( $request['sticky'] ) ) { if ( ! empty( $prepared_post->ID ) && post_password_required( $prepared_post->ID ) ) { return new WP_Error( 'rest_invalid_field', __( 'A password protected post can not be set to sticky.' ), array( 'status' => 400 ) ); } } // Parent. if ( ! empty( $schema['properties']['parent'] ) && isset( $request['parent'] ) ) { if ( 0 === (int) $request['parent'] ) { $prepared_post->post_parent = 0; } else { $parent = get_post( (int) $request['parent'] ); if ( empty( $parent ) ) { return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post parent ID.' ), array( 'status' => 400 ) ); } $prepared_post->post_parent = (int) $parent->ID; } } // Menu order. if ( ! empty( $schema['properties']['menu_order'] ) && isset( $request['menu_order'] ) ) { $prepared_post->menu_order = (int) $request['menu_order']; } // Comment status. if ( ! empty( $schema['properties']['comment_status'] ) && ! empty( $request['comment_status'] ) ) { $prepared_post->comment_status = $request['comment_status']; } // Ping status. if ( ! empty( $schema['properties']['ping_status'] ) && ! empty( $request['ping_status'] ) ) { $prepared_post->ping_status = $request['ping_status']; } if ( ! empty( $schema['properties']['template'] ) ) { // Force template to null so that it can be handled exclusively by the REST controller. $prepared_post->page_template = null; } /** * Filters a post before it is inserted via the REST API. * * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. * * Possible hook names include: * * - `rest_pre_insert_post` * - `rest_pre_insert_page` * - `rest_pre_insert_attachment` * * @since 4.7.0 * * @param stdClass $prepared_post An object representing a single post prepared * for inserting or updating the database. * @param WP_REST_Request $request Request object. */ return apply_filters( "rest_pre_insert_{$this->post_type}", $prepared_post, $request ); } /** * Checks whether the status is valid for the given post. * * Allows for sending an update request with the current status, even if that status would not be acceptable. * * @since 5.6.0 * * @param string $status The provided status. * @param WP_REST_Request $request The request object. * @param string $param The parameter name. * @return true|WP_Error True if the status is valid, or WP_Error if not. */ public function check_status( $status, $request, $param ) { if ( $request['id'] ) { $post = $this->get_post( $request['id'] ); if ( ! is_wp_error( $post ) && $post->post_status === $status ) { return true; } } $args = $request->get_attributes()['args'][ $param ]; return rest_validate_value_from_schema( $status, $args, $param ); } /** * Determines validity and normalizes the given status parameter. * * @since 4.7.0 * * @param string $post_status Post status. * @param WP_Post_Type $post_type Post type. * @return string|WP_Error Post status or WP_Error if lacking the proper permission. */ protected function handle_status_param( $post_status, $post_type ) { switch ( $post_status ) { case 'draft': case 'pending': break; case 'private': if ( ! current_user_can( $post_type->cap->publish_posts ) ) { return new WP_Error( 'rest_cannot_publish', __( 'Sorry, you are not allowed to create private posts in this post type.' ), array( 'status' => rest_authorization_required_code() ) ); } break; case 'publish': case 'future': if ( ! current_user_can( $post_type->cap->publish_posts ) ) { return new WP_Error( 'rest_cannot_publish', __( 'Sorry, you are not allowed to publish posts in this post type.' ), array( 'status' => rest_authorization_required_code() ) ); } break; default: if ( ! get_post_status_object( $post_status ) ) { $post_status = 'draft'; } break; } return $post_status; } /** * Determines the featured media based on a request param. * * @since 4.7.0 * * @param int $featured_media Featured Media ID. * @param int $post_id Post ID. * @return bool|WP_Error Whether the post thumbnail was successfully deleted, otherwise WP_Error. */ protected function handle_featured_media( $featured_media, $post_id ) { $featured_media = (int) $featured_media; if ( $featured_media ) { $result = set_post_thumbnail( $post_id, $featured_media ); if ( $result ) { return true; } else { return new WP_Error( 'rest_invalid_featured_media', __( 'Invalid featured media ID.' ), array( 'status' => 400 ) ); } } else { return delete_post_thumbnail( $post_id ); } } /** * Checks whether the template is valid for the given post. * * @since 4.9.0 * * @param string $template Page template filename. * @param WP_REST_Request $request Request. * @return bool|WP_Error True if template is still valid or if the same as existing value, or false if template not supported. */ public function check_template( $template, $request ) { if ( ! $template ) { return true; } if ( $request['id'] ) { $post = get_post( $request['id'] ); $current_template = get_page_template_slug( $request['id'] ); } else { $post = null; $current_template = ''; } // Always allow for updating a post to the same template, even if that template is no longer supported. if ( $template === $current_template ) { return true; } // If this is a create request, get_post() will return null and wp theme will fallback to the passed post type. $allowed_templates = wp_get_theme()->get_page_templates( $post, $this->post_type ); if ( isset( $allowed_templates[ $template ] ) ) { return true; } return new WP_Error( 'rest_invalid_param', /* translators: 1: Parameter, 2: List of valid values. */ sprintf( __( '%1$s is not one of %2$s.' ), 'template', implode( ', ', array_keys( $allowed_templates ) ) ) ); } /** * Sets the template for a post. * * @since 4.7.0 * @since 4.9.0 Added the `$validate` parameter. * * @param string $template Page template filename. * @param int $post_id Post ID. * @param bool $validate Whether to validate that the template selected is valid. */ public function handle_template( $template, $post_id, $validate = false ) { if ( $validate && ! array_key_exists( $template, wp_get_theme()->get_page_templates( get_post( $post_id ) ) ) ) { $template = ''; } update_post_meta( $post_id, '_wp_page_template', $template ); } /** * Updates the post's terms from a REST request. * * @since 4.7.0 * * @param int $post_id The post ID to update the terms form. * @param WP_REST_Request $request The request object with post and terms data. * @return null|WP_Error WP_Error on an error assigning any of the terms, otherwise null. */ protected function handle_terms( $post_id, $request ) { $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); foreach ( $taxonomies as $taxonomy ) { $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; if ( ! isset( $request[ $base ] ) ) { continue; } $result = wp_set_object_terms( $post_id, $request[ $base ], $taxonomy->name ); if ( is_wp_error( $result ) ) { return $result; } } } /** * Checks whether current user can assign all terms sent with the current request. * * @since 4.7.0 * * @param WP_REST_Request $request The request object with post and terms data. * @return bool Whether the current user can assign the provided terms. */ protected function check_assign_terms_permission( $request ) { $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); foreach ( $taxonomies as $taxonomy ) { $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; if ( ! isset( $request[ $base ] ) ) { continue; } foreach ( (array) $request[ $base ] as $term_id ) { // Invalid terms will be rejected later. if ( ! get_term( $term_id, $taxonomy->name ) ) { continue; } if ( ! current_user_can( 'assign_term', (int) $term_id ) ) { return false; } } } return true; } /** * Checks if a given post type can be viewed or managed. * * @since 4.7.0 * * @param WP_Post_Type|string $post_type Post type name or object. * @return bool Whether the post type is allowed in REST. */ protected function check_is_post_type_allowed( $post_type ) { if ( ! is_object( $post_type ) ) { $post_type = get_post_type_object( $post_type ); } if ( ! empty( $post_type ) && ! empty( $post_type->show_in_rest ) ) { return true; } return false; } /** * Checks if a post can be read. * * Correctly handles posts with the inherit status. * * @since 4.7.0 * * @param WP_Post $post Post object. * @return bool Whether the post can be read. */ public function check_read_permission( $post ) { $post_type = get_post_type_object( $post->post_type ); if ( ! $this->check_is_post_type_allowed( $post_type ) ) { return false; } // Is the post readable? if ( 'publish' === $post->post_status || current_user_can( 'read_post', $post->ID ) ) { return true; } $post_status_obj = get_post_status_object( $post->post_status ); if ( $post_status_obj && $post_status_obj->public ) { return true; } // Can we read the parent if we're inheriting? if ( 'inherit' === $post->post_status && $post->post_parent > 0 ) { $parent = get_post( $post->post_parent ); if ( $parent ) { return $this->check_read_permission( $parent ); } } /* * If there isn't a parent, but the status is set to inherit, assume * it's published (as per get_post_status()). */ if ( 'inherit' === $post->post_status ) { return true; } return false; } /** * Checks if a post can be edited. * * @since 4.7.0 * * @param WP_Post $post Post object. * @return bool Whether the post can be edited. */ protected function check_update_permission( $post ) { $post_type = get_post_type_object( $post->post_type ); if ( ! $this->check_is_post_type_allowed( $post_type ) ) { return false; } return current_user_can( 'edit_post', $post->ID ); } /** * Checks if a post can be created. * * @since 4.7.0 * * @param WP_Post $post Post object. * @return bool Whether the post can be created. */ protected function check_create_permission( $post ) { $post_type = get_post_type_object( $post->post_type ); if ( ! $this->check_is_post_type_allowed( $post_type ) ) { return false; } return current_user_can( $post_type->cap->create_posts ); } /** * Checks if a post can be deleted. * * @since 4.7.0 * * @param WP_Post $post Post object. * @return bool Whether the post can be deleted. */ protected function check_delete_permission( $post ) { $post_type = get_post_type_object( $post->post_type ); if ( ! $this->check_is_post_type_allowed( $post_type ) ) { return false; } return current_user_can( 'delete_post', $post->ID ); } /** * Prepares a single post output for response. * * @since 4.7.0 * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Post $item Post object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $post = $item; $GLOBALS['post'] = $post; setup_postdata( $post ); $fields = $this->get_fields_for_response( $request ); // Base fields for every post. $data = array(); if ( rest_is_field_included( 'id', $fields ) ) { $data['id'] = $post->ID; } if ( rest_is_field_included( 'date', $fields ) ) { $data['date'] = $this->prepare_date_response( $post->post_date_gmt, $post->post_date ); } if ( rest_is_field_included( 'date_gmt', $fields ) ) { /* * For drafts, `post_date_gmt` may not be set, indicating that the date * of the draft should be updated each time it is saved (see #38883). * In this case, shim the value based on the `post_date` field * with the site's timezone offset applied. */ if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) { $post_date_gmt = get_gmt_from_date( $post->post_date ); } else { $post_date_gmt = $post->post_date_gmt; } $data['date_gmt'] = $this->prepare_date_response( $post_date_gmt ); } if ( rest_is_field_included( 'guid', $fields ) ) { $data['guid'] = array( /** This filter is documented in wp-includes/post-template.php */ 'rendered' => apply_filters( 'get_the_guid', $post->guid, $post->ID ), 'raw' => $post->guid, ); } if ( rest_is_field_included( 'modified', $fields ) ) { $data['modified'] = $this->prepare_date_response( $post->post_modified_gmt, $post->post_modified ); } if ( rest_is_field_included( 'modified_gmt', $fields ) ) { /* * For drafts, `post_modified_gmt` may not be set (see `post_date_gmt` comments * above). In this case, shim the value based on the `post_modified` field * with the site's timezone offset applied. */ if ( '0000-00-00 00:00:00' === $post->post_modified_gmt ) { $post_modified_gmt = gmdate( 'Y-m-d H:i:s', strtotime( $post->post_modified ) - ( get_option( 'gmt_offset' ) * 3600 ) ); } else { $post_modified_gmt = $post->post_modified_gmt; } $data['modified_gmt'] = $this->prepare_date_response( $post_modified_gmt ); } if ( rest_is_field_included( 'password', $fields ) ) { $data['password'] = $post->post_password; } if ( rest_is_field_included( 'slug', $fields ) ) { $data['slug'] = $post->post_name; } if ( rest_is_field_included( 'status', $fields ) ) { $data['status'] = $post->post_status; } if ( rest_is_field_included( 'type', $fields ) ) { $data['type'] = $post->post_type; } if ( rest_is_field_included( 'link', $fields ) ) { $data['link'] = get_permalink( $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' ) ); } $has_password_filter = false; if ( $this->can_access_password_content( $post, $request ) ) { $this->password_check_passed[ $post->ID ] = true; // Allow access to the post, permissions already checked before. add_filter( 'post_password_required', array( $this, 'check_password_required' ), 10, 2 ); $has_password_filter = true; } if ( rest_is_field_included( 'content', $fields ) ) { $data['content'] = array(); } if ( rest_is_field_included( 'content.raw', $fields ) ) { $data['content']['raw'] = $post->post_content; } if ( rest_is_field_included( 'content.rendered', $fields ) ) { /** This filter is documented in wp-includes/post-template.php */ $data['content']['rendered'] = post_password_required( $post ) ? '' : apply_filters( 'the_content', $post->post_content ); } if ( rest_is_field_included( 'content.protected', $fields ) ) { $data['content']['protected'] = (bool) $post->post_password; } if ( rest_is_field_included( 'content.block_version', $fields ) ) { $data['content']['block_version'] = block_version( $post->post_content ); } if ( rest_is_field_included( 'excerpt', $fields ) ) { /** This filter is documented in wp-includes/post-template.php */ $excerpt = apply_filters( 'get_the_excerpt', $post->post_excerpt, $post ); /** This filter is documented in wp-includes/post-template.php */ $excerpt = apply_filters( 'the_excerpt', $excerpt ); $data['excerpt'] = array( 'raw' => $post->post_excerpt, 'rendered' => post_password_required( $post ) ? '' : $excerpt, 'protected' => (bool) $post->post_password, ); } if ( $has_password_filter ) { // Reset filter. remove_filter( 'post_password_required', array( $this, 'check_password_required' ) ); } if ( rest_is_field_included( 'author', $fields ) ) { $data['author'] = (int) $post->post_author; } if ( rest_is_field_included( 'featured_media', $fields ) ) { $data['featured_media'] = (int) get_post_thumbnail_id( $post->ID ); } if ( rest_is_field_included( 'parent', $fields ) ) { $data['parent'] = (int) $post->post_parent; } if ( rest_is_field_included( 'menu_order', $fields ) ) { $data['menu_order'] = (int) $post->menu_order; } if ( rest_is_field_included( 'comment_status', $fields ) ) { $data['comment_status'] = $post->comment_status; } if ( rest_is_field_included( 'ping_status', $fields ) ) { $data['ping_status'] = $post->ping_status; } if ( rest_is_field_included( 'sticky', $fields ) ) { $data['sticky'] = is_sticky( $post->ID ); } if ( rest_is_field_included( 'template', $fields ) ) { $template = get_page_template_slug( $post->ID ); if ( $template ) { $data['template'] = $template; } else { $data['template'] = ''; } } if ( rest_is_field_included( 'format', $fields ) ) { $data['format'] = get_post_format( $post->ID ); // Fill in blank post format. if ( empty( $data['format'] ) ) { $data['format'] = 'standard'; } } if ( rest_is_field_included( 'meta', $fields ) ) { $data['meta'] = $this->meta->get_value( $post->ID, $request ); } $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); foreach ( $taxonomies as $taxonomy ) { $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; if ( rest_is_field_included( $base, $fields ) ) { $terms = get_the_terms( $post, $taxonomy->name ); $data[ $base ] = $terms ? array_values( wp_list_pluck( $terms, 'term_id' ) ) : array(); } } $post_type_obj = get_post_type_object( $post->post_type ); if ( is_post_type_viewable( $post_type_obj ) && $post_type_obj->public ) { $permalink_template_requested = rest_is_field_included( 'permalink_template', $fields ); $generated_slug_requested = rest_is_field_included( 'generated_slug', $fields ); if ( $permalink_template_requested || $generated_slug_requested ) { if ( ! function_exists( 'get_sample_permalink' ) ) { require_once ABSPATH . 'wp-admin/includes/post.php'; } $sample_permalink = get_sample_permalink( $post->ID, $post->post_title, '' ); if ( $permalink_template_requested ) { $data['permalink_template'] = $sample_permalink[0]; } if ( $generated_slug_requested ) { $data['generated_slug'] = $sample_permalink[1]; } } } $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 ); $response->add_links( $links ); if ( ! empty( $links['self']['href'] ) ) { $actions = $this->get_available_actions( $post, $request ); $self = $links['self']['href']; foreach ( $actions as $rel ) { $response->add_link( $rel, $self ); } } } /** * Filters the post data for a REST API response. * * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. * * Possible hook names include: * * - `rest_prepare_post` * - `rest_prepare_page` * - `rest_prepare_attachment` * * @since 4.7.0 * * @param WP_REST_Response $response The response object. * @param WP_Post $post Post object. * @param WP_REST_Request $request Request object. */ return apply_filters( "rest_prepare_{$this->post_type}", $response, $post, $request ); } /** * 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. * * @since 4.7.0 * * @return string Protected title format. */ public function protected_title_format() { return '%s'; } /** * Prepares links for the request. * * @since 4.7.0 * * @param WP_Post $post Post object. * @return array Links for the given post. */ protected function prepare_links( $post ) { // Entity meta. $links = array( 'self' => array( 'href' => rest_url( rest_get_route_for_post( $post->ID ) ), ), 'collection' => array( 'href' => rest_url( rest_get_route_for_post_type_items( $this->post_type ) ), ), 'about' => array( 'href' => rest_url( 'wp/v2/types/' . $this->post_type ), ), ); if ( ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'author' ) ) && ! empty( $post->post_author ) ) { $links['author'] = array( 'href' => rest_url( 'wp/v2/users/' . $post->post_author ), 'embeddable' => true, ); } if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'comments' ) ) { $replies_url = rest_url( 'wp/v2/comments' ); $replies_url = add_query_arg( 'post', $post->ID, $replies_url ); $links['replies'] = array( 'href' => $replies_url, 'embeddable' => true, ); } if ( in_array( $post->post_type, array( 'post', 'page' ), true ) || post_type_supports( $post->post_type, 'revisions' ) ) { $revisions = wp_get_latest_revision_id_and_total_count( $post->ID ); $revisions_count = ! is_wp_error( $revisions ) ? $revisions['count'] : 0; $revisions_base = sprintf( '/%s/%s/%d/revisions', $this->namespace, $this->rest_base, $post->ID ); $links['version-history'] = array( 'href' => rest_url( $revisions_base ), 'count' => $revisions_count, ); if ( $revisions_count > 0 ) { $links['predecessor-version'] = array( 'href' => rest_url( $revisions_base . '/' . $revisions['latest_id'] ), 'id' => $revisions['latest_id'], ); } } $post_type_obj = get_post_type_object( $post->post_type ); if ( $post_type_obj->hierarchical && ! empty( $post->post_parent ) ) { $links['up'] = array( 'href' => rest_url( rest_get_route_for_post( $post->post_parent ) ), 'embeddable' => true, ); } // If we have a featured media, add that. $featured_media = get_post_thumbnail_id( $post->ID ); if ( $featured_media ) { $image_url = rest_url( rest_get_route_for_post( $featured_media ) ); $links['https://api.w.org/featuredmedia'] = array( 'href' => $image_url, 'embeddable' => true, ); } if ( ! in_array( $post->post_type, array( 'attachment', 'nav_menu_item', 'revision' ), true ) ) { $attachments_url = rest_url( rest_get_route_for_post_type_items( 'attachment' ) ); $attachments_url = add_query_arg( 'parent', $post->ID, $attachments_url ); $links['https://api.w.org/attachment'] = array( 'href' => $attachments_url, ); } $taxonomies = get_object_taxonomies( $post->post_type ); if ( ! empty( $taxonomies ) ) { $links['https://api.w.org/term'] = array(); foreach ( $taxonomies as $tax ) { $taxonomy_route = rest_get_route_for_taxonomy_items( $tax ); // Skip taxonomies that are not public. if ( empty( $taxonomy_route ) ) { continue; } $terms_url = add_query_arg( 'post', $post->ID, rest_url( $taxonomy_route ) ); $links['https://api.w.org/term'][] = array( 'href' => $terms_url, 'taxonomy' => $tax, 'embeddable' => true, ); } } return $links; } /** * Gets the link relations available for the post and current user. * * @since 4.9.8 * * @param WP_Post $post Post object. * @param WP_REST_Request $request Request object. * @return array List of link relations. */ protected function get_available_actions( $post, $request ) { if ( 'edit' !== $request['context'] ) { return array(); } $rels = array(); $post_type = get_post_type_object( $post->post_type ); if ( 'attachment' !== $this->post_type && current_user_can( $post_type->cap->publish_posts ) ) { $rels[] = 'https://api.w.org/action-publish'; } if ( current_user_can( 'unfiltered_html' ) ) { $rels[] = 'https://api.w.org/action-unfiltered-html'; } if ( 'post' === $post_type->name ) { if ( current_user_can( $post_type->cap->edit_others_posts ) && current_user_can( $post_type->cap->publish_posts ) ) { $rels[] = 'https://api.w.org/action-sticky'; } } if ( post_type_supports( $post_type->name, 'author' ) ) { if ( current_user_can( $post_type->cap->edit_others_posts ) ) { $rels[] = 'https://api.w.org/action-assign-author'; } } $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); foreach ( $taxonomies as $tax ) { $tax_base = ! empty( $tax->rest_base ) ? $tax->rest_base : $tax->name; $create_cap = is_taxonomy_hierarchical( $tax->name ) ? $tax->cap->edit_terms : $tax->cap->assign_terms; if ( current_user_can( $create_cap ) ) { $rels[] = 'https://api.w.org/action-create-' . $tax_base; } if ( current_user_can( $tax->cap->assign_terms ) ) { $rels[] = 'https://api.w.org/action-assign-' . $tax_base; } } return $rels; } /** * Retrieves the post's schema, conforming to JSON Schema. * * @since 4.7.0 * * @return array Item schema data. */ 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', // Base properties for every Post. 'properties' => array( 'date' => array( 'description' => __( "The date the post was published, in the site's timezone." ), 'type' => array( 'string', 'null' ), 'format' => 'date-time', 'context' => array( 'view', 'edit', 'embed' ), ), 'date_gmt' => array( 'description' => __( 'The date the post was published, as GMT.' ), 'type' => array( 'string', 'null' ), 'format' => 'date-time', 'context' => array( 'view', 'edit' ), ), 'guid' => array( 'description' => __( 'The globally unique identifier for the post.' ), 'type' => 'object', 'context' => array( 'view', 'edit' ), 'readonly' => true, 'properties' => array( 'raw' => array( 'description' => __( 'GUID for the post, as it exists in the database.' ), 'type' => 'string', 'context' => array( 'edit' ), 'readonly' => true, ), 'rendered' => array( 'description' => __( 'GUID for the post, transformed for display.' ), 'type' => 'string', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), ), ), 'id' => array( 'description' => __( 'Unique identifier for the post.' ), 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'link' => array( 'description' => __( 'URL to the post.' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'modified' => array( 'description' => __( "The date the post was last modified, in the site's timezone." ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), 'modified_gmt' => array( 'description' => __( 'The date the post was last modified, as GMT.' ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), 'slug' => array( 'description' => __( 'An alphanumeric identifier for the post unique to its type.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'arg_options' => array( 'sanitize_callback' => array( $this, 'sanitize_slug' ), ), ), 'status' => array( 'description' => __( 'A named status for the post.' ), 'type' => 'string', 'enum' => array_keys( get_post_stati( array( 'internal' => false ) ) ), 'context' => array( 'view', 'edit' ), 'arg_options' => array( 'validate_callback' => array( $this, 'check_status' ), ), ), 'type' => array( 'description' => __( 'Type of post.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'password' => array( 'description' => __( 'A password to protect access to the content and excerpt.' ), 'type' => 'string', 'context' => array( 'edit' ), ), ), ); $post_type_obj = get_post_type_object( $this->post_type ); if ( is_post_type_viewable( $post_type_obj ) && $post_type_obj->public ) { $schema['properties']['permalink_template'] = array( 'description' => __( 'Permalink template for the post.' ), 'type' => 'string', 'context' => array( 'edit' ), 'readonly' => true, ); $schema['properties']['generated_slug'] = array( 'description' => __( 'Slug automatically generated from the post title.' ), 'type' => 'string', 'context' => array( 'edit' ), 'readonly' => true, ); } if ( $post_type_obj->hierarchical ) { $schema['properties']['parent'] = array( 'description' => __( 'The ID for the parent of the post.' ), 'type' => 'integer', 'context' => array( 'view', 'edit' ), ); } $post_type_attributes = array( 'title', 'editor', 'author', 'excerpt', 'thumbnail', 'comments', 'revisions', 'page-attributes', 'post-formats', 'custom-fields', ); $fixed_schemas = array( 'post' => array( 'title', 'editor', 'author', 'excerpt', 'thumbnail', 'comments', 'revisions', 'post-formats', 'custom-fields', ), 'page' => array( 'title', 'editor', 'author', 'excerpt', 'thumbnail', 'comments', 'revisions', 'page-attributes', 'custom-fields', ), 'attachment' => array( 'title', 'author', 'comments', 'revisions', 'custom-fields', ), ); foreach ( $post_type_attributes as $attribute ) { if ( isset( $fixed_schemas[ $this->post_type ] ) && ! in_array( $attribute, $fixed_schemas[ $this->post_type ], true ) ) { continue; } elseif ( ! isset( $fixed_schemas[ $this->post_type ] ) && ! post_type_supports( $this->post_type, $attribute ) ) { continue; } switch ( $attribute ) { case 'title': $schema['properties']['title'] = array( 'description' => __( 'The title for the post.' ), 'type' => 'object', 'context' => array( 'view', 'edit', 'embed' ), 'arg_options' => array( 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database(). 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database(). ), 'properties' => array( 'raw' => array( 'description' => __( 'Title for the post, as it exists in the database.' ), 'type' => 'string', 'context' => array( 'edit' ), ), 'rendered' => array( 'description' => __( 'HTML title for the post, transformed for display.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), ), ); break; case 'editor': $schema['properties']['content'] = array( 'description' => __( 'The content for the post.' ), 'type' => 'object', 'context' => array( 'view', 'edit' ), 'arg_options' => array( 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database(). 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database(). ), 'properties' => array( 'raw' => array( 'description' => __( 'Content for the post, as it exists in the database.' ), 'type' => 'string', 'context' => array( 'edit' ), ), 'rendered' => array( 'description' => __( 'HTML content for the post, transformed for display.' ), 'type' => 'string', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), 'block_version' => array( 'description' => __( 'Version of the content block format used by the post.' ), 'type' => 'integer', 'context' => array( 'edit' ), 'readonly' => true, ), 'protected' => array( 'description' => __( 'Whether the content is protected with a password.' ), 'type' => 'boolean', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), ), ); break; case 'author': $schema['properties']['author'] = array( 'description' => __( 'The ID for the author of the post.' ), 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), ); break; case 'excerpt': $schema['properties']['excerpt'] = array( 'description' => __( 'The excerpt for the post.' ), 'type' => 'object', 'context' => array( 'view', 'edit', 'embed' ), 'arg_options' => array( 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database(). 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database(). ), 'properties' => array( 'raw' => array( 'description' => __( 'Excerpt for the post, as it exists in the database.' ), 'type' => 'string', 'context' => array( 'edit' ), ), 'rendered' => array( 'description' => __( 'HTML excerpt for the post, transformed for display.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'protected' => array( 'description' => __( 'Whether the excerpt is protected with a password.' ), 'type' => 'boolean', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), ), ); break; case 'thumbnail': $schema['properties']['featured_media'] = array( 'description' => __( 'The ID of the featured media for the post.' ), 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), ); break; case 'comments': $schema['properties']['comment_status'] = array( 'description' => __( 'Whether or not comments are open on the post.' ), 'type' => 'string', 'enum' => array( 'open', 'closed' ), 'context' => array( 'view', 'edit' ), ); $schema['properties']['ping_status'] = array( 'description' => __( 'Whether or not the post can be pinged.' ), 'type' => 'string', 'enum' => array( 'open', 'closed' ), 'context' => array( 'view', 'edit' ), ); break; case 'page-attributes': $schema['properties']['menu_order'] = array( 'description' => __( 'The order of the post in relation to other posts.' ), 'type' => 'integer', 'context' => array( 'view', 'edit' ), ); break; case 'post-formats': // Get the native post formats and remove the array keys. $formats = array_values( get_post_format_slugs() ); $schema['properties']['format'] = array( 'description' => __( 'The format for the post.' ), 'type' => 'string', 'enum' => $formats, 'context' => array( 'view', 'edit' ), ); break; case 'custom-fields': $schema['properties']['meta'] = $this->meta->get_field_schema(); break; } } if ( 'post' === $this->post_type ) { $schema['properties']['sticky'] = array( 'description' => __( 'Whether or not the post should be treated as sticky.' ), 'type' => 'boolean', 'context' => array( 'view', 'edit' ), ); } $schema['properties']['template'] = array( 'description' => __( 'The theme file to use to display the post.' ), 'type' => 'string', 'context' => array( 'view', 'edit' ), 'arg_options' => array( 'validate_callback' => array( $this, 'check_template' ), ), ); $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); foreach ( $taxonomies as $taxonomy ) { $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; if ( array_key_exists( $base, $schema['properties'] ) ) { $taxonomy_field_name_with_conflict = ! empty( $taxonomy->rest_base ) ? 'rest_base' : 'name'; _doing_it_wrong( 'register_taxonomy', sprintf( /* translators: 1: The taxonomy name, 2: The property name, either 'rest_base' or 'name', 3: The conflicting value. */ __( 'The "%1$s" taxonomy "%2$s" property (%3$s) conflicts with an existing property on the REST API Posts Controller. Specify a custom "rest_base" when registering the taxonomy to avoid this error.' ), $taxonomy->name, $taxonomy_field_name_with_conflict, $base ), '5.4.0' ); } $schema['properties'][ $base ] = array( /* translators: %s: Taxonomy name. */ 'description' => sprintf( __( 'The terms assigned to the post in the %s taxonomy.' ), $taxonomy->name ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), 'context' => array( 'view', 'edit' ), ); } $schema_links = $this->get_schema_links(); if ( $schema_links ) { $schema['links'] = $schema_links; } // Take a snapshot of which fields are in the schema pre-filtering. $schema_fields = array_keys( $schema['properties'] ); /** * Filters the post's schema. * * The dynamic portion of the filter, `$this->post_type`, refers to the * post type slug for the controller. * * Possible hook names include: * * - `rest_post_item_schema` * - `rest_page_item_schema` * - `rest_attachment_item_schema` * * @since 5.4.0 * * @param array $schema Item schema data. */ $schema = apply_filters( "rest_{$this->post_type}_item_schema", $schema ); // Emit a _doing_it_wrong warning if user tries to add new properties using this filter. $new_fields = array_diff( array_keys( $schema['properties'] ), $schema_fields ); if ( count( $new_fields ) > 0 ) { _doing_it_wrong( __METHOD__, sprintf( /* translators: %s: register_rest_field */ __( 'Please use %s to add new schema properties.' ), 'register_rest_field' ), '5.4.0' ); } $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves Link Description Objects that should be added to the Schema for the posts collection. * * @since 4.9.8 * * @return array */ protected function get_schema_links() { $href = rest_url( "{$this->namespace}/{$this->rest_base}/{id}" ); $links = array(); if ( 'attachment' !== $this->post_type ) { $links[] = array( 'rel' => 'https://api.w.org/action-publish', 'title' => __( 'The current user can publish this post.' ), 'href' => $href, 'targetSchema' => array( 'type' => 'object', 'properties' => array( 'status' => array( 'type' => 'string', 'enum' => array( 'publish', 'future' ), ), ), ), ); } $links[] = array( 'rel' => 'https://api.w.org/action-unfiltered-html', 'title' => __( 'The current user can post unfiltered HTML markup and JavaScript.' ), 'href' => $href, 'targetSchema' => array( 'type' => 'object', 'properties' => array( 'content' => array( 'raw' => array( 'type' => 'string', ), ), ), ), ); if ( 'post' === $this->post_type ) { $links[] = array( 'rel' => 'https://api.w.org/action-sticky', 'title' => __( 'The current user can sticky this post.' ), 'href' => $href, 'targetSchema' => array( 'type' => 'object', 'properties' => array( 'sticky' => array( 'type' => 'boolean', ), ), ), ); } if ( post_type_supports( $this->post_type, 'author' ) ) { $links[] = array( 'rel' => 'https://api.w.org/action-assign-author', 'title' => __( 'The current user can change the author on this post.' ), 'href' => $href, 'targetSchema' => array( 'type' => 'object', 'properties' => array( 'author' => array( 'type' => 'integer', ), ), ), ); } $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); foreach ( $taxonomies as $tax ) { $tax_base = ! empty( $tax->rest_base ) ? $tax->rest_base : $tax->name; /* translators: %s: Taxonomy name. */ $assign_title = sprintf( __( 'The current user can assign terms in the %s taxonomy.' ), $tax->name ); /* translators: %s: Taxonomy name. */ $create_title = sprintf( __( 'The current user can create terms in the %s taxonomy.' ), $tax->name ); $links[] = array( 'rel' => 'https://api.w.org/action-assign-' . $tax_base, 'title' => $assign_title, 'href' => $href, 'targetSchema' => array( 'type' => 'object', 'properties' => array( $tax_base => array( 'type' => 'array', 'items' => array( 'type' => 'integer', ), ), ), ), ); $links[] = array( 'rel' => 'https://api.w.org/action-create-' . $tax_base, 'title' => $create_title, 'href' => $href, 'targetSchema' => array( 'type' => 'object', 'properties' => array( $tax_base => array( 'type' => 'array', 'items' => array( 'type' => 'integer', ), ), ), ), ); } return $links; } /** * Retrieves the query params for the posts collection. * * @since 4.7.0 * @since 5.4.0 The `tax_relation` query parameter was added. * @since 5.7.0 The `modified_after` and `modified_before` query parameters were added. * * @return array Collection parameters. */ public function get_collection_params() { $query_params = parent::get_collection_params(); $query_params['context']['default'] = 'view'; $query_params['after'] = array( 'description' => __( 'Limit response to posts published after a given ISO8601 compliant date.' ), 'type' => 'string', 'format' => 'date-time', ); $query_params['modified_after'] = array( 'description' => __( 'Limit response to posts modified after a given ISO8601 compliant date.' ), 'type' => 'string', 'format' => 'date-time', ); if ( post_type_supports( $this->post_type, 'author' ) ) { $query_params['author'] = array( 'description' => __( 'Limit result set to posts assigned to specific authors.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), 'default' => array(), ); $query_params['author_exclude'] = array( 'description' => __( 'Ensure result set excludes posts assigned to specific authors.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), 'default' => array(), ); } $query_params['before'] = array( 'description' => __( 'Limit response to posts published before a given ISO8601 compliant date.' ), 'type' => 'string', 'format' => 'date-time', ); $query_params['modified_before'] = array( 'description' => __( 'Limit response to posts modified before a given ISO8601 compliant date.' ), 'type' => 'string', 'format' => 'date-time', ); $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 ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) { $query_params['menu_order'] = array( 'description' => __( 'Limit result set to posts with a specific menu_order value.' ), 'type' => 'integer', ); } $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' => 'desc', 'enum' => array( 'asc', 'desc' ), ); $query_params['orderby'] = array( 'description' => __( 'Sort collection by post attribute.' ), 'type' => 'string', 'default' => 'date', 'enum' => array( 'author', 'date', 'id', 'include', 'modified', 'parent', 'relevance', 'slug', 'include_slugs', 'title', ), ); if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) { $query_params['orderby']['enum'][] = 'menu_order'; } $post_type = get_post_type_object( $this->post_type ); if ( $post_type->hierarchical || 'attachment' === $this->post_type ) { $query_params['parent'] = array( 'description' => __( 'Limit result set to items with particular parent IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), 'default' => array(), ); $query_params['parent_exclude'] = array( 'description' => __( 'Limit result set to all items except those of a particular parent ID.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), 'default' => array(), ); } $query_params['slug'] = array( 'description' => __( 'Limit result set to posts with one or more specific slugs.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), ); $query_params['status'] = array( 'default' => 'publish', 'description' => __( 'Limit result set to posts assigned one or more statuses.' ), 'type' => 'array', 'items' => array( 'enum' => array_merge( array_keys( get_post_stati() ), array( 'any' ) ), 'type' => 'string', ), 'sanitize_callback' => array( $this, 'sanitize_post_statuses' ), ); $query_params = $this->prepare_taxonomy_limit_schema( $query_params ); if ( 'post' === $this->post_type ) { $query_params['sticky'] = array( 'description' => __( 'Limit result set to items that are sticky.' ), 'type' => 'boolean', ); } /** * Filters collection parameters for the posts controller. * * The dynamic part of the filter `$this->post_type` refers to the post * type slug for the controller. * * This filter registers the collection parameter, but does not map the * collection parameter to an internal WP_Query parameter. Use the * `rest_{$this->post_type}_query` filter to set WP_Query parameters. * * @since 4.7.0 * * @param array $query_params JSON Schema-formatted collection parameters. * @param WP_Post_Type $post_type Post type object. */ return apply_filters( "rest_{$this->post_type}_collection_params", $query_params, $post_type ); } /** * Sanitizes and validates the list of post statuses, including whether the * user can query private statuses. * * @since 4.7.0 * * @param string|array $statuses One or more post statuses. * @param WP_REST_Request $request Full details about the request. * @param string $parameter Additional parameter to pass to validation. * @return array|WP_Error A list of valid statuses, otherwise WP_Error object. */ public function sanitize_post_statuses( $statuses, $request, $parameter ) { $statuses = wp_parse_slug_list( $statuses ); // The default status is different in WP_REST_Attachments_Controller. $attributes = $request->get_attributes(); $default_status = $attributes['args']['status']['default']; foreach ( $statuses as $status ) { if ( $status === $default_status ) { continue; } $post_type_obj = get_post_type_object( $this->post_type ); if ( current_user_can( $post_type_obj->cap->edit_posts ) || 'private' === $status && current_user_can( $post_type_obj->cap->read_private_posts ) ) { $result = rest_validate_request_arg( $status, $request, $parameter ); if ( is_wp_error( $result ) ) { return $result; } } else { return new WP_Error( 'rest_forbidden_status', __( 'Status is forbidden.' ), array( 'status' => rest_authorization_required_code() ) ); } } return $statuses; } /** * Prepares the 'tax_query' for a collection of posts. * * @since 5.7.0 * * @param array $args WP_Query arguments. * @param WP_REST_Request $request Full details about the request. * @return array Updated query arguments. */ private function prepare_tax_query( array $args, WP_REST_Request $request ) { $relation = $request['tax_relation']; if ( $relation ) { $args['tax_query'] = array( 'relation' => $relation ); } $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); foreach ( $taxonomies as $taxonomy ) { $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; $tax_include = $request[ $base ]; $tax_exclude = $request[ $base . '_exclude' ]; if ( $tax_include ) { $terms = array(); $include_children = false; $operator = 'IN'; if ( rest_is_array( $tax_include ) ) { $terms = $tax_include; } elseif ( rest_is_object( $tax_include ) ) { $terms = empty( $tax_include['terms'] ) ? array() : $tax_include['terms']; $include_children = ! empty( $tax_include['include_children'] ); if ( isset( $tax_include['operator'] ) && 'AND' === $tax_include['operator'] ) { $operator = 'AND'; } } if ( $terms ) { $args['tax_query'][] = array( 'taxonomy' => $taxonomy->name, 'field' => 'term_id', 'terms' => $terms, 'include_children' => $include_children, 'operator' => $operator, ); } } if ( $tax_exclude ) { $terms = array(); $include_children = false; if ( rest_is_array( $tax_exclude ) ) { $terms = $tax_exclude; } elseif ( rest_is_object( $tax_exclude ) ) { $terms = empty( $tax_exclude['terms'] ) ? array() : $tax_exclude['terms']; $include_children = ! empty( $tax_exclude['include_children'] ); } if ( $terms ) { $args['tax_query'][] = array( 'taxonomy' => $taxonomy->name, 'field' => 'term_id', 'terms' => $terms, 'include_children' => $include_children, 'operator' => 'NOT IN', ); } } } return $args; } /** * Prepares the collection schema for including and excluding items by terms. * * @since 5.7.0 * * @param array $query_params Collection schema. * @return array Updated schema. */ private function prepare_taxonomy_limit_schema( array $query_params ) { $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); if ( ! $taxonomies ) { return $query_params; } $query_params['tax_relation'] = array( 'description' => __( 'Limit result set based on relationship between multiple taxonomies.' ), 'type' => 'string', 'enum' => array( 'AND', 'OR' ), ); $limit_schema = array( 'type' => array( 'object', 'array' ), 'oneOf' => array( array( 'title' => __( 'Term ID List' ), 'description' => __( 'Match terms with the listed IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), ), array( 'title' => __( 'Term ID Taxonomy Query' ), 'description' => __( 'Perform an advanced term query.' ), 'type' => 'object', 'properties' => array( 'terms' => array( 'description' => __( 'Term IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), 'default' => array(), ), 'include_children' => array( 'description' => __( 'Whether to include child terms in the terms limiting the result set.' ), 'type' => 'boolean', 'default' => false, ), ), 'additionalProperties' => false, ), ), ); $include_schema = array_merge( array( /* translators: %s: Taxonomy name. */ 'description' => __( 'Limit result set to items with specific terms assigned in the %s taxonomy.' ), ), $limit_schema ); // 'operator' is supported only for 'include' queries. $include_schema['oneOf'][1]['properties']['operator'] = array( 'description' => __( 'Whether items must be assigned all or any of the specified terms.' ), 'type' => 'string', 'enum' => array( 'AND', 'OR' ), 'default' => 'OR', ); $exclude_schema = array_merge( array( /* translators: %s: Taxonomy name. */ 'description' => __( 'Limit result set to items except those with specific terms assigned in the %s taxonomy.' ), ), $limit_schema ); foreach ( $taxonomies as $taxonomy ) { $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; $base_exclude = $base . '_exclude'; $query_params[ $base ] = $include_schema; $query_params[ $base ]['description'] = sprintf( $query_params[ $base ]['description'], $base ); $query_params[ $base_exclude ] = $exclude_schema; $query_params[ $base_exclude ]['description'] = sprintf( $query_params[ $base_exclude ]['description'], $base ); if ( ! $taxonomy->hierarchical ) { unset( $query_params[ $base ]['oneOf'][1]['properties']['include_children'] ); unset( $query_params[ $base_exclude ]['oneOf'][1]['properties']['include_children'] ); } } return $query_params; } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Used By | Description | | --- | --- | | [WP\_REST\_Menu\_Items\_Controller](wp_rest_menu_items_controller) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Core class to access nav items via the REST API. | | [WP\_REST\_Blocks\_Controller](wp_rest_blocks_controller) wp-includes/rest-api/endpoints/class-wp-rest-blocks-controller.php | Controller which provides a REST endpoint for the editor to read, create, edit and delete reusable blocks. Blocks are stored as posts with the wp\_block post type. | | [WP\_REST\_Attachments\_Controller](wp_rest_attachments_controller) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Core controller used to access attachments via the REST API. | | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Controller {} class WP\_REST\_Controller {} ============================= Core base controller for managing and interacting with REST API items. * [add\_additional\_fields\_schema](wp_rest_controller/add_additional_fields_schema) β€” Adds the schema from additional fields to a schema array. * [add\_additional\_fields\_to\_object](wp_rest_controller/add_additional_fields_to_object) β€” Adds the values from additional fields to a data object. * [create\_item](wp_rest_controller/create_item) β€” Creates one item from the collection. * [create\_item\_permissions\_check](wp_rest_controller/create_item_permissions_check) β€” Checks if a given request has access to create items. * [delete\_item](wp_rest_controller/delete_item) β€” Deletes one item from the collection. * [delete\_item\_permissions\_check](wp_rest_controller/delete_item_permissions_check) β€” Checks if a given request has access to delete a specific item. * [filter\_response\_by\_context](wp_rest_controller/filter_response_by_context) β€” Filters a response based on the context defined in the schema. * [get\_additional\_fields](wp_rest_controller/get_additional_fields) β€” Retrieves all of the registered additional fields for a given object-type. * [get\_collection\_params](wp_rest_controller/get_collection_params) β€” Retrieves the query params for the collections. * [get\_context\_param](wp_rest_controller/get_context_param) β€” Retrieves the magical context param. * [get\_endpoint\_args\_for\_item\_schema](wp_rest_controller/get_endpoint_args_for_item_schema) β€” Retrieves an array of endpoint arguments from the item schema for the controller. * [get\_fields\_for\_response](wp_rest_controller/get_fields_for_response) β€” Gets an array of fields to be included on the response. * [get\_item](wp_rest_controller/get_item) β€” Retrieves one item from the collection. * [get\_item\_permissions\_check](wp_rest_controller/get_item_permissions_check) β€” Checks if a given request has access to get a specific item. * [get\_item\_schema](wp_rest_controller/get_item_schema) β€” Retrieves the item's schema, conforming to JSON Schema. * [get\_items](wp_rest_controller/get_items) β€” Retrieves a collection of items. * [get\_items\_permissions\_check](wp_rest_controller/get_items_permissions_check) β€” Checks if a given request has access to get items. * [get\_object\_type](wp_rest_controller/get_object_type) β€” Retrieves the object type this controller is responsible for managing. * [get\_public\_item\_schema](wp_rest_controller/get_public_item_schema) β€” Retrieves the item's schema for display / public consumption purposes. * [prepare\_item\_for\_database](wp_rest_controller/prepare_item_for_database) β€” Prepares one item for create or update operation. * [prepare\_item\_for\_response](wp_rest_controller/prepare_item_for_response) β€” Prepares the item for the REST response. * [prepare\_response\_for\_collection](wp_rest_controller/prepare_response_for_collection) β€” Prepares a response for insertion into a collection. * [register\_routes](wp_rest_controller/register_routes) β€” Registers the routes for the objects of the controller. * [sanitize\_slug](wp_rest_controller/sanitize_slug) β€” Sanitizes the slug value. * [update\_additional\_fields\_for\_object](wp_rest_controller/update_additional_fields_for_object) β€” Updates the values of additional fields added to a data object. * [update\_item](wp_rest_controller/update_item) β€” Updates one item from the collection. * [update\_item\_permissions\_check](wp_rest_controller/update_item_permissions_check) β€” Checks if a given request has access to update a specific item. 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/) ``` abstract class WP_REST_Controller { /** * The namespace of this controller's route. * * @since 4.7.0 * @var string */ protected $namespace; /** * The base of this controller's route. * * @since 4.7.0 * @var string */ protected $rest_base; /** * Cached results of get_item_schema. * * @since 5.3.0 * @var array */ protected $schema; /** * Registers the routes for the objects of the controller. * * @since 4.7.0 * * @see register_rest_route() */ 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' ); } /** * Checks if a given request has access to get items. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ 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 ) ); } /** * Retrieves a collection of items. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_items( $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 ) ); } /** * Checks if a given request has access to get a specific item. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise. */ 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 ) ); } /** * Retrieves one item from the collection. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_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 ) ); } /** * Checks if a given request has access to create items. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise. */ 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 ) ); } /** * Creates one item from the collection. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function create_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 ) ); } /** * Checks if a given request has access to update a specific item. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise. */ 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 ) ); } /** * Updates one item from the collection. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function update_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 ) ); } /** * Checks if a given request has access to delete a specific item. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise. */ public function delete_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 ) ); } /** * Deletes one item from the collection. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ 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 ) ); } /** * Prepares one item for create or update operation. * * @since 4.7.0 * * @param WP_REST_Request $request Request object. * @return object|WP_Error The prepared item, or WP_Error object on failure. */ 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 ) ); } /** * Prepares the item for the REST response. * * @since 4.7.0 * * @param mixed $item WordPress representation of the item. * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function prepare_item_for_response( $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 ) ); } /** * Prepares a response for insertion into a collection. * * @since 4.7.0 * * @param WP_REST_Response $response Response object. * @return array|mixed Response data, ready for insertion into collection data. */ 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; } /** * Filters a response based on the context defined in the schema. * * @since 4.7.0 * * @param array $data Response data to filter. * @param string $context Context defined in the schema. * @return array Filtered response. */ public function filter_response_by_context( $data, $context ) { $schema = $this->get_item_schema(); return rest_filter_response_by_context( $data, $schema, $context ); } /** * Retrieves the item's schema, conforming to JSON Schema. * * @since 4.7.0 * * @return array Item schema data. */ public function get_item_schema() { return $this->add_additional_fields_schema( array() ); } /** * Retrieves the item's schema for display / public consumption purposes. * * @since 4.7.0 * * @return array Public item schema data. */ 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; } /** * Retrieves the query params for the collections. * * @since 4.7.0 * * @return array Query parameters for the collection. */ 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', ), ); } /** * Retrieves the magical context param. * * Ensures consistent descriptions between endpoints, and populates enum from schema. * * @since 4.7.0 * * @param array $args Optional. Additional arguments for context parameter. Default empty array. * @return array Context parameter details. */ 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 ); } /** * Adds the values from additional fields to a data object. * * @since 4.7.0 * * @param array $prepared Prepared response array. * @param WP_REST_Request $request Full details about the request. * @return array Modified data object with additional fields. */ protected function add_additional_fields_to_object( $prepared, $request ) { $additional_fields = $this->get_additional_fields(); $requested_fields = $this->get_fields_for_response( $request ); foreach ( $additional_fields as $field_name => $field_options ) { if ( ! $field_options['get_callback'] ) { continue; } if ( ! rest_is_field_included( $field_name, $requested_fields ) ) { continue; } $prepared[ $field_name ] = call_user_func( $field_options['get_callback'], $prepared, $field_name, $request, $this->get_object_type() ); } return $prepared; } /** * Updates the values of additional fields added to a data object. * * @since 4.7.0 * * @param object $object Data model like WP_Term or WP_Post. * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True on success, WP_Error object if a field cannot be updated. */ protected function update_additional_fields_for_object( $object, $request ) { $additional_fields = $this->get_additional_fields(); foreach ( $additional_fields as $field_name => $field_options ) { if ( ! $field_options['update_callback'] ) { continue; } // Don't run the update callbacks if the data wasn't passed in the request. if ( ! isset( $request[ $field_name ] ) ) { continue; } $result = call_user_func( $field_options['update_callback'], $request[ $field_name ], $object, $field_name, $request, $this->get_object_type() ); if ( is_wp_error( $result ) ) { return $result; } } return true; } /** * Adds the schema from additional fields to a schema array. * * The type of object is inferred from the passed schema. * * @since 4.7.0 * * @param array $schema Schema array. * @return array Modified Schema array. */ protected function add_additional_fields_schema( $schema ) { if ( empty( $schema['title'] ) ) { return $schema; } // Can't use $this->get_object_type otherwise we cause an inf loop. $object_type = $schema['title']; $additional_fields = $this->get_additional_fields( $object_type ); foreach ( $additional_fields as $field_name => $field_options ) { if ( ! $field_options['schema'] ) { continue; } $schema['properties'][ $field_name ] = $field_options['schema']; } return $schema; } /** * Retrieves all of the registered additional fields for a given object-type. * * @since 4.7.0 * * @global array $wp_rest_additional_fields Holds registered fields, organized by object type. * * @param string $object_type Optional. The object type. * @return array Registered additional fields (if any), empty array if none or if the object type * could not be inferred. */ protected function get_additional_fields( $object_type = null ) { global $wp_rest_additional_fields; if ( ! $object_type ) { $object_type = $this->get_object_type(); } if ( ! $object_type ) { return array(); } if ( ! $wp_rest_additional_fields || ! isset( $wp_rest_additional_fields[ $object_type ] ) ) { return array(); } return $wp_rest_additional_fields[ $object_type ]; } /** * Retrieves the object type this controller is responsible for managing. * * @since 4.7.0 * * @return string Object type for the controller. */ protected function get_object_type() { $schema = $this->get_item_schema(); if ( ! $schema || ! isset( $schema['title'] ) ) { return null; } return $schema['title']; } /** * Gets an array of fields to be included on the response. * * Included fields are based on item schema and `_fields=` request argument. * * @since 4.9.6 * * @param WP_REST_Request $request Full details about the request. * @return string[] Fields to be included in the response. */ 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() ); } /** * Retrieves an array of endpoint arguments from the item schema for the controller. * * @since 4.7.0 * * @param string $method Optional. HTTP method of the request. The arguments for `CREATABLE` requests are * checked for required values and may fall-back to a given default, this is not done * on `EDITABLE` requests. Default WP_REST_Server::CREATABLE. * @return array Endpoint arguments. */ public function get_endpoint_args_for_item_schema( $method = WP_REST_Server::CREATABLE ) { return rest_get_endpoint_args_for_schema( $this->get_item_schema(), $method ); } /** * Sanitizes the slug value. * * @since 4.7.0 * * @internal We can't use sanitize_title() directly, as the second * parameter is the fallback title, which would end up being set to the * request object. * * @see https://github.com/WP-API/WP-API/issues/1585 * * @todo Remove this in favour of https://core.trac.wordpress.org/ticket/34659 * * @param string $slug Slug value passed in request. * @return string Sanitized value for the slug. */ public function sanitize_slug( $slug ) { return sanitize_title( $slug ); } } ``` | Used By | Description | | --- | --- | | [WP\_REST\_Block\_Patterns\_Controller](wp_rest_block_patterns_controller) wp-includes/rest-api/endpoints/class-wp-rest-block-patterns-controller.php | Core class used to access block patterns via the REST API. | | [WP\_REST\_Block\_Pattern\_Categories\_Controller](wp_rest_block_pattern_categories_controller) wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php | Core class used to access block pattern categories via the REST API. | | [WP\_REST\_Global\_Styles\_Controller](wp_rest_global_styles_controller) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Base Global Styles REST API Controller. | | [WP\_REST\_URL\_Details\_Controller](wp_rest_url_details_controller) wp-includes/rest-api/endpoints/class-wp-rest-url-details-controller.php | Controller which provides REST endpoint for retrieving information from a remote site’s HTML response. | | [WP\_REST\_Menu\_Locations\_Controller](wp_rest_menu_locations_controller) wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php | Core class used to access menu locations via the REST API. | | [WP\_REST\_Edit\_Site\_Export\_Controller](wp_rest_edit_site_export_controller) wp-includes/rest-api/endpoints/class-wp-rest-edit-site-export-controller.php | Controller which provides REST endpoint for exporting current templates and template parts. | | [WP\_REST\_Widgets\_Controller](wp_rest_widgets_controller) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Core class to access widgets via the REST API. | | [WP\_REST\_Sidebars\_Controller](wp_rest_sidebars_controller) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Core class used to manage a site’s sidebars. | | [WP\_REST\_Templates\_Controller](wp_rest_templates_controller) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Base Templates REST API Controller. | | [WP\_REST\_Pattern\_Directory\_Controller](wp_rest_pattern_directory_controller) wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php | Controller which provides REST endpoint for block patterns. | | [WP\_REST\_Widget\_Types\_Controller](wp_rest_widget_types_controller) wp-includes/rest-api/endpoints/class-wp-rest-widget-types-controller.php | Core class to access widget types via the REST API. | | [WP\_REST\_Site\_Health\_Controller](wp_rest_site_health_controller) wp-includes/rest-api/endpoints/class-wp-rest-site-health-controller.php | Core class for interacting with Site Health tests. | | [WP\_REST\_Application\_Passwords\_Controller](wp_rest_application_passwords_controller) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Core class to access a user’s application passwords via the REST API. | | [WP\_REST\_Block\_Directory\_Controller](wp_rest_block_directory_controller) wp-includes/rest-api/endpoints/class-wp-rest-block-directory-controller.php | Controller which provides REST endpoint for the blocks. | | [WP\_REST\_Plugins\_Controller](wp_rest_plugins_controller) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Core class to access plugins via the REST API. | | [WP\_REST\_Block\_Types\_Controller](wp_rest_block_types_controller) wp-includes/rest-api/endpoints/class-wp-rest-block-types-controller.php | Core class used to access block types via the REST API. | | [WP\_REST\_Search\_Controller](wp_rest_search_controller) wp-includes/rest-api/endpoints/class-wp-rest-search-controller.php | Core class to search through all WordPress content via the REST API. | | [WP\_REST\_Themes\_Controller](wp_rest_themes_controller) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Core class used to manage themes via the REST API. | | [WP\_REST\_Block\_Renderer\_Controller](wp_rest_block_renderer_controller) wp-includes/rest-api/endpoints/class-wp-rest-block-renderer-controller.php | Controller which provides REST endpoint for rendering a block. | | [WP\_REST\_Users\_Controller](wp_rest_users_controller) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Core class used to manage users via the REST API. | | [WP\_REST\_Revisions\_Controller](wp_rest_revisions_controller) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Core class used to access revisions via the REST API. | | [WP\_REST\_Post\_Statuses\_Controller](wp_rest_post_statuses_controller) wp-includes/rest-api/endpoints/class-wp-rest-post-statuses-controller.php | Core class used to access post statuses via the REST API. | | [WP\_REST\_Settings\_Controller](wp_rest_settings_controller) wp-includes/rest-api/endpoints/class-wp-rest-settings-controller.php | Core class used to manage a site’s settings via the REST API. | | [WP\_REST\_Terms\_Controller](wp_rest_terms_controller) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Core class used to managed terms associated with a taxonomy via the REST API. | | [WP\_REST\_Posts\_Controller](wp_rest_posts_controller) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Core class to access posts via the REST API. | | [WP\_REST\_Taxonomies\_Controller](wp_rest_taxonomies_controller) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Core class used to manage taxonomies via the REST API. | | [WP\_REST\_Post\_Types\_Controller](wp_rest_post_types_controller) wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php | Core class to access post types via the REST API. | | [WP\_REST\_Comments\_Controller](wp_rest_comments_controller) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Core controller used to access comments via the REST API. | | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Block_Renderer_Controller {} class WP\_REST\_Block\_Renderer\_Controller {} ============================================== Controller which provides REST endpoint for rendering a block. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_block_renderer_controller/__construct) β€” Constructs the controller. * [get\_item](wp_rest_block_renderer_controller/get_item) β€” Returns block output from block's registered render\_callback. * [get\_item\_permissions\_check](wp_rest_block_renderer_controller/get_item_permissions_check) β€” Checks if a given request has access to read blocks. * [get\_item\_schema](wp_rest_block_renderer_controller/get_item_schema) β€” Retrieves block's output schema, conforming to JSON Schema. * [register\_routes](wp_rest_block_renderer_controller/register_routes) β€” Registers the necessary REST API routes, one for each dynamic block. File: `wp-includes/rest-api/endpoints/class-wp-rest-block-renderer-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-renderer-controller.php/) ``` class WP_REST_Block_Renderer_Controller extends WP_REST_Controller { /** * Constructs the controller. * * @since 5.0.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'block-renderer'; } /** * Registers the necessary REST API routes, one for each dynamic block. * * @since 5.0.0 * * @see register_rest_route() */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<name>[a-z0-9-]+/[a-z0-9-]+)', array( 'args' => array( 'name' => array( 'description' => __( 'Unique registered name for the block.' ), 'type' => 'string', ), ), array( 'methods' => array( WP_REST_Server::READABLE, WP_REST_Server::CREATABLE ), 'callback' => array( $this, 'get_item' ), 'permission_callback' => array( $this, 'get_item_permissions_check' ), 'args' => array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), 'attributes' => array( 'description' => __( 'Attributes for the block.' ), 'type' => 'object', 'default' => array(), 'validate_callback' => static function ( $value, $request ) { $block = WP_Block_Type_Registry::get_instance()->get_registered( $request['name'] ); if ( ! $block ) { // This will get rejected in ::get_item(). return true; } $schema = array( 'type' => 'object', 'properties' => $block->get_attributes(), 'additionalProperties' => false, ); return rest_validate_value_from_schema( $value, $schema ); }, 'sanitize_callback' => static function ( $value, $request ) { $block = WP_Block_Type_Registry::get_instance()->get_registered( $request['name'] ); if ( ! $block ) { // This will get rejected in ::get_item(). return true; } $schema = array( 'type' => 'object', 'properties' => $block->get_attributes(), 'additionalProperties' => false, ); return rest_sanitize_value_from_schema( $value, $schema ); }, ), 'post_id' => array( 'description' => __( 'ID of the post context.' ), 'type' => 'integer', ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks if a given request has access to read blocks. * * @since 5.0.0 * * @global WP_Post $post Global post object. * * @param WP_REST_Request $request Request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_item_permissions_check( $request ) { global $post; $post_id = isset( $request['post_id'] ) ? (int) $request['post_id'] : 0; if ( $post_id > 0 ) { $post = get_post( $post_id ); if ( ! $post || ! current_user_can( 'edit_post', $post->ID ) ) { return new WP_Error( 'block_cannot_read', __( 'Sorry, you are not allowed to read blocks of this post.' ), array( 'status' => rest_authorization_required_code(), ) ); } } else { if ( ! current_user_can( 'edit_posts' ) ) { return new WP_Error( 'block_cannot_read', __( 'Sorry, you are not allowed to read blocks as this user.' ), array( 'status' => rest_authorization_required_code(), ) ); } } return true; } /** * Returns block output from block's registered render_callback. * * @since 5.0.0 * * @global WP_Post $post Global post object. * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { global $post; $post_id = isset( $request['post_id'] ) ? (int) $request['post_id'] : 0; if ( $post_id > 0 ) { $post = get_post( $post_id ); // Set up postdata since this will be needed if post_id was set. setup_postdata( $post ); } $registry = WP_Block_Type_Registry::get_instance(); $registered = $registry->get_registered( $request['name'] ); if ( null === $registered || ! $registered->is_dynamic() ) { return new WP_Error( 'block_invalid', __( 'Invalid block.' ), array( 'status' => 404, ) ); } $attributes = $request->get_param( 'attributes' ); // Create an array representation simulating the output of parse_blocks. $block = array( 'blockName' => $request['name'], 'attrs' => $attributes, 'innerHTML' => '', 'innerContent' => array(), ); // Render using render_block to ensure all relevant filters are used. $data = array( 'rendered' => render_block( $block ), ); return rest_ensure_response( $data ); } /** * Retrieves block's output schema, conforming to JSON Schema. * * @since 5.0.0 * * @return array Item schema data. */ public function get_item_schema() { if ( $this->schema ) { return $this->schema; } $this->schema = array( '$schema' => 'http://json-schema.org/schema#', 'title' => 'rendered-block', 'type' => 'object', 'properties' => array( 'rendered' => array( 'description' => __( 'The rendered block.' ), 'type' => 'string', 'required' => true, 'context' => array( 'edit' ), ), ), ); return $this->schema; } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. | wordpress class Requests_Exception_HTTP_417 {} class Requests\_Exception\_HTTP\_417 {} ======================================= Exception for 417 Expectation Failed responses File: `wp-includes/Requests/Exception/HTTP/417.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/417.php/) ``` class Requests_Exception_HTTP_417 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 417; /** * Reason phrase * * @var string */ protected $reason = 'Expectation Failed'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_REST_Themes_Controller {} class WP\_REST\_Themes\_Controller {} ===================================== Core class used to manage themes via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_themes_controller/__construct) β€” Constructor. * [\_sanitize\_stylesheet\_callback](wp_rest_themes_controller/_sanitize_stylesheet_callback) β€” Sanitize the stylesheet to decode endpoint. * [check\_read\_active\_theme\_permission](wp_rest_themes_controller/check_read_active_theme_permission) β€” Checks if a theme can be read. * [get\_collection\_params](wp_rest_themes_controller/get_collection_params) β€” Retrieves the search params for the themes collection. * [get\_item](wp_rest_themes_controller/get_item) β€” Retrieves a single theme. * [get\_item\_permissions\_check](wp_rest_themes_controller/get_item_permissions_check) β€” Checks if a given request has access to read the theme. * [get\_item\_schema](wp_rest_themes_controller/get_item_schema) β€” Retrieves the theme's schema, conforming to JSON Schema. * [get\_items](wp_rest_themes_controller/get_items) β€” Retrieves a collection of themes. * [get\_items\_permissions\_check](wp_rest_themes_controller/get_items_permissions_check) β€” Checks if a given request has access to read the theme. * [is\_same\_theme](wp_rest_themes_controller/is_same_theme) β€” Helper function to compare two themes. * [prepare\_item\_for\_response](wp_rest_themes_controller/prepare_item_for_response) β€” Prepares a single theme output for response. * [prepare\_links](wp_rest_themes_controller/prepare_links) β€” Prepares links for the request. * [prepare\_theme\_support](wp_rest_themes_controller/prepare_theme_support) β€” Prepares the theme support value for inclusion in the REST API response. * [register\_routes](wp_rest_themes_controller/register_routes) β€” Registers the routes for themes. * [sanitize\_theme\_status](wp_rest_themes_controller/sanitize_theme_status) β€” Sanitizes and validates the list of theme status. β€” deprecated File: `wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php/) ``` class WP_REST_Themes_Controller extends WP_REST_Controller { /** * Matches theme's directory: `/themes/<subdirectory>/<theme>/` or `/themes/<theme>/`. * Excludes invalid directory name characters: `/:<>*?"|`. */ const PATTERN = '[^\/:<>\*\?"\|]+(?:\/[^\/:<>\*\?"\|]+)?'; /** * Constructor. * * @since 5.0.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'themes'; } /** * Registers the routes for themes. * * @since 5.0.0 * * @see register_rest_route() */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => $this->get_collection_params(), ), 'schema' => array( $this, 'get_item_schema' ), ) ); register_rest_route( $this->namespace, sprintf( '/%s/(?P<stylesheet>%s)', $this->rest_base, self::PATTERN ), array( 'args' => array( 'stylesheet' => array( 'description' => __( "The theme's stylesheet. This uniquely identifies the theme." ), 'type' => 'string', 'sanitize_callback' => array( $this, '_sanitize_stylesheet_callback' ), ), ), array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'permission_callback' => array( $this, 'get_item_permissions_check' ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Sanitize the stylesheet to decode endpoint. * * @since 5.9.0 * * @param string $stylesheet The stylesheet name. * @return string Sanitized stylesheet. */ public function _sanitize_stylesheet_callback( $stylesheet ) { return urldecode( $stylesheet ); } /** * Checks if a given request has access to read the theme. * * @since 5.0.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, otherwise WP_Error object. */ public function get_items_permissions_check( $request ) { if ( current_user_can( 'switch_themes' ) || current_user_can( 'manage_network_themes' ) ) { return true; } $registered = $this->get_collection_params(); if ( isset( $registered['status'], $request['status'] ) && is_array( $request['status'] ) && array( 'active' ) === $request['status'] ) { return $this->check_read_active_theme_permission(); } return new WP_Error( 'rest_cannot_view_themes', __( 'Sorry, you are not allowed to view themes.' ), array( 'status' => rest_authorization_required_code() ) ); } /** * Checks if a given request has access to read the theme. * * @since 5.7.0 * * @param WP_REST_Request $request Full details about the request. * @return bool|WP_Error True if the request has read access for the item, otherwise WP_Error object. */ public function get_item_permissions_check( $request ) { if ( current_user_can( 'switch_themes' ) || current_user_can( 'manage_network_themes' ) ) { return true; } $wp_theme = wp_get_theme( $request['stylesheet'] ); $current_theme = wp_get_theme(); if ( $this->is_same_theme( $wp_theme, $current_theme ) ) { return $this->check_read_active_theme_permission(); } return new WP_Error( 'rest_cannot_view_themes', __( 'Sorry, you are not allowed to view themes.' ), array( 'status' => rest_authorization_required_code() ) ); } /** * Checks if a theme can be read. * * @since 5.7.0 * * @return bool|WP_Error Whether the theme can be read. */ protected function check_read_active_theme_permission() { 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_active_theme', __( 'Sorry, you are not allowed to view the active theme.' ), array( 'status' => rest_authorization_required_code() ) ); } /** * Retrieves a single theme. * * @since 5.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { $wp_theme = wp_get_theme( $request['stylesheet'] ); if ( ! $wp_theme->exists() ) { return new WP_Error( 'rest_theme_not_found', __( 'Theme not found.' ), array( 'status' => 404 ) ); } $data = $this->prepare_item_for_response( $wp_theme, $request ); return rest_ensure_response( $data ); } /** * Retrieves a collection of themes. * * @since 5.0.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { $themes = array(); $active_themes = wp_get_themes(); $current_theme = wp_get_theme(); $status = $request['status']; foreach ( $active_themes as $theme_name => $theme ) { $theme_status = ( $this->is_same_theme( $theme, $current_theme ) ) ? 'active' : 'inactive'; if ( is_array( $status ) && ! in_array( $theme_status, $status, true ) ) { continue; } $prepared = $this->prepare_item_for_response( $theme, $request ); $themes[] = $this->prepare_response_for_collection( $prepared ); } $response = rest_ensure_response( $themes ); $response->header( 'X-WP-Total', count( $themes ) ); $response->header( 'X-WP-TotalPages', 1 ); return $response; } /** * Prepares a single theme output for response. * * @since 5.0.0 * @since 5.9.0 Renamed `$theme` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Theme $item Theme object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $theme = $item; $data = array(); $fields = $this->get_fields_for_response( $request ); if ( rest_is_field_included( 'stylesheet', $fields ) ) { $data['stylesheet'] = $theme->get_stylesheet(); } if ( rest_is_field_included( 'template', $fields ) ) { /** * Use the 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() takes into account where WordPress actually located the theme and * whether it is actually valid. */ $data['template'] = $theme->get_template(); } $plain_field_mappings = array( 'requires_php' => 'RequiresPHP', 'requires_wp' => 'RequiresWP', 'textdomain' => 'TextDomain', 'version' => 'Version', ); foreach ( $plain_field_mappings as $field => $header ) { if ( rest_is_field_included( $field, $fields ) ) { $data[ $field ] = $theme->get( $header ); } } if ( rest_is_field_included( 'screenshot', $fields ) ) { // Using $theme->get_screenshot() with no args to get absolute URL. $data['screenshot'] = $theme->get_screenshot() ? $theme->get_screenshot() : ''; } $rich_field_mappings = array( 'author' => 'Author', 'author_uri' => 'AuthorURI', 'description' => 'Description', 'name' => 'Name', 'tags' => 'Tags', 'theme_uri' => 'ThemeURI', ); foreach ( $rich_field_mappings as $field => $header ) { if ( rest_is_field_included( "{$field}.raw", $fields ) ) { $data[ $field ]['raw'] = $theme->display( $header, false, true ); } if ( rest_is_field_included( "{$field}.rendered", $fields ) ) { $data[ $field ]['rendered'] = $theme->display( $header ); } } $current_theme = wp_get_theme(); if ( rest_is_field_included( 'status', $fields ) ) { $data['status'] = ( $this->is_same_theme( $theme, $current_theme ) ) ? 'active' : 'inactive'; } if ( rest_is_field_included( 'theme_supports', $fields ) && $this->is_same_theme( $theme, $current_theme ) ) { foreach ( get_registered_theme_features() as $feature => $config ) { if ( ! is_array( $config['show_in_rest'] ) ) { continue; } $name = $config['show_in_rest']['name']; if ( ! rest_is_field_included( "theme_supports.{$name}", $fields ) ) { continue; } if ( ! current_theme_supports( $feature ) ) { $data['theme_supports'][ $name ] = $config['show_in_rest']['schema']['default']; continue; } $support = get_theme_support( $feature ); if ( isset( $config['show_in_rest']['prepare_callback'] ) ) { $prepare = $config['show_in_rest']['prepare_callback']; } else { $prepare = array( $this, 'prepare_theme_support' ); } $prepared = $prepare( $support, $config, $feature, $request ); if ( is_wp_error( $prepared ) ) { continue; } $data['theme_supports'][ $name ] = $prepared; } } $data = $this->add_additional_fields_to_object( $data, $request ); // Wrap the data in a response object. $response = rest_ensure_response( $data ); if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { $response->add_links( $this->prepare_links( $theme ) ); } /** * Filters theme data returned from the REST API. * * @since 5.0.0 * * @param WP_REST_Response $response The response object. * @param WP_Theme $theme Theme object used to create response. * @param WP_REST_Request $request Request object. */ return apply_filters( 'rest_prepare_theme', $response, $theme, $request ); } /** * Prepares links for the request. * * @since 5.7.0 * * @param WP_Theme $theme Theme data. * @return array Links for the given block type. */ protected function prepare_links( $theme ) { $links = array( 'self' => array( 'href' => rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $theme->get_stylesheet() ) ), ), 'collection' => array( 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ), ), ); if ( $this->is_same_theme( $theme, wp_get_theme() ) ) { // This creates a record for the active theme if not existent. $id = WP_Theme_JSON_Resolver::get_user_global_styles_post_id(); } else { $user_cpt = WP_Theme_JSON_Resolver::get_user_data_from_wp_global_styles( $theme ); $id = isset( $user_cpt['ID'] ) ? $user_cpt['ID'] : null; } if ( $id ) { $links['https://api.w.org/user-global-styles'] = array( 'href' => rest_url( 'wp/v2/global-styles/' . $id ), ); } return $links; } /** * Helper function to compare two themes. * * @since 5.7.0 * * @param WP_Theme $theme_a First theme to compare. * @param WP_Theme $theme_b Second theme to compare. * @return bool */ protected function is_same_theme( $theme_a, $theme_b ) { return $theme_a->get_stylesheet() === $theme_b->get_stylesheet(); } /** * Prepares the theme support value for inclusion in the REST API response. * * @since 5.5.0 * * @param mixed $support The raw value from get_theme_support(). * @param array $args The feature's registration args. * @param string $feature The feature name. * @param WP_REST_Request $request The request object. * @return mixed The prepared support value. */ protected function prepare_theme_support( $support, $args, $feature, $request ) { $schema = $args['show_in_rest']['schema']; if ( 'boolean' === $schema['type'] ) { return true; } if ( is_array( $support ) && ! $args['variadic'] ) { $support = $support[0]; } return rest_sanitize_value_from_schema( $support, $schema ); } /** * Retrieves the theme's schema, conforming to JSON Schema. * * @since 5.0.0 * * @return array Item schema data. */ 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' => 'theme', 'type' => 'object', 'properties' => array( 'stylesheet' => array( 'description' => __( 'The theme\'s stylesheet. This uniquely identifies the theme.' ), 'type' => 'string', 'readonly' => true, ), 'template' => array( 'description' => __( 'The theme\'s template. If this is a child theme, this refers to the parent theme, otherwise this is the same as the theme\'s stylesheet.' ), 'type' => 'string', 'readonly' => true, ), 'author' => array( 'description' => __( 'The theme author.' ), 'type' => 'object', 'readonly' => true, 'properties' => array( 'raw' => array( 'description' => __( 'The theme author\'s name, as found in the theme header.' ), 'type' => 'string', ), 'rendered' => array( 'description' => __( 'HTML for the theme author, transformed for display.' ), 'type' => 'string', ), ), ), 'author_uri' => array( 'description' => __( 'The website of the theme author.' ), 'type' => 'object', 'readonly' => true, 'properties' => array( 'raw' => array( 'description' => __( 'The website of the theme author, as found in the theme header.' ), 'type' => 'string', 'format' => 'uri', ), 'rendered' => array( 'description' => __( 'The website of the theme author, transformed for display.' ), 'type' => 'string', 'format' => 'uri', ), ), ), 'description' => array( 'description' => __( 'A description of the theme.' ), 'type' => 'object', 'readonly' => true, 'properties' => array( 'raw' => array( 'description' => __( 'The theme description, as found in the theme header.' ), 'type' => 'string', ), 'rendered' => array( 'description' => __( 'The theme description, transformed for display.' ), 'type' => 'string', ), ), ), 'name' => array( 'description' => __( 'The name of the theme.' ), 'type' => 'object', 'readonly' => true, 'properties' => array( 'raw' => array( 'description' => __( 'The theme name, as found in the theme header.' ), 'type' => 'string', ), 'rendered' => array( 'description' => __( 'The theme name, transformed for display.' ), 'type' => 'string', ), ), ), 'requires_php' => array( 'description' => __( 'The minimum PHP version required for the theme to work.' ), 'type' => 'string', 'readonly' => true, ), 'requires_wp' => array( 'description' => __( 'The minimum WordPress version required for the theme to work.' ), 'type' => 'string', 'readonly' => true, ), 'screenshot' => array( 'description' => __( 'The theme\'s screenshot URL.' ), 'type' => 'string', 'format' => 'uri', 'readonly' => true, ), 'tags' => array( 'description' => __( 'Tags indicating styles and features of the theme.' ), 'type' => 'object', 'readonly' => true, 'properties' => array( 'raw' => array( 'description' => __( 'The theme tags, as found in the theme header.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), ), 'rendered' => array( 'description' => __( 'The theme tags, transformed for display.' ), 'type' => 'string', ), ), ), 'textdomain' => array( 'description' => __( 'The theme\'s text domain.' ), 'type' => 'string', 'readonly' => true, ), 'theme_supports' => array( 'description' => __( 'Features supported by this theme.' ), 'type' => 'object', 'readonly' => true, 'properties' => array(), ), 'theme_uri' => array( 'description' => __( 'The URI of the theme\'s webpage.' ), 'type' => 'object', 'readonly' => true, 'properties' => array( 'raw' => array( 'description' => __( 'The URI of the theme\'s webpage, as found in the theme header.' ), 'type' => 'string', 'format' => 'uri', ), 'rendered' => array( 'description' => __( 'The URI of the theme\'s webpage, transformed for display.' ), 'type' => 'string', 'format' => 'uri', ), ), ), 'version' => array( 'description' => __( 'The theme\'s current version.' ), 'type' => 'string', 'readonly' => true, ), 'status' => array( 'description' => __( 'A named status for the theme.' ), 'type' => 'string', 'enum' => array( 'inactive', 'active' ), ), ), ); foreach ( get_registered_theme_features() as $feature => $config ) { if ( ! is_array( $config['show_in_rest'] ) ) { continue; } $name = $config['show_in_rest']['name']; $schema['properties']['theme_supports']['properties'][ $name ] = $config['show_in_rest']['schema']; } $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the search params for the themes collection. * * @since 5.0.0 * * @return array Collection parameters. */ public function get_collection_params() { $query_params = array( 'status' => array( 'description' => __( 'Limit result set to themes assigned one or more statuses.' ), 'type' => 'array', 'items' => array( 'enum' => array( 'active', 'inactive' ), 'type' => 'string', ), ), ); /** * Filters REST API collection parameters for the themes controller. * * @since 5.0.0 * * @param array $query_params JSON Schema-formatted collection parameters. */ return apply_filters( 'rest_themes_collection_params', $query_params ); } /** * Sanitizes and validates the list of theme status. * * @since 5.0.0 * @deprecated 5.7.0 * * @param string|array $statuses One or more theme statuses. * @param WP_REST_Request $request Full details about the request. * @param string $parameter Additional parameter to pass to validation. * @return array|WP_Error A list of valid statuses, otherwise WP_Error object. */ public function sanitize_theme_status( $statuses, $request, $parameter ) { _deprecated_function( __METHOD__, '5.7.0' ); $statuses = wp_parse_slug_list( $statuses ); foreach ( $statuses as $status ) { $result = rest_validate_request_arg( $status, $request, $parameter ); if ( is_wp_error( $result ) ) { return $result; } } return $statuses; } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
programming_docs
wordpress class WP_Customize_Nav_Menu_Name_Control {} class WP\_Customize\_Nav\_Menu\_Name\_Control {} ================================================ Customize control to represent the name field for a given menu. * [WP\_Customize\_Control](wp_customize_control) * [content\_template](wp_customize_nav_menu_name_control/content_template) β€” Render the Underscore template for this control. * [render\_content](wp_customize_nav_menu_name_control/render_content) β€” No-op since we're using JS template. File: `wp-includes/customize/class-wp-customize-nav-menu-name-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-name-control.php/) ``` class WP_Customize_Nav_Menu_Name_Control extends WP_Customize_Control { /** * Type of control, used by JS. * * @since 4.3.0 * @var string */ public $type = 'nav_menu_name'; /** * No-op since we're using JS template. * * @since 4.3.0 */ protected function render_content() {} /** * Render the Underscore template for this control. * * @since 4.3.0 */ protected function content_template() { ?> <label> <# if ( data.label ) { #> <span class="customize-control-title">{{ data.label }}</span> <# } #> <input type="text" class="menu-name-field live-update-section-title" <# if ( data.description ) { #> aria-describedby="{{ data.section }}-description" <# } #> /> </label> <# if ( data.description ) { #> <p id="{{ data.section }}-description">{{ data.description }}</p> <# } #> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Control](wp_customize_control) wp-includes/class-wp-customize-control.php | Customize Control class. | | Version | Description | | --- | --- | | [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. | wordpress class IXR_Date {} class IXR\_Date {} ================== [IXR\_Date](ixr_date) * [\_\_construct](ixr_date/__construct) β€” PHP5 constructor. * [getIso](ixr_date/getiso) * [getTimestamp](ixr_date/gettimestamp) * [getXml](ixr_date/getxml) * [IXR\_Date](ixr_date/ixr_date) β€” PHP4 constructor. * [parseIso](ixr_date/parseiso) * [parseTimestamp](ixr_date/parsetimestamp) File: `wp-includes/IXR/class-IXR-date.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-date.php/) ``` class IXR_Date { var $year; var $month; var $day; var $hour; var $minute; var $second; var $timezone; /** * PHP5 constructor. */ function __construct( $time ) { // $time can be a PHP timestamp or an ISO one if (is_numeric($time)) { $this->parseTimestamp($time); } else { $this->parseIso($time); } } /** * PHP4 constructor. */ public function IXR_Date( $time ) { self::__construct( $time ); } function parseTimestamp($timestamp) { $this->year = gmdate('Y', $timestamp); $this->month = gmdate('m', $timestamp); $this->day = gmdate('d', $timestamp); $this->hour = gmdate('H', $timestamp); $this->minute = gmdate('i', $timestamp); $this->second = gmdate('s', $timestamp); $this->timezone = ''; } function parseIso($iso) { $this->year = substr($iso, 0, 4); $this->month = substr($iso, 4, 2); $this->day = substr($iso, 6, 2); $this->hour = substr($iso, 9, 2); $this->minute = substr($iso, 12, 2); $this->second = substr($iso, 15, 2); $this->timezone = substr($iso, 17); } function getIso() { return $this->year.$this->month.$this->day.'T'.$this->hour.':'.$this->minute.':'.$this->second.$this->timezone; } function getXml() { return '<dateTime.iso8601>'.$this->getIso().'</dateTime.iso8601>'; } function getTimestamp() { return mktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year); } } ``` | Version | Description | | --- | --- | | [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. | wordpress class Walker {} class Walker {} =============== A class for displaying various tree-like structures. Extend the [Walker](walker) class to use it, see examples below. Child classes do not need to implement all of the abstract methods in the class. The child only needs to implement the methods that are needed. The [Walker](walker) class was implemented in [WordPress 2.1](https://codex.wordpress.org/Version_2.1 "Version 2.1") to provide developers with a means to traverse tree-like data structures for the purpose of rendering HTML. In terms of web development, a tree-like structure is an array or object with hierarchical data – such that it can be visually represented with a root element and subtrees of children. Examples of WordPress objects with data that are structured in a β€œtree-like” way include navigational menus, page categories, and breadcrumbs. [Walker](walker) is an *[abstract](http://php.net/manual/en/language.oop5.abstract.php)* class. In order to be useful the class must be [extended](http://php.net/manual/en/reflection.extending.php) and any necessary abstract methods defined (see β€œAbstract Methods” below for more). The class itself simply β€œwalks” through each node in a tree (e.g. an object or associative array) and executes an abstract function at each node. In order to take an action at one of these nodes, a developer must define those abstract methods within a custom child class. Although the [Walker](walker) class has many uses, one of the most common usages by developers is outputting HTML for custom menus (usually ones that have been defined using the [Appearance β†’ Menus](https://wordpress.org/support/article/appearance-menus-screen/ "Appearance Menus Screen") screen in the [Administration Screens](https://wordpress.org/support/article/administration-screens/ "Administration Screens")). **Abstraction Note:** The [Walker](walker) class was created *prior* to PHP5 and so does **not** make use of PHP5’s explicit abstraction keywords or features. In this case, the class and its methods are *implicitly* abstract (PHP4 compatible) and **not** *explicitly* abstract (PHP5 compatible). Developers are not required to implement any methods of the class, and may use or override only those methods that are needed. If you chose not to extend a specific abstract method, that method will simply do nothing. Please refer source code for the complete lists of methods and properties. Below description may cover some of them. Note that the properties of the [Walker](walker) class are intended to be set by the extending class and probably should not vary over the lifetime of an instance. $db\_fields **Required**. Because [Walker](walker) can take any type of tree object, you need to specify what object properties the [Walker](walker) class should treat as parent id and item id (usually these are the names of database fields, hence the property name). This property **must** be an associative array with two keys: `'parent'` and `'id'`. The value of each key should be the names of the object properties that hold the *parent id* and *item id*, respectively. $tree\_type Optional. The [Walker](walker) class itself makes no use of this value, although it may be useful to developers. Internally, WordPress’s own extended [Walker](walker) classes will set this to values like β€˜category’ or β€˜page’. $max\_pages Optional. The maximum number of pages walked by the paged walker. There are two general use-cases for the [Walker](walker) class. Some WordPress APIs and functions ( such as [wp\_nav\_menu()](../functions/wp_nav_menu) ) allow developers to specify a custom [Walker](walker) class as a callback. This is the most common usage of the [Walker](walker) class by developers. In this scenario, the class is automatically passed a tree of elements. When creating a custom walker for this scenario, you will generally only need to define the **abstract** methods needed to create the kind of structure you want. Everything else is handled automatically for you. It is also possible to call your custom [Walker](walker) classes manually. This is particularly useful for plugin developers. In this scenario, you can initiate the walker by calling either the walk() or paged\_walk() method of your child class, with the appropriate parameters. * [display\_element](walker/display_element) β€” Traverses elements to create list from elements. * [end\_el](walker/end_el) β€” Ends the element output, if needed. * [end\_lvl](walker/end_lvl) β€” Ends the list of after the elements are added. * [get\_number\_of\_root\_elements](walker/get_number_of_root_elements) β€” Calculates the total number of root elements. * [paged\_walk](walker/paged_walk) β€” Produces a page of nested elements. * [start\_el](walker/start_el) β€” Starts the element output. * [start\_lvl](walker/start_lvl) β€” Starts the list before the elements are added. * [unset\_children](walker/unset_children) β€” Unsets all the children for a given top level element. * [walk](walker/walk) β€” Displays array of elements hierarchically. File: `wp-includes/class-wp-walker.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-walker.php/) ``` class Walker { /** * What the class handles. * * @since 2.1.0 * @var string */ public $tree_type; /** * DB fields to use. * * @since 2.1.0 * @var string[] */ public $db_fields; /** * Max number of pages walked by the paged walker. * * @since 2.7.0 * @var int */ public $max_pages = 1; /** * Whether the current element has children or not. * * To be used in start_el(). * * @since 4.0.0 * @var bool */ public $has_children; /** * Starts the list before the elements are added. * * The $args parameter holds additional values that may be used with the child * class methods. This method is called at the start of the output list. * * @since 2.1.0 * @abstract * * @param string $output Used to append additional content (passed by reference). * @param int $depth Depth of the item. * @param array $args An array of additional arguments. */ public function start_lvl( &$output, $depth = 0, $args = array() ) {} /** * Ends the list of after the elements are added. * * The $args parameter holds additional values that may be used with the child * class methods. This method finishes the list at the end of output of the elements. * * @since 2.1.0 * @abstract * * @param string $output Used to append additional content (passed by reference). * @param int $depth Depth of the item. * @param array $args An array of additional arguments. */ public function end_lvl( &$output, $depth = 0, $args = array() ) {} /** * Starts the element output. * * The $args parameter holds additional values that may be used with the child * class methods. Also includes the element output. * * @since 2.1.0 * @since 5.9.0 Renamed `$object` (a PHP reserved keyword) to `$data_object` for PHP 8 named parameter support. * @abstract * * @param string $output Used to append additional content (passed by reference). * @param object $data_object The data object. * @param int $depth Depth of the item. * @param array $args An array of additional arguments. * @param int $current_object_id Optional. ID of the current item. Default 0. */ public function start_el( &$output, $data_object, $depth = 0, $args = array(), $current_object_id = 0 ) {} /** * Ends the element output, if needed. * * The $args parameter holds additional values that may be used with the child class methods. * * @since 2.1.0 * @since 5.9.0 Renamed `$object` (a PHP reserved keyword) to `$data_object` for PHP 8 named parameter support. * @abstract * * @param string $output Used to append additional content (passed by reference). * @param object $data_object The data object. * @param int $depth Depth of the item. * @param array $args An array of additional arguments. */ public function end_el( &$output, $data_object, $depth = 0, $args = array() ) {} /** * Traverses elements to create list from elements. * * Display one element if the element doesn't have any children otherwise, * display the element and its children. Will only traverse up to the max * depth and no ignore elements under that depth. It is possible to set the * max depth to include all depths, see walk() method. * * This method should not be called directly, use the walk() method instead. * * @since 2.5.0 * * @param object $element Data object. * @param array $children_elements List of elements to continue traversing (passed by reference). * @param int $max_depth Max depth to traverse. * @param int $depth Depth of current element. * @param array $args An array of arguments. * @param string $output Used to append additional content (passed by reference). */ public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) { if ( ! $element ) { return; } $id_field = $this->db_fields['id']; $id = $element->$id_field; // Display this element. $this->has_children = ! empty( $children_elements[ $id ] ); if ( isset( $args[0] ) && is_array( $args[0] ) ) { $args[0]['has_children'] = $this->has_children; // Back-compat. } $this->start_el( $output, $element, $depth, ...array_values( $args ) ); // Descend only when the depth is right and there are children for this element. if ( ( 0 == $max_depth || $max_depth > $depth + 1 ) && isset( $children_elements[ $id ] ) ) { foreach ( $children_elements[ $id ] as $child ) { if ( ! isset( $newlevel ) ) { $newlevel = true; // Start the child delimiter. $this->start_lvl( $output, $depth, ...array_values( $args ) ); } $this->display_element( $child, $children_elements, $max_depth, $depth + 1, $args, $output ); } unset( $children_elements[ $id ] ); } if ( isset( $newlevel ) && $newlevel ) { // End the child delimiter. $this->end_lvl( $output, $depth, ...array_values( $args ) ); } // End this element. $this->end_el( $output, $element, $depth, ...array_values( $args ) ); } /** * Displays array of elements hierarchically. * * Does not assume any existing order of elements. * * $max_depth = -1 means flatly display every element. * $max_depth = 0 means display all levels. * $max_depth > 0 specifies the number of display levels. * * @since 2.1.0 * @since 5.3.0 Formalized the existing `...$args` parameter by adding it * to the function signature. * * @param array $elements An array of elements. * @param int $max_depth The maximum hierarchical depth. * @param mixed ...$args Optional additional arguments. * @return string The hierarchical item output. */ public function walk( $elements, $max_depth, ...$args ) { $output = ''; // Invalid parameter or nothing to walk. if ( $max_depth < -1 || empty( $elements ) ) { return $output; } $parent_field = $this->db_fields['parent']; // Flat display. if ( -1 == $max_depth ) { $empty_array = array(); foreach ( $elements as $e ) { $this->display_element( $e, $empty_array, 1, 0, $args, $output ); } return $output; } /* * Need to display in hierarchical order. * Separate elements into two buckets: top level and children elements. * Children_elements is two dimensional array. Example: * Children_elements[10][] contains all sub-elements whose parent is 10. */ $top_level_elements = array(); $children_elements = array(); foreach ( $elements as $e ) { if ( empty( $e->$parent_field ) ) { $top_level_elements[] = $e; } else { $children_elements[ $e->$parent_field ][] = $e; } } /* * When none of the elements is top level. * Assume the first one must be root of the sub elements. */ if ( empty( $top_level_elements ) ) { $first = array_slice( $elements, 0, 1 ); $root = $first[0]; $top_level_elements = array(); $children_elements = array(); foreach ( $elements as $e ) { if ( $root->$parent_field == $e->$parent_field ) { $top_level_elements[] = $e; } else { $children_elements[ $e->$parent_field ][] = $e; } } } foreach ( $top_level_elements as $e ) { $this->display_element( $e, $children_elements, $max_depth, 0, $args, $output ); } /* * If we are displaying all levels, and remaining children_elements is not empty, * then we got orphans, which should be displayed regardless. */ if ( ( 0 == $max_depth ) && count( $children_elements ) > 0 ) { $empty_array = array(); foreach ( $children_elements as $orphans ) { foreach ( $orphans as $op ) { $this->display_element( $op, $empty_array, 1, 0, $args, $output ); } } } return $output; } /** * Produces a page of nested elements. * * Given an array of hierarchical elements, the maximum depth, a specific page number, * and number of elements per page, this function first determines all top level root elements * belonging to that page, then lists them and all of their children in hierarchical order. * * $max_depth = 0 means display all levels. * $max_depth > 0 specifies the number of display levels. * * @since 2.7.0 * @since 5.3.0 Formalized the existing `...$args` parameter by adding it * to the function signature. * * @param array $elements An array of elements. * @param int $max_depth The maximum hierarchical depth. * @param int $page_num The specific page number, beginning with 1. * @param int $per_page Number of elements per page. * @param mixed ...$args Optional additional arguments. * @return string XHTML of the specified page of elements. */ public function paged_walk( $elements, $max_depth, $page_num, $per_page, ...$args ) { if ( empty( $elements ) || $max_depth < -1 ) { return ''; } $output = ''; $parent_field = $this->db_fields['parent']; $count = -1; if ( -1 == $max_depth ) { $total_top = count( $elements ); } if ( $page_num < 1 || $per_page < 0 ) { // No paging. $paging = false; $start = 0; if ( -1 == $max_depth ) { $end = $total_top; } $this->max_pages = 1; } else { $paging = true; $start = ( (int) $page_num - 1 ) * (int) $per_page; $end = $start + $per_page; if ( -1 == $max_depth ) { $this->max_pages = ceil( $total_top / $per_page ); } } // Flat display. if ( -1 == $max_depth ) { if ( ! empty( $args[0]['reverse_top_level'] ) ) { $elements = array_reverse( $elements ); $oldstart = $start; $start = $total_top - $end; $end = $total_top - $oldstart; } $empty_array = array(); foreach ( $elements as $e ) { $count++; if ( $count < $start ) { continue; } if ( $count >= $end ) { break; } $this->display_element( $e, $empty_array, 1, 0, $args, $output ); } return $output; } /* * Separate elements into two buckets: top level and children elements. * Children_elements is two dimensional array, e.g. * $children_elements[10][] contains all sub-elements whose parent is 10. */ $top_level_elements = array(); $children_elements = array(); foreach ( $elements as $e ) { if ( empty( $e->$parent_field ) ) { $top_level_elements[] = $e; } else { $children_elements[ $e->$parent_field ][] = $e; } } $total_top = count( $top_level_elements ); if ( $paging ) { $this->max_pages = ceil( $total_top / $per_page ); } else { $end = $total_top; } if ( ! empty( $args[0]['reverse_top_level'] ) ) { $top_level_elements = array_reverse( $top_level_elements ); $oldstart = $start; $start = $total_top - $end; $end = $total_top - $oldstart; } if ( ! empty( $args[0]['reverse_children'] ) ) { foreach ( $children_elements as $parent => $children ) { $children_elements[ $parent ] = array_reverse( $children ); } } foreach ( $top_level_elements as $e ) { $count++; // For the last page, need to unset earlier children in order to keep track of orphans. if ( $end >= $total_top && $count < $start ) { $this->unset_children( $e, $children_elements ); } if ( $count < $start ) { continue; } if ( $count >= $end ) { break; } $this->display_element( $e, $children_elements, $max_depth, 0, $args, $output ); } if ( $end >= $total_top && count( $children_elements ) > 0 ) { $empty_array = array(); foreach ( $children_elements as $orphans ) { foreach ( $orphans as $op ) { $this->display_element( $op, $empty_array, 1, 0, $args, $output ); } } } return $output; } /** * Calculates the total number of root elements. * * @since 2.7.0 * * @param array $elements Elements to list. * @return int Number of root elements. */ public function get_number_of_root_elements( $elements ) { $num = 0; $parent_field = $this->db_fields['parent']; foreach ( $elements as $e ) { if ( empty( $e->$parent_field ) ) { $num++; } } return $num; } /** * Unsets all the children for a given top level element. * * @since 2.7.0 * * @param object $element The top level element. * @param array $children_elements The children elements. */ public function unset_children( $element, &$children_elements ) { if ( ! $element || ! $children_elements ) { return; } $id_field = $this->db_fields['id']; $id = $element->$id_field; if ( ! empty( $children_elements[ $id ] ) && is_array( $children_elements[ $id ] ) ) { foreach ( (array) $children_elements[ $id ] as $child ) { $this->unset_children( $child, $children_elements ); } } unset( $children_elements[ $id ] ); } } ``` | Used By | Description | | --- | --- | | [Walker\_Category\_Checklist](walker_category_checklist) wp-admin/includes/class-walker-category-checklist.php | Core walker class to output an unordered list of category checkbox input elements. | | [Walker\_Category](walker_category) wp-includes/class-walker-category.php | Core class used to create an HTML list of categories. | | [Walker\_CategoryDropdown](walker_categorydropdown) wp-includes/class-walker-category-dropdown.php | Core class used to create an HTML dropdown list of Categories. | | [Walker\_Nav\_Menu](walker_nav_menu) wp-includes/class-walker-nav-menu.php | Core class used to implement an HTML list of nav menu items. | | [Walker\_PageDropdown](walker_pagedropdown) wp-includes/class-walker-page-dropdown.php | Core class used to create an HTML drop-down list of pages. | | [Walker\_Page](walker_page) wp-includes/class-walker-page.php | Core walker class used to create an HTML list of pages. | | [Walker\_Comment](walker_comment) wp-includes/class-walker-comment.php | Core walker class used to create an HTML list of comments. | | Version | Description | | --- | --- | | [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Search_Handler {} class WP\_REST\_Search\_Handler {} ================================== Core base class representing a search handler for an object type in the REST API. * [get\_subtypes](wp_rest_search_handler/get_subtypes) β€” Gets the object subtypes managed by this search handler. * [get\_type](wp_rest_search_handler/get_type) β€” Gets the object type managed by this search handler. * [prepare\_item](wp_rest_search_handler/prepare_item) β€” Prepares the search result for a given ID. * [prepare\_item\_links](wp_rest_search_handler/prepare_item_links) β€” Prepares links for the search result of a given ID. * [search\_items](wp_rest_search_handler/search_items) β€” Searches the object type content for a given search request. File: `wp-includes/rest-api/search/class-wp-rest-search-handler.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/search/class-wp-rest-search-handler.php/) ``` abstract class WP_REST_Search_Handler { /** * Field containing the IDs in the search result. */ const RESULT_IDS = 'ids'; /** * Field containing the total count in the search result. */ const RESULT_TOTAL = 'total'; /** * Object type managed by this search handler. * * @since 5.0.0 * @var string */ protected $type = ''; /** * Object subtypes managed by this search handler. * * @since 5.0.0 * @var array */ protected $subtypes = array(); /** * Gets the object type managed by this search handler. * * @since 5.0.0 * * @return string Object type identifier. */ public function get_type() { return $this->type; } /** * Gets the object subtypes managed by this search handler. * * @since 5.0.0 * * @return array Array of object subtype identifiers. */ public function get_subtypes() { return $this->subtypes; } /** * Searches the object type content for a given search request. * * @since 5.0.0 * * @param WP_REST_Request $request Full REST request. * @return array Associative array containing an `WP_REST_Search_Handler::RESULT_IDS` containing * an array of found IDs and `WP_REST_Search_Handler::RESULT_TOTAL` containing the * total count for the matching search results. */ abstract public function search_items( WP_REST_Request $request ); /** * Prepares the search result for a given ID. * * @since 5.0.0 * @since 5.6.0 The `$id` parameter can accept a string. * * @param int|string $id Item ID. * @param array $fields Fields to include for the item. * @return array Associative array containing all fields for the item. */ abstract public function prepare_item( $id, array $fields ); /** * Prepares links for the search result of a given ID. * * @since 5.0.0 * @since 5.6.0 The `$id` parameter can accept a string. * * @param int|string $id Item ID. * @return array Links for the given item. */ abstract public function prepare_item_links( $id ); } ``` | Used By | Description | | --- | --- | | [WP\_REST\_Term\_Search\_Handler](wp_rest_term_search_handler) wp-includes/rest-api/search/class-wp-rest-term-search-handler.php | Core class representing a search handler for terms in the REST API. | | [WP\_REST\_Post\_Format\_Search\_Handler](wp_rest_post_format_search_handler) wp-includes/rest-api/search/class-wp-rest-post-format-search-handler.php | Core class representing a search handler for post formats in the REST API. | | [WP\_REST\_Post\_Search\_Handler](wp_rest_post_search_handler) wp-includes/rest-api/search/class-wp-rest-post-search-handler.php | Core class representing a search handler for posts in the REST API. | | Version | Description | | --- | --- | | [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. | wordpress class POMO_CachedFileReader {} class POMO\_CachedFileReader {} =============================== Reads the contents of the file in the beginning. * [\_\_construct](pomo_cachedfilereader/__construct) β€” PHP5 constructor. * [POMO\_CachedFileReader](pomo_cachedfilereader/pomo_cachedfilereader) β€” PHP4 constructor. β€” deprecated File: `wp-includes/pomo/streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/streams.php/) ``` class POMO_CachedFileReader extends POMO_StringReader { /** * PHP5 constructor. */ public function __construct( $filename ) { parent::__construct(); $this->_str = file_get_contents( $filename ); if ( false === $this->_str ) { return false; } $this->_pos = 0; } /** * PHP4 constructor. * * @deprecated 5.4.0 Use __construct() instead. * * @see POMO_CachedFileReader::__construct() */ public function POMO_CachedFileReader( $filename ) { _deprecated_constructor( self::class, '5.4.0', static::class ); self::__construct( $filename ); } } ``` | Uses | Description | | --- | --- | | [POMO\_StringReader](pomo_stringreader) wp-includes/pomo/streams.php | Provides file-like methods for manipulating a string instead of a physical file. | | Used By | Description | | --- | --- | | [POMO\_CachedIntFileReader](pomo_cachedintfilereader) wp-includes/pomo/streams.php | Reads the contents of the file in the beginning. | wordpress class WP_Privacy_Data_Removal_Requests_Table {} class WP\_Privacy\_Data\_Removal\_Requests\_Table {} ==================================================== This class has been deprecated. Previous class for list table for privacy data erasure requests. * [\_\_construct](wp_privacy_data_removal_requests_table/__construct) * [column\_email](wp_privacy_data_removal_requests_table/column_email) β€” Actions column. * [column\_next\_steps](wp_privacy_data_removal_requests_table/column_next_steps) β€” Next steps column. File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/) ``` class WP_Privacy_Data_Removal_Requests_Table extends WP_Privacy_Data_Removal_Requests_List_Table { function __construct( $args ) { _deprecated_function( __CLASS__, '5.3.0', 'WP_Privacy_Data_Removal_Requests_List_Table' ); if ( ! isset( $args['screen'] ) || $args['screen'] === 'remove_personal_data' ) { $args['screen'] = 'erase-personal-data'; } parent::__construct( $args ); } } ``` | Uses | Description | | --- | --- | | [WP\_Privacy\_Data\_Removal\_Requests\_List\_Table](wp_privacy_data_removal_requests_list_table) wp-admin/includes/class-wp-privacy-data-removal-requests-list-table.php | [WP\_Privacy\_Data\_Removal\_Requests\_List\_Table](wp_privacy_data_removal_requests_list_table) class. | | Version | Description | | --- | --- | | [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | This class has been deprecated. | | [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. | wordpress class WP_Tax_Query {} class WP\_Tax\_Query {} ======================= Core class used to implement taxonomy queries for the Taxonomy API. Used for generating SQL clauses that filter a primary query according to object taxonomy terms. [WP\_Tax\_Query](wp_tax_query) is a helper that allows primary query classes, such as [WP\_Query](wp_query), to filter their results by object metadata, by generating `JOIN` and `WHERE` subclauses to be attached to the primary SQL query string. * [\_\_construct](wp_tax_query/__construct) β€” Constructor. * [clean\_query](wp_tax_query/clean_query) β€” Validates a single query. * [find\_compatible\_table\_alias](wp_tax_query/find_compatible_table_alias) β€” Identifies an existing table alias that is compatible with the current query clause. * [get\_sql](wp_tax_query/get_sql) β€” Generates SQL clauses to be appended to a main query. * [get\_sql\_clauses](wp_tax_query/get_sql_clauses) β€” Generates SQL clauses to be appended to a main query. * [get\_sql\_for\_clause](wp_tax_query/get_sql_for_clause) β€” Generates SQL JOIN and WHERE clauses for a "first-order" query clause. * [get\_sql\_for\_query](wp_tax_query/get_sql_for_query) β€” Generates SQL clauses for a single query array. * [is\_first\_order\_clause](wp_tax_query/is_first_order_clause) β€” Determines whether a clause is first-order. * [sanitize\_query](wp_tax_query/sanitize_query) β€” Ensures the 'tax\_query' argument passed to the class constructor is well-formed. * [sanitize\_relation](wp_tax_query/sanitize_relation) β€” Sanitizes a 'relation' operator. * [transform\_query](wp_tax_query/transform_query) β€” Transforms a single query, from one field to another. File: `wp-includes/class-wp-tax-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-tax-query.php/) ``` class WP_Tax_Query { /** * Array of taxonomy queries. * * See WP_Tax_Query::__construct() for information on tax query arguments. * * @since 3.1.0 * @var array */ public $queries = array(); /** * The relation between the queries. Can be one of 'AND' or 'OR'. * * @since 3.1.0 * @var string */ public $relation; /** * Standard response when the query should not return any rows. * * @since 3.2.0 * @var string */ private static $no_results = array( 'join' => array( '' ), 'where' => array( '0 = 1' ), ); /** * A flat list of table aliases used in the JOIN clauses. * * @since 4.1.0 * @var array */ protected $table_aliases = array(); /** * Terms and taxonomies fetched by this query. * * We store this data in a flat array because they are referenced in a * number of places by WP_Query. * * @since 4.1.0 * @var array */ public $queried_terms = array(); /** * Database table that where the metadata's objects are stored (eg $wpdb->users). * * @since 4.1.0 * @var string */ public $primary_table; /** * Column in 'primary_table' that represents the ID of the object. * * @since 4.1.0 * @var string */ public $primary_id_column; /** * Constructor. * * @since 3.1.0 * @since 4.1.0 Added support for `$operator` 'NOT EXISTS' and 'EXISTS' values. * * @param array $tax_query { * Array of taxonomy query clauses. * * @type string $relation Optional. The MySQL keyword used to join * the clauses of the query. Accepts 'AND', or 'OR'. Default 'AND'. * @type array ...$0 { * An array of first-order clause parameters, or another fully-formed tax query. * * @type string $taxonomy Taxonomy being queried. Optional when field=term_taxonomy_id. * @type string|int|array $terms Term or terms to filter by. * @type string $field Field to match $terms against. Accepts 'term_id', 'slug', * 'name', or 'term_taxonomy_id'. Default: 'term_id'. * @type string $operator MySQL operator to be used with $terms in the WHERE clause. * Accepts 'AND', 'IN', 'NOT IN', 'EXISTS', 'NOT EXISTS'. * Default: 'IN'. * @type bool $include_children Optional. Whether to include child terms. * Requires a $taxonomy. Default: true. * } * } */ public function __construct( $tax_query ) { if ( isset( $tax_query['relation'] ) ) { $this->relation = $this->sanitize_relation( $tax_query['relation'] ); } else { $this->relation = 'AND'; } $this->queries = $this->sanitize_query( $tax_query ); } /** * Ensures the 'tax_query' argument passed to the class constructor is well-formed. * * Ensures that each query-level clause has a 'relation' key, and that * each first-order clause contains all the necessary keys from `$defaults`. * * @since 4.1.0 * * @param array $queries Array of queries clauses. * @return array Sanitized array of query clauses. */ public function sanitize_query( $queries ) { $cleaned_query = array(); $defaults = array( 'taxonomy' => '', 'terms' => array(), 'field' => 'term_id', 'operator' => 'IN', 'include_children' => true, ); foreach ( $queries as $key => $query ) { if ( 'relation' === $key ) { $cleaned_query['relation'] = $this->sanitize_relation( $query ); // First-order clause. } elseif ( self::is_first_order_clause( $query ) ) { $cleaned_clause = array_merge( $defaults, $query ); $cleaned_clause['terms'] = (array) $cleaned_clause['terms']; $cleaned_query[] = $cleaned_clause; /* * Keep a copy of the clause in the flate * $queried_terms array, for use in WP_Query. */ if ( ! empty( $cleaned_clause['taxonomy'] ) && 'NOT IN' !== $cleaned_clause['operator'] ) { $taxonomy = $cleaned_clause['taxonomy']; if ( ! isset( $this->queried_terms[ $taxonomy ] ) ) { $this->queried_terms[ $taxonomy ] = array(); } /* * Backward compatibility: Only store the first * 'terms' and 'field' found for a given taxonomy. */ if ( ! empty( $cleaned_clause['terms'] ) && ! isset( $this->queried_terms[ $taxonomy ]['terms'] ) ) { $this->queried_terms[ $taxonomy ]['terms'] = $cleaned_clause['terms']; } if ( ! empty( $cleaned_clause['field'] ) && ! isset( $this->queried_terms[ $taxonomy ]['field'] ) ) { $this->queried_terms[ $taxonomy ]['field'] = $cleaned_clause['field']; } } // Otherwise, it's a nested query, so we recurse. } elseif ( is_array( $query ) ) { $cleaned_subquery = $this->sanitize_query( $query ); if ( ! empty( $cleaned_subquery ) ) { // All queries with children must have a relation. if ( ! isset( $cleaned_subquery['relation'] ) ) { $cleaned_subquery['relation'] = 'AND'; } $cleaned_query[] = $cleaned_subquery; } } } return $cleaned_query; } /** * Sanitizes a 'relation' operator. * * @since 4.1.0 * * @param string $relation Raw relation key from the query argument. * @return string Sanitized relation ('AND' or 'OR'). */ public function sanitize_relation( $relation ) { if ( 'OR' === strtoupper( $relation ) ) { return 'OR'; } else { return 'AND'; } } /** * Determines whether a clause is first-order. * * A "first-order" clause is one that contains any of the first-order * clause keys ('terms', 'taxonomy', 'include_children', 'field', * 'operator'). An empty clause also counts as a first-order clause, * for backward compatibility. Any clause that doesn't meet this is * determined, by process of elimination, to be a higher-order query. * * @since 4.1.0 * * @param array $query Tax query arguments. * @return bool Whether the query clause is a first-order clause. */ protected static function is_first_order_clause( $query ) { return is_array( $query ) && ( empty( $query ) || array_key_exists( 'terms', $query ) || array_key_exists( 'taxonomy', $query ) || array_key_exists( 'include_children', $query ) || array_key_exists( 'field', $query ) || array_key_exists( 'operator', $query ) ); } /** * Generates SQL clauses to be appended to a main query. * * @since 3.1.0 * * @param string $primary_table Database table where the object being filtered is stored (eg wp_users). * @param string $primary_id_column ID column for the filtered object in $primary_table. * @return string[] { * Array containing JOIN and WHERE SQL clauses to append to the main query. * * @type string $join SQL fragment to append to the main JOIN clause. * @type string $where SQL fragment to append to the main WHERE clause. * } */ public function get_sql( $primary_table, $primary_id_column ) { $this->primary_table = $primary_table; $this->primary_id_column = $primary_id_column; return $this->get_sql_clauses(); } /** * Generates SQL clauses to be appended to a main query. * * Called by the public WP_Tax_Query::get_sql(), this method * is abstracted out to maintain parity with the other Query classes. * * @since 4.1.0 * * @return string[] { * Array containing JOIN and WHERE SQL clauses to append to the main query. * * @type string $join SQL fragment to append to the main JOIN clause. * @type string $where SQL fragment to append to the main WHERE clause. * } */ protected function get_sql_clauses() { /* * $queries are passed by reference to get_sql_for_query() for recursion. * To keep $this->queries unaltered, pass a copy. */ $queries = $this->queries; $sql = $this->get_sql_for_query( $queries ); if ( ! empty( $sql['where'] ) ) { $sql['where'] = ' AND ' . $sql['where']; } return $sql; } /** * Generates SQL clauses for a single query array. * * If nested subqueries are found, this method recurses the tree to * produce the properly nested SQL. * * @since 4.1.0 * * @param array $query Query to parse (passed by reference). * @param int $depth Optional. Number of tree levels deep we currently are. * Used to calculate indentation. Default 0. * @return string[] { * Array containing JOIN and WHERE SQL clauses to append to a single query array. * * @type string $join SQL fragment to append to the main JOIN clause. * @type string $where SQL fragment to append to the main WHERE clause. * } */ protected function get_sql_for_query( &$query, $depth = 0 ) { $sql_chunks = array( 'join' => array(), 'where' => array(), ); $sql = array( 'join' => '', 'where' => '', ); $indent = ''; for ( $i = 0; $i < $depth; $i++ ) { $indent .= ' '; } foreach ( $query as $key => &$clause ) { if ( 'relation' === $key ) { $relation = $query['relation']; } elseif ( is_array( $clause ) ) { // This is a first-order clause. if ( $this->is_first_order_clause( $clause ) ) { $clause_sql = $this->get_sql_for_clause( $clause, $query ); $where_count = count( $clause_sql['where'] ); if ( ! $where_count ) { $sql_chunks['where'][] = ''; } elseif ( 1 === $where_count ) { $sql_chunks['where'][] = $clause_sql['where'][0]; } else { $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )'; } $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] ); // This is a subquery, so we recurse. } else { $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 ); $sql_chunks['where'][] = $clause_sql['where']; $sql_chunks['join'][] = $clause_sql['join']; } } } // Filter to remove empties. $sql_chunks['join'] = array_filter( $sql_chunks['join'] ); $sql_chunks['where'] = array_filter( $sql_chunks['where'] ); if ( empty( $relation ) ) { $relation = 'AND'; } // Filter duplicate JOIN clauses and combine into a single string. if ( ! empty( $sql_chunks['join'] ) ) { $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) ); } // Generate a single WHERE clause with proper brackets and indentation. if ( ! empty( $sql_chunks['where'] ) ) { $sql['where'] = '( ' . "\n " . $indent . implode( ' ' . "\n " . $indent . $relation . ' ' . "\n " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')'; } return $sql; } /** * Generates SQL JOIN and WHERE clauses for a "first-order" query clause. * * @since 4.1.0 * * @global wpdb $wpdb The WordPress database abstraction object. * * @param array $clause Query clause (passed by reference). * @param array $parent_query Parent query array. * @return string[] { * Array containing JOIN and WHERE SQL clauses to append to a first-order query. * * @type string $join SQL fragment to append to the main JOIN clause. * @type string $where SQL fragment to append to the main WHERE clause. * } */ public function get_sql_for_clause( &$clause, $parent_query ) { global $wpdb; $sql = array( 'where' => array(), 'join' => array(), ); $join = ''; $where = ''; $this->clean_query( $clause ); if ( is_wp_error( $clause ) ) { return self::$no_results; } $terms = $clause['terms']; $operator = strtoupper( $clause['operator'] ); if ( 'IN' === $operator ) { if ( empty( $terms ) ) { return self::$no_results; } $terms = implode( ',', $terms ); /* * Before creating another table join, see if this clause has a * sibling with an existing join that can be shared. */ $alias = $this->find_compatible_table_alias( $clause, $parent_query ); if ( false === $alias ) { $i = count( $this->table_aliases ); $alias = $i ? 'tt' . $i : $wpdb->term_relationships; // Store the alias as part of a flat array to build future iterators. $this->table_aliases[] = $alias; // Store the alias with this clause, so later siblings can use it. $clause['alias'] = $alias; $join .= " LEFT JOIN $wpdb->term_relationships"; $join .= $i ? " AS $alias" : ''; $join .= " ON ($this->primary_table.$this->primary_id_column = $alias.object_id)"; } $where = "$alias.term_taxonomy_id $operator ($terms)"; } elseif ( 'NOT IN' === $operator ) { if ( empty( $terms ) ) { return $sql; } $terms = implode( ',', $terms ); $where = "$this->primary_table.$this->primary_id_column NOT IN ( SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id IN ($terms) )"; } elseif ( 'AND' === $operator ) { if ( empty( $terms ) ) { return $sql; } $num_terms = count( $terms ); $terms = implode( ',', $terms ); $where = "( SELECT COUNT(1) FROM $wpdb->term_relationships WHERE term_taxonomy_id IN ($terms) AND object_id = $this->primary_table.$this->primary_id_column ) = $num_terms"; } elseif ( 'NOT EXISTS' === $operator || 'EXISTS' === $operator ) { $where = $wpdb->prepare( "$operator ( SELECT 1 FROM $wpdb->term_relationships INNER JOIN $wpdb->term_taxonomy ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id WHERE $wpdb->term_taxonomy.taxonomy = %s AND $wpdb->term_relationships.object_id = $this->primary_table.$this->primary_id_column )", $clause['taxonomy'] ); } $sql['join'][] = $join; $sql['where'][] = $where; return $sql; } /** * Identifies an existing table alias that is compatible with the current query clause. * * We avoid unnecessary table joins by allowing each clause to look for * an existing table alias that is compatible with the query that it * needs to perform. * * An existing alias is compatible if (a) it is a sibling of `$clause` * (ie, it's under the scope of the same relation), and (b) the combination * of operator and relation between the clauses allows for a shared table * join. In the case of WP_Tax_Query, this only applies to 'IN' * clauses that are connected by the relation 'OR'. * * @since 4.1.0 * * @param array $clause Query clause. * @param array $parent_query Parent query of $clause. * @return string|false Table alias if found, otherwise false. */ protected function find_compatible_table_alias( $clause, $parent_query ) { $alias = false; // Sanity check. Only IN queries use the JOIN syntax. if ( ! isset( $clause['operator'] ) || 'IN' !== $clause['operator'] ) { return $alias; } // Since we're only checking IN queries, we're only concerned with OR relations. if ( ! isset( $parent_query['relation'] ) || 'OR' !== $parent_query['relation'] ) { return $alias; } $compatible_operators = array( 'IN' ); foreach ( $parent_query as $sibling ) { if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) { continue; } if ( empty( $sibling['alias'] ) || empty( $sibling['operator'] ) ) { continue; } // The sibling must both have compatible operator to share its alias. if ( in_array( strtoupper( $sibling['operator'] ), $compatible_operators, true ) ) { $alias = preg_replace( '/\W/', '_', $sibling['alias'] ); break; } } return $alias; } /** * Validates a single query. * * @since 3.2.0 * * @param array $query The single query. Passed by reference. */ private function clean_query( &$query ) { if ( empty( $query['taxonomy'] ) ) { if ( 'term_taxonomy_id' !== $query['field'] ) { $query = new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) ); return; } // So long as there are shared terms, 'include_children' requires that a taxonomy is set. $query['include_children'] = false; } elseif ( ! taxonomy_exists( $query['taxonomy'] ) ) { $query = new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) ); return; } if ( 'slug' === $query['field'] || 'name' === $query['field'] ) { $query['terms'] = array_unique( (array) $query['terms'] ); } else { $query['terms'] = wp_parse_id_list( $query['terms'] ); } if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) { $this->transform_query( $query, 'term_id' ); if ( is_wp_error( $query ) ) { return; } $children = array(); foreach ( $query['terms'] as $term ) { $children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) ); $children[] = $term; } $query['terms'] = $children; } $this->transform_query( $query, 'term_taxonomy_id' ); } /** * Transforms a single query, from one field to another. * * Operates on the `$query` object by reference. In the case of error, * `$query` is converted to a WP_Error object. * * @since 3.2.0 * * @global wpdb $wpdb The WordPress database abstraction object. * * @param array $query The single query. Passed by reference. * @param string $resulting_field The resulting field. Accepts 'slug', 'name', 'term_taxonomy_id', * or 'term_id'. Default 'term_id'. */ public function transform_query( &$query, $resulting_field ) { if ( empty( $query['terms'] ) ) { return; } if ( $query['field'] == $resulting_field ) { return; } $resulting_field = sanitize_key( $resulting_field ); // Empty 'terms' always results in a null transformation. $terms = array_filter( $query['terms'] ); if ( empty( $terms ) ) { $query['terms'] = array(); $query['field'] = $resulting_field; return; } $args = array( 'get' => 'all', 'number' => 0, 'taxonomy' => $query['taxonomy'], 'update_term_meta_cache' => false, 'orderby' => 'none', ); // Term query parameter name depends on the 'field' being searched on. switch ( $query['field'] ) { case 'slug': $args['slug'] = $terms; break; case 'name': $args['name'] = $terms; break; case 'term_taxonomy_id': $args['term_taxonomy_id'] = $terms; break; default: $args['include'] = wp_parse_id_list( $terms ); break; } if ( ! is_taxonomy_hierarchical( $query['taxonomy'] ) ) { $args['number'] = count( $terms ); } $term_query = new WP_Term_Query(); $term_list = $term_query->query( $args ); if ( is_wp_error( $term_list ) ) { $query = $term_list; return; } if ( 'AND' === $query['operator'] && count( $term_list ) < count( $query['terms'] ) ) { $query = new WP_Error( 'inexistent_terms', __( 'Inexistent terms.' ) ); return; } $query['terms'] = wp_list_pluck( $term_list, $resulting_field ); $query['field'] = $resulting_field; } } ``` | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Post_Types_Controller {} class WP\_REST\_Post\_Types\_Controller {} ========================================== Core class to access post types via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_post_types_controller/__construct) β€” Constructor. * [get\_collection\_params](wp_rest_post_types_controller/get_collection_params) β€” Retrieves the query params for collections. * [get\_item](wp_rest_post_types_controller/get_item) β€” Retrieves a specific post type. * [get\_item\_schema](wp_rest_post_types_controller/get_item_schema) β€” Retrieves the post type's schema, conforming to JSON Schema. * [get\_items](wp_rest_post_types_controller/get_items) β€” Retrieves all public post types. * [get\_items\_permissions\_check](wp_rest_post_types_controller/get_items_permissions_check) β€” Checks whether a given request has permission to read types. * [prepare\_item\_for\_response](wp_rest_post_types_controller/prepare_item_for_response) β€” Prepares a post type object for serialization. * [prepare\_links](wp_rest_post_types_controller/prepare_links) β€” Prepares links for the request. * [register\_routes](wp_rest_post_types_controller/register_routes) β€” Registers the routes for post types. File: `wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php/) ``` class WP_REST_Post_Types_Controller extends WP_REST_Controller { /** * Constructor. * * @since 4.7.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'types'; } /** * Registers the routes for post types. * * @since 4.7.0 * * @see register_rest_route() */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => $this->get_collection_params(), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<type>[\w-]+)', array( 'args' => array( 'type' => array( 'description' => __( 'An alphanumeric identifier for the post type.' ), 'type' => 'string', ), ), array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'permission_callback' => '__return_true', 'args' => array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks whether a given request has permission to read types. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { if ( 'edit' === $request['context'] ) { $types = get_post_types( array( 'show_in_rest' => true ), 'objects' ); foreach ( $types as $type ) { if ( current_user_can( $type->cap->edit_posts ) ) { return true; } } return new WP_Error( 'rest_cannot_view', __( 'Sorry, you are not allowed to edit posts in this post type.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Retrieves all public post types. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { $data = array(); $types = get_post_types( array( 'show_in_rest' => true ), 'objects' ); foreach ( $types as $type ) { if ( 'edit' === $request['context'] && ! current_user_can( $type->cap->edit_posts ) ) { continue; } $post_type = $this->prepare_item_for_response( $type, $request ); $data[ $type->name ] = $this->prepare_response_for_collection( $post_type ); } return rest_ensure_response( $data ); } /** * Retrieves a specific post type. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { $obj = get_post_type_object( $request['type'] ); if ( empty( $obj ) ) { return new WP_Error( 'rest_type_invalid', __( 'Invalid post type.' ), array( 'status' => 404 ) ); } if ( empty( $obj->show_in_rest ) ) { return new WP_Error( 'rest_cannot_read_type', __( 'Cannot view post type.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( 'edit' === $request['context'] && ! current_user_can( $obj->cap->edit_posts ) ) { return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit posts in this post type.' ), array( 'status' => rest_authorization_required_code() ) ); } $data = $this->prepare_item_for_response( $obj, $request ); return rest_ensure_response( $data ); } /** * Prepares a post type object for serialization. * * @since 4.7.0 * @since 5.9.0 Renamed `$post_type` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Post_Type $item Post type object. * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response Response object. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $post_type = $item; $taxonomies = wp_list_filter( get_object_taxonomies( $post_type->name, 'objects' ), array( 'show_in_rest' => true ) ); $taxonomies = wp_list_pluck( $taxonomies, 'name' ); $base = ! empty( $post_type->rest_base ) ? $post_type->rest_base : $post_type->name; $namespace = ! empty( $post_type->rest_namespace ) ? $post_type->rest_namespace : 'wp/v2'; $supports = get_all_post_type_supports( $post_type->name ); $fields = $this->get_fields_for_response( $request ); $data = array(); if ( rest_is_field_included( 'capabilities', $fields ) ) { $data['capabilities'] = $post_type->cap; } if ( rest_is_field_included( 'description', $fields ) ) { $data['description'] = $post_type->description; } if ( rest_is_field_included( 'hierarchical', $fields ) ) { $data['hierarchical'] = $post_type->hierarchical; } if ( rest_is_field_included( 'has_archive', $fields ) ) { $data['has_archive'] = $post_type->has_archive; } if ( rest_is_field_included( 'visibility', $fields ) ) { $data['visibility'] = array( 'show_in_nav_menus' => (bool) $post_type->show_in_nav_menus, 'show_ui' => (bool) $post_type->show_ui, ); } if ( rest_is_field_included( 'viewable', $fields ) ) { $data['viewable'] = is_post_type_viewable( $post_type ); } if ( rest_is_field_included( 'labels', $fields ) ) { $data['labels'] = $post_type->labels; } if ( rest_is_field_included( 'name', $fields ) ) { $data['name'] = $post_type->label; } if ( rest_is_field_included( 'slug', $fields ) ) { $data['slug'] = $post_type->name; } if ( rest_is_field_included( 'icon', $fields ) ) { $data['icon'] = $post_type->menu_icon; } if ( rest_is_field_included( 'supports', $fields ) ) { $data['supports'] = $supports; } if ( rest_is_field_included( 'taxonomies', $fields ) ) { $data['taxonomies'] = array_values( $taxonomies ); } if ( rest_is_field_included( 'rest_base', $fields ) ) { $data['rest_base'] = $base; } if ( rest_is_field_included( 'rest_namespace', $fields ) ) { $data['rest_namespace'] = $namespace; } $context = ! empty( $request['context'] ) ? $request['context'] : 'view'; $data = $this->add_additional_fields_to_object( $data, $request ); $data = $this->filter_response_by_context( $data, $context ); // Wrap the data in a response object. $response = rest_ensure_response( $data ); if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { $response->add_links( $this->prepare_links( $post_type ) ); } /** * Filters a post type returned from the REST API. * * Allows modification of the post type data right before it is returned. * * @since 4.7.0 * * @param WP_REST_Response $response The response object. * @param WP_Post_Type $post_type The original post type object. * @param WP_REST_Request $request Request used to generate the response. */ return apply_filters( 'rest_prepare_post_type', $response, $post_type, $request ); } /** * Prepares links for the request. * * @since 6.1.0 * * @param WP_Post_Type $post_type The post type. * @return array Links for the given post type. */ protected function prepare_links( $post_type ) { return array( 'collection' => array( 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ), ), 'https://api.w.org/items' => array( 'href' => rest_url( rest_get_route_for_post_type_items( $post_type->name ) ), ), ); } /** * Retrieves the post type's schema, conforming to JSON Schema. * * @since 4.7.0 * @since 4.8.0 The `supports` property was added. * @since 5.9.0 The `visibility` and `rest_namespace` properties were added. * @since 6.1.0 The `icon` property was added. * * @return array Item schema data. */ public function get_item_schema() { if ( $this->schema ) { return $this->add_additional_fields_schema( $this->schema ); } $schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'type', 'type' => 'object', 'properties' => array( 'capabilities' => array( 'description' => __( 'All capabilities used by the post type.' ), 'type' => 'object', 'context' => array( 'edit' ), 'readonly' => true, ), 'description' => array( 'description' => __( 'A human-readable description of the post type.' ), 'type' => 'string', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), 'hierarchical' => array( 'description' => __( 'Whether or not the post type should have children.' ), 'type' => 'boolean', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), 'viewable' => array( 'description' => __( 'Whether or not the post type can be viewed.' ), 'type' => 'boolean', 'context' => array( 'edit' ), 'readonly' => true, ), 'labels' => array( 'description' => __( 'Human-readable labels for the post type for various contexts.' ), 'type' => 'object', 'context' => array( 'edit' ), 'readonly' => true, ), 'name' => array( 'description' => __( 'The title for the post type.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'slug' => array( 'description' => __( 'An alphanumeric identifier for the post type.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'supports' => array( 'description' => __( 'All features, supported by the post type.' ), 'type' => 'object', 'context' => array( 'edit' ), 'readonly' => true, ), 'has_archive' => array( 'description' => __( 'If the value is a string, the value will be used as the archive slug. If the value is false the post type has no archive.' ), 'type' => array( 'string', 'boolean' ), 'context' => array( 'view', 'edit' ), 'readonly' => true, ), 'taxonomies' => array( 'description' => __( 'Taxonomies associated with post type.' ), 'type' => 'array', 'items' => array( 'type' => 'string', ), 'context' => array( 'view', 'edit' ), 'readonly' => true, ), 'rest_base' => array( 'description' => __( 'REST base route for the post type.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'rest_namespace' => array( 'description' => __( 'REST route\'s namespace for the post type.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'visibility' => array( 'description' => __( 'The visibility settings for the post type.' ), 'type' => 'object', 'context' => array( 'edit' ), 'readonly' => true, 'properties' => array( 'show_ui' => array( 'description' => __( 'Whether to generate a default UI for managing this post type.' ), 'type' => 'boolean', ), 'show_in_nav_menus' => array( 'description' => __( 'Whether to make the post type available for selection in navigation menus.' ), 'type' => 'boolean', ), ), ), 'icon' => array( 'description' => __( 'The icon for the post type.' ), 'type' => array( 'string', 'null' ), 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), ), ); $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the query params for collections. * * @since 4.7.0 * * @return array Collection parameters. */ public function get_collection_params() { return array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. | wordpress class WP_Style_Engine_Processor {} class WP\_Style\_Engine\_Processor {} ===================================== Class [WP\_Style\_Engine\_Processor](wp_style_engine_processor). Compiles styles from stores or collection of CSS rules. * [add\_rules](wp_style_engine_processor/add_rules) β€” Adds rules to be processed. * [add\_store](wp_style_engine_processor/add_store) β€” Adds a store to the processor. * [combine\_rules\_selectors](wp_style_engine_processor/combine_rules_selectors) β€” Combines selectors from the rules store when they have the same styles. * [get\_css](wp_style_engine_processor/get_css) β€” Gets the CSS rules as a string. File: `wp-includes/style-engine/class-wp-style-engine-processor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-processor.php/) ``` class WP_Style_Engine_Processor { /** * A collection of Style Engine Store objects. * * @since 6.1.0 * @var WP_Style_Engine_CSS_Rules_Store[] */ protected $stores = array(); /** * The set of CSS rules that this processor will work on. * * @since 6.1.0 * @var WP_Style_Engine_CSS_Rule[] */ protected $css_rules = array(); /** * Adds a store to the processor. * * @since 6.1.0 * * @param WP_Style_Engine_CSS_Rules_Store $store The store to add. * * @return WP_Style_Engine_Processor Returns the object to allow chaining methods. */ public function add_store( $store ) { if ( ! $store instanceof WP_Style_Engine_CSS_Rules_Store ) { _doing_it_wrong( __METHOD__, __( '$store must be an instance of WP_Style_Engine_CSS_Rules_Store' ), '6.1.0' ); return $this; } $this->stores[ $store->get_name() ] = $store; return $this; } /** * Adds rules to be processed. * * @since 6.1.0 * * @param WP_Style_Engine_CSS_Rule|WP_Style_Engine_CSS_Rule[] $css_rules A single, or an array of, WP_Style_Engine_CSS_Rule objects from a store or otherwise. * * @return WP_Style_Engine_Processor Returns the object to allow chaining methods. */ public function add_rules( $css_rules ) { if ( ! is_array( $css_rules ) ) { $css_rules = array( $css_rules ); } foreach ( $css_rules as $rule ) { $selector = $rule->get_selector(); if ( isset( $this->css_rules[ $selector ] ) ) { $this->css_rules[ $selector ]->add_declarations( $rule->get_declarations() ); continue; } $this->css_rules[ $rule->get_selector() ] = $rule; } return $this; } /** * Gets the CSS rules as a string. * * @since 6.1.0 * * @param array $options { * Optional. An array of options. Default empty array. * * @type bool $optimize Whether to optimize the CSS output, e.g., combine rules. Default is `false`. * @type bool $prettify Whether to add new lines and indents to output. Default is the test of whether the global constant `SCRIPT_DEBUG` is defined. * } * * @return string The computed CSS. */ public function get_css( $options = array() ) { $defaults = array( 'optimize' => true, 'prettify' => defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG, ); $options = wp_parse_args( $options, $defaults ); // If we have stores, get the rules from them. foreach ( $this->stores as $store ) { $this->add_rules( $store->get_all_rules() ); } // Combine CSS selectors that have identical declarations. if ( true === $options['optimize'] ) { $this->combine_rules_selectors(); } // Build the CSS. $css = ''; foreach ( $this->css_rules as $rule ) { $css .= $rule->get_css( $options['prettify'] ); $css .= $options['prettify'] ? "\n" : ''; } return $css; } /** * Combines selectors from the rules store when they have the same styles. * * @since 6.1.0 * * @return void */ private function combine_rules_selectors() { // Build an array of selectors along with the JSON-ified styles to make comparisons easier. $selectors_json = array(); foreach ( $this->css_rules as $rule ) { $declarations = $rule->get_declarations()->get_declarations(); ksort( $declarations ); $selectors_json[ $rule->get_selector() ] = wp_json_encode( $declarations ); } // Combine selectors that have the same styles. foreach ( $selectors_json as $selector => $json ) { // Get selectors that use the same styles. $duplicates = array_keys( $selectors_json, $json, true ); // Skip if there are no duplicates. if ( 1 >= count( $duplicates ) ) { continue; } $declarations = $this->css_rules[ $selector ]->get_declarations(); foreach ( $duplicates as $key ) { // Unset the duplicates from the $selectors_json array to avoid looping through them as well. unset( $selectors_json[ $key ] ); // Remove the rules from the rules collection. unset( $this->css_rules[ $key ] ); } // Create a new rule with the combined selectors. $duplicate_selectors = implode( ',', $duplicates ); $this->css_rules[ $duplicate_selectors ] = new WP_Style_Engine_CSS_Rule( $duplicate_selectors, $declarations ); } } } ``` | Version | Description | | --- | --- | | [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. | wordpress class Requests_Cookie {} class Requests\_Cookie {} ========================= Cookie storage object * [\_\_construct](requests_cookie/__construct) β€” Create a new cookie object * [\_\_toString](requests_cookie/__tostring) β€” Get the cookie value * [domain\_matches](requests_cookie/domain_matches) β€” Check if a cookie is valid for a given domain * [format\_for\_header](requests_cookie/format_for_header) β€” Format a cookie for a Cookie header * [format\_for\_set\_cookie](requests_cookie/format_for_set_cookie) β€” Format a cookie for a Set-Cookie header * [formatForHeader](requests_cookie/formatforheader) β€” Format a cookie for a Cookie header β€” deprecated * [formatForSetCookie](requests_cookie/formatforsetcookie) β€” Format a cookie for a Set-Cookie header β€” deprecated * [is\_expired](requests_cookie/is_expired) β€” Check if a cookie is expired. * [normalize](requests_cookie/normalize) β€” Normalize cookie and attributes * [normalize\_attribute](requests_cookie/normalize_attribute) β€” Parse an individual cookie attribute * [parse](requests_cookie/parse) β€” Parse a cookie string into a cookie object * [parse\_from\_headers](requests_cookie/parse_from_headers) β€” Parse all Set-Cookie headers from request headers * [parseFromHeaders](requests_cookie/parsefromheaders) β€” Parse all Set-Cookie headers from request headers β€” deprecated * [path\_matches](requests_cookie/path_matches) β€” Check if a cookie is valid for a given path * [uri\_matches](requests_cookie/uri_matches) β€” Check if a cookie is valid for a given URI File: `wp-includes/Requests/Cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie.php/) ``` class Requests_Cookie { /** * Cookie name. * * @var string */ public $name; /** * Cookie value. * * @var string */ public $value; /** * Cookie attributes * * Valid keys are (currently) path, domain, expires, max-age, secure and * httponly. * * @var Requests_Utility_CaseInsensitiveDictionary|array Array-like object */ public $attributes = array(); /** * Cookie flags * * Valid keys are (currently) creation, last-access, persistent and * host-only. * * @var array */ public $flags = array(); /** * Reference time for relative calculations * * This is used in place of `time()` when calculating Max-Age expiration and * checking time validity. * * @var int */ public $reference_time = 0; /** * Create a new cookie object * * @param string $name * @param string $value * @param array|Requests_Utility_CaseInsensitiveDictionary $attributes Associative array of attribute data */ 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(); } /** * Check if a cookie is expired. * * Checks the age against $this->reference_time to determine if the cookie * is expired. * * @return boolean True if expired, false if time is valid. */ 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; } /** * Check if a cookie is valid for a given URI * * @param Requests_IRI $uri URI to check * @return boolean Whether the cookie is valid for the given URI */ 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'; } /** * Check if a cookie is valid for a given domain * * @param string $string Domain to check * @return boolean Whether the cookie is valid for the given domain */ 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); } /** * Check if a cookie is valid for a given path * * From the path-match check in RFC 6265 section 5.1.4 * * @param string $request_path Path to check * @return boolean Whether the cookie is valid for the given path */ 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; } /** * Normalize cookie and attributes * * @return boolean Whether the cookie was successfully normalized */ 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; } /** * Parse an individual cookie attribute * * Handles parsing individual attributes from the cookie values. * * @param string $name Attribute name * @param string|boolean $value Attribute value (string value, or true if empty/flag) * @return mixed Value if available, or null if the attribute value is invalid (and should be skipped) */ 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; } } /** * Format a cookie for a Cookie header * * This is used when sending cookies to a server. * * @return string Cookie formatted for Cookie header */ public function format_for_header() { return sprintf('%s=%s', $this->name, $this->value); } /** * Format a cookie for a Cookie header * * @codeCoverageIgnore * @deprecated Use {@see Requests_Cookie::format_for_header} * @return string */ public function formatForHeader() { return $this->format_for_header(); } /** * 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. * * @return string Cookie formatted for Set-Cookie header */ 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; } /** * Format a cookie for a Set-Cookie header * * @codeCoverageIgnore * @deprecated Use {@see Requests_Cookie::format_for_set_cookie} * @return string */ public function formatForSetCookie() { return $this->format_for_set_cookie(); } /** * Get the cookie value * * Attributes and other data can be accessed via methods. */ public function __toString() { return $this->value; } /** * 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. * * @param string Cookie header value (from a Set-Cookie header) * @return Requests_Cookie Parsed cookie object */ 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); } /** * Parse all Set-Cookie headers from request headers * * @param Requests_Response_Headers $headers Headers to parse from * @param Requests_IRI|null $origin URI for comparing cookie origins * @param int|null $time Reference time for expiration calculation * @return array */ 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; } /** * Parse all Set-Cookie headers from request headers * * @codeCoverageIgnore * @deprecated Use {@see Requests_Cookie::parse_from_headers} * @return array */ public static function parseFromHeaders(Requests_Response_Headers $headers) { return self::parse_from_headers($headers); } } ```
programming_docs
wordpress class WP_Term {} class WP\_Term {} ================= Core class used to implement the [WP\_Term](wp_term) object. * [\_\_construct](wp_term/__construct) β€” Constructor. * [\_\_get](wp_term/__get) β€” Getter. * [filter](wp_term/filter) β€” Sanitizes term fields, according to the filter type provided. * [get\_instance](wp_term/get_instance) β€” Retrieve WP\_Term instance. * [to\_array](wp_term/to_array) β€” Converts an object to array. File: `wp-includes/class-wp-term.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-term.php/) ``` final class WP_Term { /** * Term ID. * * @since 4.4.0 * @var int */ public $term_id; /** * The term's name. * * @since 4.4.0 * @var string */ public $name = ''; /** * The term's slug. * * @since 4.4.0 * @var string */ public $slug = ''; /** * The term's term_group. * * @since 4.4.0 * @var int */ public $term_group = ''; /** * Term Taxonomy ID. * * @since 4.4.0 * @var int */ public $term_taxonomy_id = 0; /** * The term's taxonomy name. * * @since 4.4.0 * @var string */ public $taxonomy = ''; /** * The term's description. * * @since 4.4.0 * @var string */ public $description = ''; /** * ID of a term's parent term. * * @since 4.4.0 * @var int */ public $parent = 0; /** * Cached object count for this term. * * @since 4.4.0 * @var int */ public $count = 0; /** * Stores the term object's sanitization level. * * Does not correspond to a database field. * * @since 4.4.0 * @var string */ public $filter = 'raw'; /** * Retrieve WP_Term instance. * * @since 4.4.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $term_id Term ID. * @param string $taxonomy Optional. Limit matched terms to those matching `$taxonomy`. Only used for * disambiguating potentially shared terms. * @return WP_Term|WP_Error|false Term object, if found. WP_Error if `$term_id` is shared between taxonomies and * there's insufficient data to distinguish which term is intended. * False for other failures. */ public static function get_instance( $term_id, $taxonomy = null ) { global $wpdb; $term_id = (int) $term_id; if ( ! $term_id ) { return false; } $_term = wp_cache_get( $term_id, 'terms' ); // If there isn't a cached version, hit the database. if ( ! $_term || ( $taxonomy && $taxonomy !== $_term->taxonomy ) ) { // Any term found in the cache is not a match, so don't use it. $_term = false; // Grab all matching terms, in case any are shared between taxonomies. $terms = $wpdb->get_results( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE t.term_id = %d", $term_id ) ); if ( ! $terms ) { return false; } // If a taxonomy was specified, find a match. if ( $taxonomy ) { foreach ( $terms as $match ) { if ( $taxonomy === $match->taxonomy ) { $_term = $match; break; } } // If only one match was found, it's the one we want. } elseif ( 1 === count( $terms ) ) { $_term = reset( $terms ); // Otherwise, the term must be shared between taxonomies. } else { // If the term is shared only with invalid taxonomies, return the one valid term. foreach ( $terms as $t ) { if ( ! taxonomy_exists( $t->taxonomy ) ) { continue; } // Only hit if we've already identified a term in a valid taxonomy. if ( $_term ) { return new WP_Error( 'ambiguous_term_id', __( 'Term ID is shared between multiple taxonomies' ), $term_id ); } $_term = $t; } } if ( ! $_term ) { return false; } // Don't return terms from invalid taxonomies. if ( ! taxonomy_exists( $_term->taxonomy ) ) { return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) ); } $_term = sanitize_term( $_term, $_term->taxonomy, 'raw' ); // Don't cache terms that are shared between taxonomies. if ( 1 === count( $terms ) ) { wp_cache_add( $term_id, $_term, 'terms' ); } } $term_obj = new WP_Term( $_term ); $term_obj->filter( $term_obj->filter ); return $term_obj; } /** * Constructor. * * @since 4.4.0 * * @param WP_Term|object $term Term object. */ public function __construct( $term ) { foreach ( get_object_vars( $term ) as $key => $value ) { $this->$key = $value; } } /** * Sanitizes term fields, according to the filter type provided. * * @since 4.4.0 * * @param string $filter Filter context. Accepts 'edit', 'db', 'display', 'attribute', 'js', 'rss', or 'raw'. */ public function filter( $filter ) { sanitize_term( $this, $this->taxonomy, $filter ); } /** * Converts an object to array. * * @since 4.4.0 * * @return array Object as array. */ public function to_array() { return get_object_vars( $this ); } /** * Getter. * * @since 4.4.0 * * @param string $key Property to get. * @return mixed Property value. */ public function __get( $key ) { switch ( $key ) { case 'data': $data = new stdClass(); $columns = array( 'term_id', 'name', 'slug', 'term_group', 'term_taxonomy_id', 'taxonomy', 'description', 'parent', 'count' ); foreach ( $columns as $column ) { $data->{$column} = isset( $this->{$column} ) ? $this->{$column} : null; } return sanitize_term( $data, $data->taxonomy, 'raw' ); } } } ``` | Version | Description | | --- | --- | | [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. | wordpress class Walker_Nav_Menu_Checklist {} class Walker\_Nav\_Menu\_Checklist {} ===================================== Create HTML list of nav menu input items. * [\_\_construct](walker_nav_menu_checklist/__construct) * [end\_lvl](walker_nav_menu_checklist/end_lvl) β€” Ends the list of after the elements are added. * [start\_el](walker_nav_menu_checklist/start_el) β€” Start the element output. * [start\_lvl](walker_nav_menu_checklist/start_lvl) β€” Starts the list before the elements are added. File: `wp-admin/includes/class-walker-nav-menu-checklist.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-walker-nav-menu-checklist.php/) ``` class Walker_Nav_Menu_Checklist extends Walker_Nav_Menu { /** * @param array|false $fields Database fields to use. */ public function __construct( $fields = false ) { if ( $fields ) { $this->db_fields = $fields; } } /** * Starts the list before the elements are added. * * @see Walker_Nav_Menu::start_lvl() * * @since 3.0.0 * * @param string $output Used to append additional content (passed by reference). * @param int $depth Depth of page. Used for padding. * @param stdClass $args Not used. */ public function start_lvl( &$output, $depth = 0, $args = null ) { $indent = str_repeat( "\t", $depth ); $output .= "\n$indent<ul class='children'>\n"; } /** * Ends the list of after the elements are added. * * @see Walker_Nav_Menu::end_lvl() * * @since 3.0.0 * * @param string $output Used to append additional content (passed by reference). * @param int $depth Depth of page. Used for padding. * @param stdClass $args Not used. */ public function end_lvl( &$output, $depth = 0, $args = null ) { $indent = str_repeat( "\t", $depth ); $output .= "\n$indent</ul>"; } /** * Start the element output. * * @see Walker_Nav_Menu::start_el() * * @since 3.0.0 * @since 5.9.0 Renamed `$item` to `$data_object` and `$id` to `$current_object_id` * to match parent class for PHP 8 named parameter support. * * @global int $_nav_menu_placeholder * @global int|string $nav_menu_selected_id * * @param string $output Used to append additional content (passed by reference). * @param WP_Post $data_object Menu item data object. * @param int $depth Depth of menu item. Used for padding. * @param stdClass $args Not used. * @param int $current_object_id Optional. ID of the current menu item. Default 0. */ public function start_el( &$output, $data_object, $depth = 0, $args = null, $current_object_id = 0 ) { global $_nav_menu_placeholder, $nav_menu_selected_id; // Restores the more descriptive, specific name for use within this method. $menu_item = $data_object; $_nav_menu_placeholder = ( 0 > $_nav_menu_placeholder ) ? (int) $_nav_menu_placeholder - 1 : -1; $possible_object_id = isset( $menu_item->post_type ) && 'nav_menu_item' === $menu_item->post_type ? $menu_item->object_id : $_nav_menu_placeholder; $possible_db_id = ( ! empty( $menu_item->ID ) ) && ( 0 < $possible_object_id ) ? (int) $menu_item->ID : 0; $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $output .= $indent . '<li>'; $output .= '<label class="menu-item-title">'; $output .= '<input type="checkbox"' . wp_nav_menu_disabled_check( $nav_menu_selected_id, false ) . ' class="menu-item-checkbox'; if ( ! empty( $menu_item->front_or_home ) ) { $output .= ' add-to-top'; } $output .= '" name="menu-item[' . $possible_object_id . '][menu-item-object-id]" value="' . esc_attr( $menu_item->object_id ) . '" /> '; if ( ! empty( $menu_item->label ) ) { $title = $menu_item->label; } elseif ( isset( $menu_item->post_type ) ) { /** This filter is documented in wp-includes/post-template.php */ $title = apply_filters( 'the_title', $menu_item->post_title, $menu_item->ID ); } $output .= isset( $title ) ? esc_html( $title ) : esc_html( $menu_item->title ); if ( empty( $menu_item->label ) && isset( $menu_item->post_type ) && 'page' === $menu_item->post_type ) { // Append post states. $output .= _post_states( $menu_item, false ); } $output .= '</label>'; // Menu item hidden fields. $output .= '<input type="hidden" class="menu-item-db-id" name="menu-item[' . $possible_object_id . '][menu-item-db-id]" value="' . $possible_db_id . '" />'; $output .= '<input type="hidden" class="menu-item-object" name="menu-item[' . $possible_object_id . '][menu-item-object]" value="' . esc_attr( $menu_item->object ) . '" />'; $output .= '<input type="hidden" class="menu-item-parent-id" name="menu-item[' . $possible_object_id . '][menu-item-parent-id]" value="' . esc_attr( $menu_item->menu_item_parent ) . '" />'; $output .= '<input type="hidden" class="menu-item-type" name="menu-item[' . $possible_object_id . '][menu-item-type]" value="' . esc_attr( $menu_item->type ) . '" />'; $output .= '<input type="hidden" class="menu-item-title" name="menu-item[' . $possible_object_id . '][menu-item-title]" value="' . esc_attr( $menu_item->title ) . '" />'; $output .= '<input type="hidden" class="menu-item-url" name="menu-item[' . $possible_object_id . '][menu-item-url]" value="' . esc_attr( $menu_item->url ) . '" />'; $output .= '<input type="hidden" class="menu-item-target" name="menu-item[' . $possible_object_id . '][menu-item-target]" value="' . esc_attr( $menu_item->target ) . '" />'; $output .= '<input type="hidden" class="menu-item-attr-title" name="menu-item[' . $possible_object_id . '][menu-item-attr-title]" value="' . esc_attr( $menu_item->attr_title ) . '" />'; $output .= '<input type="hidden" class="menu-item-classes" name="menu-item[' . $possible_object_id . '][menu-item-classes]" value="' . esc_attr( implode( ' ', $menu_item->classes ) ) . '" />'; $output .= '<input type="hidden" class="menu-item-xfn" name="menu-item[' . $possible_object_id . '][menu-item-xfn]" value="' . esc_attr( $menu_item->xfn ) . '" />'; } } ``` | Uses | Description | | --- | --- | | [Walker\_Nav\_Menu](walker_nav_menu) wp-includes/class-walker-nav-menu.php | Core class used to implement an HTML list of nav menu items. | | Version | Description | | --- | --- | | [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. | wordpress class Custom_Background {} class Custom\_Background {} =========================== The custom background class. * [\_\_construct](custom_background/__construct) β€” Constructor - Registers administration header callback. * [admin\_load](custom_background/admin_load) β€” Sets up the enqueue for the CSS & JavaScript files. * [admin\_page](custom_background/admin_page) β€” Displays the custom background page. * [ajax\_background\_add](custom_background/ajax_background_add) β€” Handles Ajax request for adding custom background context to an attachment. * [attachment\_fields\_to\_edit](custom_background/attachment_fields_to_edit) β€” deprecated * [filter\_upload\_tabs](custom_background/filter_upload_tabs) β€” deprecated * [handle\_upload](custom_background/handle_upload) β€” Handles an Image upload for the background image. * [init](custom_background/init) β€” Sets up the hooks for the Custom Background admin page. * [take\_action](custom_background/take_action) β€” Executes custom background modification. * [wp\_set\_background\_image](custom_background/wp_set_background_image) β€” deprecated File: `wp-admin/includes/class-custom-background.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-background.php/) ``` class Custom_Background { /** * Callback for administration header. * * @var callable * @since 3.0.0 */ public $admin_header_callback; /** * Callback for header div. * * @var callable * @since 3.0.0 */ public $admin_image_div_callback; /** * Used to trigger a success message when settings updated and set to true. * * @since 3.0.0 * @var bool */ private $updated; /** * Constructor - Registers administration header callback. * * @since 3.0.0 * @param callable $admin_header_callback * @param callable $admin_image_div_callback Optional custom image div output callback. */ public function __construct( $admin_header_callback = '', $admin_image_div_callback = '' ) { $this->admin_header_callback = $admin_header_callback; $this->admin_image_div_callback = $admin_image_div_callback; add_action( 'admin_menu', array( $this, 'init' ) ); add_action( 'wp_ajax_custom-background-add', array( $this, 'ajax_background_add' ) ); // Unused since 3.5.0. add_action( 'wp_ajax_set-background-image', array( $this, 'wp_set_background_image' ) ); } /** * Sets up the hooks for the Custom Background admin page. * * @since 3.0.0 */ public function init() { $page = add_theme_page( __( 'Background' ), __( 'Background' ), 'edit_theme_options', 'custom-background', array( $this, 'admin_page' ) ); if ( ! $page ) { return; } add_action( "load-{$page}", array( $this, 'admin_load' ) ); add_action( "load-{$page}", array( $this, 'take_action' ), 49 ); add_action( "load-{$page}", array( $this, 'handle_upload' ), 49 ); if ( $this->admin_header_callback ) { add_action( "admin_head-{$page}", $this->admin_header_callback, 51 ); } } /** * Sets up the enqueue for the CSS & JavaScript files. * * @since 3.0.0 */ public function admin_load() { get_current_screen()->add_help_tab( array( 'id' => 'overview', 'title' => __( 'Overview' ), 'content' => '<p>' . __( 'You can customize the look of your site without touching any of your theme&#8217;s code by using a custom background. Your background can be an image or a color.' ) . '</p>' . '<p>' . __( 'To use a background image, simply upload it or choose an image that has already been uploaded to your Media Library by clicking the &#8220;Choose Image&#8221; button. You can display a single instance of your image, or tile it to fill the screen. You can have your background fixed in place, so your site content moves on top of it, or you can have it scroll with your site.' ) . '</p>' . '<p>' . __( 'You can also choose a background color by clicking the Select Color button and either typing in a legitimate HTML hex value, e.g. &#8220;#ff0000&#8221; for red, or by choosing a color using the color picker.' ) . '</p>' . '<p>' . __( 'Do not forget to click on the Save Changes button when you are finished.' ) . '</p>', ) ); get_current_screen()->set_help_sidebar( '<p><strong>' . __( 'For more information:' ) . '</strong></p>' . '<p>' . __( '<a href="https://codex.wordpress.org/Appearance_Background_Screen">Documentation on Custom Background</a>' ) . '</p>' . '<p>' . __( '<a href="https://wordpress.org/support/">Support</a>' ) . '</p>' ); wp_enqueue_media(); wp_enqueue_script( 'custom-background' ); wp_enqueue_style( 'wp-color-picker' ); } /** * Executes custom background modification. * * @since 3.0.0 */ public function take_action() { if ( empty( $_POST ) ) { return; } if ( isset( $_POST['reset-background'] ) ) { check_admin_referer( 'custom-background-reset', '_wpnonce-custom-background-reset' ); remove_theme_mod( 'background_image' ); remove_theme_mod( 'background_image_thumb' ); $this->updated = true; return; } if ( isset( $_POST['remove-background'] ) ) { // @todo Uploaded files are not removed here. check_admin_referer( 'custom-background-remove', '_wpnonce-custom-background-remove' ); set_theme_mod( 'background_image', '' ); set_theme_mod( 'background_image_thumb', '' ); $this->updated = true; wp_safe_redirect( $_POST['_wp_http_referer'] ); return; } if ( isset( $_POST['background-preset'] ) ) { check_admin_referer( 'custom-background' ); if ( in_array( $_POST['background-preset'], array( 'default', 'fill', 'fit', 'repeat', 'custom' ), true ) ) { $preset = $_POST['background-preset']; } else { $preset = 'default'; } set_theme_mod( 'background_preset', $preset ); } if ( isset( $_POST['background-position'] ) ) { check_admin_referer( 'custom-background' ); $position = explode( ' ', $_POST['background-position'] ); if ( in_array( $position[0], array( 'left', 'center', 'right' ), true ) ) { $position_x = $position[0]; } else { $position_x = 'left'; } if ( in_array( $position[1], array( 'top', 'center', 'bottom' ), true ) ) { $position_y = $position[1]; } else { $position_y = 'top'; } set_theme_mod( 'background_position_x', $position_x ); set_theme_mod( 'background_position_y', $position_y ); } if ( isset( $_POST['background-size'] ) ) { check_admin_referer( 'custom-background' ); if ( in_array( $_POST['background-size'], array( 'auto', 'contain', 'cover' ), true ) ) { $size = $_POST['background-size']; } else { $size = 'auto'; } set_theme_mod( 'background_size', $size ); } if ( isset( $_POST['background-repeat'] ) ) { check_admin_referer( 'custom-background' ); $repeat = $_POST['background-repeat']; if ( 'no-repeat' !== $repeat ) { $repeat = 'repeat'; } set_theme_mod( 'background_repeat', $repeat ); } if ( isset( $_POST['background-attachment'] ) ) { check_admin_referer( 'custom-background' ); $attachment = $_POST['background-attachment']; if ( 'fixed' !== $attachment ) { $attachment = 'scroll'; } set_theme_mod( 'background_attachment', $attachment ); } if ( isset( $_POST['background-color'] ) ) { check_admin_referer( 'custom-background' ); $color = preg_replace( '/[^0-9a-fA-F]/', '', $_POST['background-color'] ); if ( strlen( $color ) === 6 || strlen( $color ) === 3 ) { set_theme_mod( 'background_color', $color ); } else { set_theme_mod( 'background_color', '' ); } } $this->updated = true; } /** * Displays the custom background page. * * @since 3.0.0 */ public function admin_page() { ?> <div class="wrap" id="custom-background"> <h1><?php _e( 'Custom Background' ); ?></h1> <?php if ( current_user_can( 'customize' ) ) { ?> <div class="notice notice-info hide-if-no-customize"> <p> <?php printf( /* translators: %s: URL to background image configuration in Customizer. */ __( 'You can now manage and live-preview Custom Backgrounds in the <a href="%s">Customizer</a>.' ), admin_url( 'customize.php?autofocus[control]=background_image' ) ); ?> </p> </div> <?php } ?> <?php if ( ! empty( $this->updated ) ) { ?> <div id="message" class="updated"> <p> <?php /* translators: %s: Home URL. */ printf( __( 'Background updated. <a href="%s">Visit your site</a> to see how it looks.' ), esc_url( home_url( '/' ) ) ); ?> </p> </div> <?php } ?> <h2><?php _e( 'Background Image' ); ?></h2> <table class="form-table" role="presentation"> <tbody> <tr> <th scope="row"><?php _e( 'Preview' ); ?></th> <td> <?php if ( $this->admin_image_div_callback ) { call_user_func( $this->admin_image_div_callback ); } else { $background_styles = ''; $bgcolor = get_background_color(); if ( $bgcolor ) { $background_styles .= 'background-color: #' . $bgcolor . ';'; } $background_image_thumb = get_background_image(); if ( $background_image_thumb ) { $background_image_thumb = esc_url( set_url_scheme( get_theme_mod( 'background_image_thumb', str_replace( '%', '%%', $background_image_thumb ) ) ) ); $background_position_x = get_theme_mod( 'background_position_x', get_theme_support( 'custom-background', 'default-position-x' ) ); $background_position_y = get_theme_mod( 'background_position_y', get_theme_support( 'custom-background', 'default-position-y' ) ); $background_size = get_theme_mod( 'background_size', get_theme_support( 'custom-background', 'default-size' ) ); $background_repeat = get_theme_mod( 'background_repeat', get_theme_support( 'custom-background', 'default-repeat' ) ); $background_attachment = get_theme_mod( 'background_attachment', get_theme_support( 'custom-background', 'default-attachment' ) ); // Background-image URL must be single quote, see below. $background_styles .= " background-image: url('$background_image_thumb');" . " background-size: $background_size;" . " background-position: $background_position_x $background_position_y;" . " background-repeat: $background_repeat;" . " background-attachment: $background_attachment;"; } ?> <div id="custom-background-image" style="<?php echo $background_styles; ?>"><?php // Must be double quote, see above. ?> <?php if ( $background_image_thumb ) { ?> <img class="custom-background-image" src="<?php echo $background_image_thumb; ?>" style="visibility:hidden;" alt="" /><br /> <img class="custom-background-image" src="<?php echo $background_image_thumb; ?>" style="visibility:hidden;" alt="" /> <?php } ?> </div> <?php } ?> </td> </tr> <?php if ( get_background_image() ) : ?> <tr> <th scope="row"><?php _e( 'Remove Image' ); ?></th> <td> <form method="post"> <?php wp_nonce_field( 'custom-background-remove', '_wpnonce-custom-background-remove' ); ?> <?php submit_button( __( 'Remove Background Image' ), '', 'remove-background', false ); ?><br /> <?php _e( 'This will remove the background image. You will not be able to restore any customizations.' ); ?> </form> </td> </tr> <?php endif; ?> <?php $default_image = get_theme_support( 'custom-background', 'default-image' ); ?> <?php if ( $default_image && get_background_image() !== $default_image ) : ?> <tr> <th scope="row"><?php _e( 'Restore Original Image' ); ?></th> <td> <form method="post"> <?php wp_nonce_field( 'custom-background-reset', '_wpnonce-custom-background-reset' ); ?> <?php submit_button( __( 'Restore Original Image' ), '', 'reset-background', false ); ?><br /> <?php _e( 'This will restore the original background image. You will not be able to restore any customizations.' ); ?> </form> </td> </tr> <?php endif; ?> <?php if ( current_user_can( 'upload_files' ) ) : ?> <tr> <th scope="row"><?php _e( 'Select Image' ); ?></th> <td><form enctype="multipart/form-data" id="upload-form" class="wp-upload-form" method="post"> <p> <label for="upload"><?php _e( 'Choose an image from your computer:' ); ?></label><br /> <input type="file" id="upload" name="import" /> <input type="hidden" name="action" value="save" /> <?php wp_nonce_field( 'custom-background-upload', '_wpnonce-custom-background-upload' ); ?> <?php submit_button( __( 'Upload' ), '', 'submit', false ); ?> </p> <p> <label for="choose-from-library-link"><?php _e( 'Or choose an image from your media library:' ); ?></label><br /> <button id="choose-from-library-link" class="button" data-choose="<?php esc_attr_e( 'Choose a Background Image' ); ?>" data-update="<?php esc_attr_e( 'Set as background' ); ?>"><?php _e( 'Choose Image' ); ?></button> </p> </form> </td> </tr> <?php endif; ?> </tbody> </table> <h2><?php _e( 'Display Options' ); ?></h2> <form method="post"> <table class="form-table" role="presentation"> <tbody> <?php if ( get_background_image() ) : ?> <input name="background-preset" type="hidden" value="custom"> <?php $background_position = sprintf( '%s %s', get_theme_mod( 'background_position_x', get_theme_support( 'custom-background', 'default-position-x' ) ), get_theme_mod( 'background_position_y', get_theme_support( 'custom-background', 'default-position-y' ) ) ); $background_position_options = array( array( 'left top' => array( 'label' => __( 'Top Left' ), 'icon' => 'dashicons dashicons-arrow-left-alt', ), 'center top' => array( 'label' => __( 'Top' ), 'icon' => 'dashicons dashicons-arrow-up-alt', ), 'right top' => array( 'label' => __( 'Top Right' ), 'icon' => 'dashicons dashicons-arrow-right-alt', ), ), array( 'left center' => array( 'label' => __( 'Left' ), 'icon' => 'dashicons dashicons-arrow-left-alt', ), 'center center' => array( 'label' => __( 'Center' ), 'icon' => 'background-position-center-icon', ), 'right center' => array( 'label' => __( 'Right' ), 'icon' => 'dashicons dashicons-arrow-right-alt', ), ), array( 'left bottom' => array( 'label' => __( 'Bottom Left' ), 'icon' => 'dashicons dashicons-arrow-left-alt', ), 'center bottom' => array( 'label' => __( 'Bottom' ), 'icon' => 'dashicons dashicons-arrow-down-alt', ), 'right bottom' => array( 'label' => __( 'Bottom Right' ), 'icon' => 'dashicons dashicons-arrow-right-alt', ), ), ); ?> <tr> <th scope="row"><?php _e( 'Image Position' ); ?></th> <td><fieldset><legend class="screen-reader-text"><span><?php _e( 'Image Position' ); ?></span></legend> <div class="background-position-control"> <?php foreach ( $background_position_options as $group ) : ?> <div class="button-group"> <?php foreach ( $group as $value => $input ) : ?> <label> <input class="ui-helper-hidden-accessible" name="background-position" type="radio" value="<?php echo esc_attr( $value ); ?>"<?php checked( $value, $background_position ); ?>> <span class="button display-options position"><span class="<?php echo esc_attr( $input['icon'] ); ?>" aria-hidden="true"></span></span> <span class="screen-reader-text"><?php echo $input['label']; ?></span> </label> <?php endforeach; ?> </div> <?php endforeach; ?> </div> </fieldset></td> </tr> <tr> <th scope="row"><label for="background-size"><?php _e( 'Image Size' ); ?></label></th> <td><fieldset><legend class="screen-reader-text"><span><?php _e( 'Image Size' ); ?></span></legend> <select id="background-size" name="background-size"> <option value="auto"<?php selected( 'auto', get_theme_mod( 'background_size', get_theme_support( 'custom-background', 'default-size' ) ) ); ?>><?php _ex( 'Original', 'Original Size' ); ?></option> <option value="contain"<?php selected( 'contain', get_theme_mod( 'background_size', get_theme_support( 'custom-background', 'default-size' ) ) ); ?>><?php _e( 'Fit to Screen' ); ?></option> <option value="cover"<?php selected( 'cover', get_theme_mod( 'background_size', get_theme_support( 'custom-background', 'default-size' ) ) ); ?>><?php _e( 'Fill Screen' ); ?></option> </select> </fieldset></td> </tr> <tr> <th scope="row"><?php _ex( 'Repeat', 'Background Repeat' ); ?></th> <td><fieldset><legend class="screen-reader-text"><span><?php _ex( 'Repeat', 'Background Repeat' ); ?></span></legend> <input name="background-repeat" type="hidden" value="no-repeat"> <label><input type="checkbox" name="background-repeat" value="repeat"<?php checked( 'repeat', get_theme_mod( 'background_repeat', get_theme_support( 'custom-background', 'default-repeat' ) ) ); ?>> <?php _e( 'Repeat Background Image' ); ?></label> </fieldset></td> </tr> <tr> <th scope="row"><?php _ex( 'Scroll', 'Background Scroll' ); ?></th> <td><fieldset><legend class="screen-reader-text"><span><?php _ex( 'Scroll', 'Background Scroll' ); ?></span></legend> <input name="background-attachment" type="hidden" value="fixed"> <label><input name="background-attachment" type="checkbox" value="scroll" <?php checked( 'scroll', get_theme_mod( 'background_attachment', get_theme_support( 'custom-background', 'default-attachment' ) ) ); ?>> <?php _e( 'Scroll with Page' ); ?></label> </fieldset></td> </tr> <?php endif; // get_background_image() ?> <tr> <th scope="row"><?php _e( 'Background Color' ); ?></th> <td><fieldset><legend class="screen-reader-text"><span><?php _e( 'Background Color' ); ?></span></legend> <?php $default_color = ''; if ( current_theme_supports( 'custom-background', 'default-color' ) ) { $default_color = ' data-default-color="#' . esc_attr( get_theme_support( 'custom-background', 'default-color' ) ) . '"'; } ?> <input type="text" name="background-color" id="background-color" value="#<?php echo esc_attr( get_background_color() ); ?>"<?php echo $default_color; ?>> </fieldset></td> </tr> </tbody> </table> <?php wp_nonce_field( 'custom-background' ); ?> <?php submit_button( null, 'primary', 'save-background-options' ); ?> </form> </div> <?php } /** * Handles an Image upload for the background image. * * @since 3.0.0 */ public function handle_upload() { if ( empty( $_FILES ) ) { return; } check_admin_referer( 'custom-background-upload', '_wpnonce-custom-background-upload' ); $overrides = array( 'test_form' => false ); $uploaded_file = $_FILES['import']; $wp_filetype = wp_check_filetype_and_ext( $uploaded_file['tmp_name'], $uploaded_file['name'] ); if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) ) { wp_die( __( 'The uploaded file is not a valid image. Please try again.' ) ); } $file = wp_handle_upload( $uploaded_file, $overrides ); if ( isset( $file['error'] ) ) { wp_die( $file['error'] ); } $url = $file['url']; $type = $file['type']; $file = $file['file']; $filename = wp_basename( $file ); // Construct the attachment array. $attachment = array( 'post_title' => $filename, 'post_content' => $url, 'post_mime_type' => $type, 'guid' => $url, 'context' => 'custom-background', ); // Save the data. $id = wp_insert_attachment( $attachment, $file ); // Add the metadata. wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) ); update_post_meta( $id, '_wp_attachment_is_custom_background', get_option( 'stylesheet' ) ); set_theme_mod( 'background_image', sanitize_url( $url ) ); $thumbnail = wp_get_attachment_image_src( $id, 'thumbnail' ); set_theme_mod( 'background_image_thumb', sanitize_url( $thumbnail[0] ) ); /** This action is documented in wp-admin/includes/class-custom-image-header.php */ do_action( 'wp_create_file_in_uploads', $file, $id ); // For replication. $this->updated = true; } /** * Handles Ajax request for adding custom background context to an attachment. * * Triggers when the user adds a new background image from the * Media Manager. * * @since 4.1.0 */ public function ajax_background_add() { check_ajax_referer( 'background-add', 'nonce' ); if ( ! current_user_can( 'edit_theme_options' ) ) { wp_send_json_error(); } $attachment_id = absint( $_POST['attachment_id'] ); if ( $attachment_id < 1 ) { wp_send_json_error(); } update_post_meta( $attachment_id, '_wp_attachment_is_custom_background', get_stylesheet() ); wp_send_json_success(); } /** * @since 3.4.0 * @deprecated 3.5.0 * * @param array $form_fields * @return array $form_fields */ public function attachment_fields_to_edit( $form_fields ) { return $form_fields; } /** * @since 3.4.0 * @deprecated 3.5.0 * * @param array $tabs * @return array $tabs */ public function filter_upload_tabs( $tabs ) { return $tabs; } /** * @since 3.4.0 * @deprecated 3.5.0 */ public function wp_set_background_image() { check_ajax_referer( 'custom-background' ); if ( ! current_user_can( 'edit_theme_options' ) || ! isset( $_POST['attachment_id'] ) ) { exit; } $attachment_id = absint( $_POST['attachment_id'] ); $sizes = array_keys( /** This filter is documented in wp-admin/includes/media.php */ apply_filters( 'image_size_names_choose', array( 'thumbnail' => __( 'Thumbnail' ), 'medium' => __( 'Medium' ), 'large' => __( 'Large' ), 'full' => __( 'Full Size' ), ) ) ); $size = 'thumbnail'; if ( in_array( $_POST['size'], $sizes, true ) ) { $size = esc_attr( $_POST['size'] ); } update_post_meta( $attachment_id, '_wp_attachment_is_custom_background', get_option( 'stylesheet' ) ); $url = wp_get_attachment_image_src( $attachment_id, $size ); $thumbnail = wp_get_attachment_image_src( $attachment_id, 'thumbnail' ); set_theme_mod( 'background_image', sanitize_url( $url[0] ) ); set_theme_mod( 'background_image_thumb', sanitize_url( $thumbnail[0] ) ); exit; } } ``` | Version | Description | | --- | --- | | [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
programming_docs
wordpress class WP_Dependencies {} class WP\_Dependencies {} ========================= Core base class extended to register items. * [\_WP\_Dependency](_wp_dependency) `WP_Dependencies` is a class defined in `[wp-includes/class.wp-dependencies.php](https://core.trac.wordpress.org/browser/tags/5.5/src/wp-includes/class.wp-dependencies.php#L0)` that helps process items in an order defined by dependencies (a dependent item is processed later than a dependency). It’s an abstract class in that it’s intended to be extended, rather than used directly. `WP_Dependencies` is the base for `[WP\_Scripts](wp_scripts "Class Reference/WP Scripts (page does not exist)")` and `[WP\_Styles](wp_styles "Class Reference/WP Styles")`, and is a collection of `[\_WP\_Dependency](_wp_dependency "Class Reference/ WP Dependency")`s. An item goes through various stages of processing as various methods are called: 1. registered: `add()` 2. enqueued: `enqueue()` 3. to\_do: `all_deps()` 4. done: `do_items()` The `query()` method can be used to determine whether a given item is in a given stage. Separate processing runs can be identified by different groups (identified by integers). For example, items output in the document <head> might go in one group, while items output in the footer may go in another. An enqueued item that was processed in a group associated with an earlier run is skipped in later runs. The base `WP_Dependencies` doesn’t create groups on its own; child classes must do this. * [add](wp_dependencies/add) β€” Register an item. * [add\_data](wp_dependencies/add_data) β€” Add extra item data. * [all\_deps](wp_dependencies/all_deps) β€” Determines dependencies. * [dequeue](wp_dependencies/dequeue) β€” Dequeue an item or items. * [do\_item](wp_dependencies/do_item) β€” Processes a dependency. * [do\_items](wp_dependencies/do_items) β€” Processes the items and dependencies. * [enqueue](wp_dependencies/enqueue) β€” Queue an item or items. * [get\_data](wp_dependencies/get_data) β€” Get extra item data. * [query](wp_dependencies/query) β€” Query the list for an item. * [recurse\_deps](wp_dependencies/recurse_deps) β€” Recursively search the passed dependency tree for a handle. * [remove](wp_dependencies/remove) β€” Un-register an item or items. * [set\_group](wp_dependencies/set_group) β€” Set item group, unless already in a lower group. File: `wp-includes/class-wp-dependencies.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-dependencies-php-2/) ``` class WP_Dependencies { /** * An array of all registered dependencies keyed by handle. * * @since 2.6.8 * * @var _WP_Dependency[] */ public $registered = array(); /** * An array of handles of queued dependencies. * * @since 2.6.8 * * @var string[] */ public $queue = array(); /** * An array of handles of dependencies to queue. * * @since 2.6.0 * * @var string[] */ public $to_do = array(); /** * An array of handles of dependencies already queued. * * @since 2.6.0 * * @var string[] */ public $done = array(); /** * An array of additional arguments passed when a handle is registered. * * Arguments are appended to the item query string. * * @since 2.6.0 * * @var array */ public $args = array(); /** * An array of dependency groups to enqueue. * * Each entry is keyed by handle and represents the integer group level or boolean * false if the handle has no group. * * @since 2.8.0 * * @var (int|false)[] */ public $groups = array(); /** * A handle group to enqueue. * * @since 2.8.0 * * @deprecated 4.5.0 * @var int */ public $group = 0; /** * Cached lookup array of flattened queued items and dependencies. * * @since 5.4.0 * * @var array */ private $all_queued_deps; /** * List of assets enqueued before details were registered. * * @since 5.9.0 * * @var array */ private $queued_before_register = array(); /** * Processes the items and dependencies. * * Processes the items passed to it or the queue, and their dependencies. * * @since 2.6.0 * @since 2.8.0 Added the `$group` parameter. * * @param string|string[]|false $handles Optional. Items to be processed: queue (false), * single item (string), or multiple items (array of strings). * Default false. * @param int|false $group Optional. Group level: level (int), no group (false). * @return string[] Array of handles of items that have been processed. */ public function do_items( $handles = false, $group = false ) { /* * If nothing is passed, print the queue. If a string is passed, * print that item. If an array is passed, print those items. */ $handles = false === $handles ? $this->queue : (array) $handles; $this->all_deps( $handles ); foreach ( $this->to_do as $key => $handle ) { if ( ! in_array( $handle, $this->done, true ) && isset( $this->registered[ $handle ] ) ) { /* * Attempt to process the item. If successful, * add the handle to the done array. * * Unset the item from the to_do array. */ if ( $this->do_item( $handle, $group ) ) { $this->done[] = $handle; } unset( $this->to_do[ $key ] ); } } return $this->done; } /** * Processes a dependency. * * @since 2.6.0 * @since 5.5.0 Added the `$group` parameter. * * @param string $handle Name of the item. Should be unique. * @param int|false $group Optional. Group level: level (int), no group (false). * Default false. * @return bool True on success, false if not set. */ public function do_item( $handle, $group = false ) { return isset( $this->registered[ $handle ] ); } /** * Determines dependencies. * * Recursively builds an array of items to process taking * dependencies into account. Does NOT catch infinite loops. * * @since 2.1.0 * @since 2.6.0 Moved from `WP_Scripts`. * @since 2.8.0 Added the `$group` parameter. * * @param string|string[] $handles Item handle (string) or item handles (array of strings). * @param bool $recursion Optional. Internal flag that function is calling itself. * Default false. * @param int|false $group Optional. Group level: level (int), no group (false). * Default false. * @return bool True on success, false on failure. */ public function all_deps( $handles, $recursion = false, $group = false ) { $handles = (array) $handles; if ( ! $handles ) { return false; } foreach ( $handles as $handle ) { $handle_parts = explode( '?', $handle ); $handle = $handle_parts[0]; $queued = in_array( $handle, $this->to_do, true ); if ( in_array( $handle, $this->done, true ) ) { // Already done. continue; } $moved = $this->set_group( $handle, $recursion, $group ); $new_group = $this->groups[ $handle ]; if ( $queued && ! $moved ) { // Already queued and in the right group. continue; } $keep_going = true; if ( ! isset( $this->registered[ $handle ] ) ) { $keep_going = false; // Item doesn't exist. } elseif ( $this->registered[ $handle ]->deps && array_diff( $this->registered[ $handle ]->deps, array_keys( $this->registered ) ) ) { $keep_going = false; // Item requires dependencies that don't exist. } elseif ( $this->registered[ $handle ]->deps && ! $this->all_deps( $this->registered[ $handle ]->deps, true, $new_group ) ) { $keep_going = false; // Item requires dependencies that don't exist. } if ( ! $keep_going ) { // Either item or its dependencies don't exist. if ( $recursion ) { return false; // Abort this branch. } else { continue; // We're at the top level. Move on to the next one. } } if ( $queued ) { // Already grabbed it and its dependencies. continue; } if ( isset( $handle_parts[1] ) ) { $this->args[ $handle ] = $handle_parts[1]; } $this->to_do[] = $handle; } return true; } /** * Register an item. * * Registers the item if no item of that name already exists. * * @since 2.1.0 * @since 2.6.0 Moved from `WP_Scripts`. * * @param string $handle Name of the item. Should be unique. * @param string|false $src Full URL of the item, or path of the item relative * to the WordPress root directory. If source is set to false, * item is an alias of other items it depends on. * @param string[] $deps Optional. An array of registered item handles this item depends on. * Default empty array. * @param string|bool|null $ver Optional. String specifying item version number, if it has one, * which is added to the URL as a query string for cache busting purposes. * If version is set to false, a version number is automatically added * equal to current installed WordPress version. * If set to null, no version is added. * @param mixed $args Optional. Custom property of the item. NOT the class property $args. * Examples: $media, $in_footer. * @return bool Whether the item has been registered. True on success, false on failure. */ public function add( $handle, $src, $deps = array(), $ver = false, $args = null ) { if ( isset( $this->registered[ $handle ] ) ) { return false; } $this->registered[ $handle ] = new _WP_Dependency( $handle, $src, $deps, $ver, $args ); // If the item was enqueued before the details were registered, enqueue it now. if ( array_key_exists( $handle, $this->queued_before_register ) ) { if ( ! is_null( $this->queued_before_register[ $handle ] ) ) { $this->enqueue( $handle . '?' . $this->queued_before_register[ $handle ] ); } else { $this->enqueue( $handle ); } unset( $this->queued_before_register[ $handle ] ); } return true; } /** * Add extra item data. * * Adds data to a registered item. * * @since 2.6.0 * * @param string $handle Name of the item. Should be unique. * @param string $key The data key. * @param mixed $value The data value. * @return bool True on success, false on failure. */ public function add_data( $handle, $key, $value ) { if ( ! isset( $this->registered[ $handle ] ) ) { return false; } return $this->registered[ $handle ]->add_data( $key, $value ); } /** * Get extra item data. * * Gets data associated with a registered item. * * @since 3.3.0 * * @param string $handle Name of the item. Should be unique. * @param string $key The data key. * @return mixed Extra item data (string), false otherwise. */ public function get_data( $handle, $key ) { if ( ! isset( $this->registered[ $handle ] ) ) { return false; } if ( ! isset( $this->registered[ $handle ]->extra[ $key ] ) ) { return false; } return $this->registered[ $handle ]->extra[ $key ]; } /** * Un-register an item or items. * * @since 2.1.0 * @since 2.6.0 Moved from `WP_Scripts`. * * @param string|string[] $handles Item handle (string) or item handles (array of strings). */ public function remove( $handles ) { foreach ( (array) $handles as $handle ) { unset( $this->registered[ $handle ] ); } } /** * Queue an item or items. * * Decodes handles and arguments, then queues handles and stores * arguments in the class property $args. For example in extending * classes, $args is appended to the item url as a query string. * Note $args is NOT the $args property of items in the $registered array. * * @since 2.1.0 * @since 2.6.0 Moved from `WP_Scripts`. * * @param string|string[] $handles Item handle (string) or item handles (array of strings). */ public function enqueue( $handles ) { foreach ( (array) $handles as $handle ) { $handle = explode( '?', $handle ); if ( ! in_array( $handle[0], $this->queue, true ) && isset( $this->registered[ $handle[0] ] ) ) { $this->queue[] = $handle[0]; // Reset all dependencies so they must be recalculated in recurse_deps(). $this->all_queued_deps = null; if ( isset( $handle[1] ) ) { $this->args[ $handle[0] ] = $handle[1]; } } elseif ( ! isset( $this->registered[ $handle[0] ] ) ) { $this->queued_before_register[ $handle[0] ] = null; // $args if ( isset( $handle[1] ) ) { $this->queued_before_register[ $handle[0] ] = $handle[1]; } } } } /** * Dequeue an item or items. * * Decodes handles and arguments, then dequeues handles * and removes arguments from the class property $args. * * @since 2.1.0 * @since 2.6.0 Moved from `WP_Scripts`. * * @param string|string[] $handles Item handle (string) or item handles (array of strings). */ public function dequeue( $handles ) { foreach ( (array) $handles as $handle ) { $handle = explode( '?', $handle ); $key = array_search( $handle[0], $this->queue, true ); if ( false !== $key ) { // Reset all dependencies so they must be recalculated in recurse_deps(). $this->all_queued_deps = null; unset( $this->queue[ $key ] ); unset( $this->args[ $handle[0] ] ); } elseif ( array_key_exists( $handle[0], $this->queued_before_register ) ) { unset( $this->queued_before_register[ $handle[0] ] ); } } } /** * Recursively search the passed dependency tree for a handle. * * @since 4.0.0 * * @param string[] $queue An array of queued _WP_Dependency handles. * @param string $handle Name of the item. Should be unique. * @return bool Whether the handle is found after recursively searching the dependency tree. */ protected function recurse_deps( $queue, $handle ) { if ( isset( $this->all_queued_deps ) ) { return isset( $this->all_queued_deps[ $handle ] ); } $all_deps = array_fill_keys( $queue, true ); $queues = array(); $done = array(); while ( $queue ) { foreach ( $queue as $queued ) { if ( ! isset( $done[ $queued ] ) && isset( $this->registered[ $queued ] ) ) { $deps = $this->registered[ $queued ]->deps; if ( $deps ) { $all_deps += array_fill_keys( $deps, true ); array_push( $queues, $deps ); } $done[ $queued ] = true; } } $queue = array_pop( $queues ); } $this->all_queued_deps = $all_deps; return isset( $this->all_queued_deps[ $handle ] ); } /** * Query the list for an item. * * @since 2.1.0 * @since 2.6.0 Moved from `WP_Scripts`. * * @param string $handle Name of the item. Should be unique. * @param string $status Optional. Status of the item to query. Default 'registered'. * @return bool|_WP_Dependency Found, or object Item data. */ public function query( $handle, $status = 'registered' ) { switch ( $status ) { case 'registered': case 'scripts': // Back compat. if ( isset( $this->registered[ $handle ] ) ) { return $this->registered[ $handle ]; } return false; case 'enqueued': case 'queue': // Back compat. if ( in_array( $handle, $this->queue, true ) ) { return true; } return $this->recurse_deps( $this->queue, $handle ); case 'to_do': case 'to_print': // Back compat. return in_array( $handle, $this->to_do, true ); case 'done': case 'printed': // Back compat. return in_array( $handle, $this->done, true ); } return false; } /** * Set item group, unless already in a lower group. * * @since 2.8.0 * * @param string $handle Name of the item. Should be unique. * @param bool $recursion Internal flag that calling function was called recursively. * @param int|false $group Group level: level (int), no group (false). * @return bool Not already in the group or a lower group. */ public function set_group( $handle, $recursion, $group ) { $group = (int) $group; if ( isset( $this->groups[ $handle ] ) && $this->groups[ $handle ] <= $group ) { return false; } $this->groups[ $handle ] = $group; return true; } } ``` | Used By | Description | | --- | --- | | [WP\_Styles](wp_styles) wp-includes/class-wp-styles.php | Core class used to register styles. | | [WP\_Scripts](wp_scripts) wp-includes/class-wp-scripts.php | Core class used to register scripts. | | Version | Description | | --- | --- | | [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. | wordpress class WP_Theme_JSON_Resolver {} class WP\_Theme\_JSON\_Resolver {} ================================== Class that abstracts the processing of the different data sources for site-level config and offers an API to work with them. This class is for internal core usage and is not supposed to be used by extenders (plugins and/or themes). This is a low-level API that may need to do breaking changes. Please, use get\_global\_settings, get\_global\_styles, and get\_global\_stylesheet instead. * [clean\_cached\_data](wp_theme_json_resolver/clean_cached_data) β€” Cleans the cached data so it can be recalculated. * [extract\_paths\_to\_translate](wp_theme_json_resolver/extract_paths_to_translate) β€” Converts a tree as in i18n-theme.json into a linear array containing metadata to translate a theme.json file. * [get\_block\_data](wp_theme_json_resolver/get_block_data) β€” Gets the styles for blocks from the block.json file. * [get\_core\_data](wp_theme_json_resolver/get_core_data) β€” Returns core's origin config. * [get\_fields\_to\_translate](wp_theme_json_resolver/get_fields_to_translate) β€” Returns a data structure used in theme.json translation. β€” deprecated * [get\_file\_path\_from\_theme](wp_theme_json_resolver/get_file_path_from_theme) β€” Builds the path to the given file and checks that it is readable. * [get\_merged\_data](wp_theme_json_resolver/get_merged_data) β€” Returns the data merged from multiple origins. * [get\_style\_variations](wp_theme_json_resolver/get_style_variations) β€” Returns the style variations defined by the theme. * [get\_theme\_data](wp_theme_json_resolver/get_theme_data) β€” Returns the theme's data. * [get\_user\_data](wp_theme_json_resolver/get_user_data) β€” Returns the user's origin config. * [get\_user\_data\_from\_wp\_global\_styles](wp_theme_json_resolver/get_user_data_from_wp_global_styles) β€” Returns the custom post type that contains the user's origin config for the active theme or a void array if none are found. * [get\_user\_global\_styles\_post\_id](wp_theme_json_resolver/get_user_global_styles_post_id) β€” Returns the ID of the custom post type that stores user data. * [has\_same\_registered\_blocks](wp_theme_json_resolver/has_same_registered_blocks) β€” Checks whether the registered blocks were already processed for this origin. * [read\_json\_file](wp_theme_json_resolver/read_json_file) β€” Processes a file that adheres to the theme.json schema and returns an array with its contents, or a void array if none found. * [remove\_json\_comments](wp_theme_json_resolver/remove_json_comments) β€” When given an array, this will remove any keys with the name `//`. * [theme\_has\_support](wp_theme_json_resolver/theme_has_support) β€” Determines whether the active theme has a theme.json file. * [translate](wp_theme_json_resolver/translate) β€” Given a theme.json structure modifies it in place to update certain values by its translated strings according to the language set by the user. * [translate\_theme\_json\_chunk](wp_theme_json_resolver/translate_theme_json_chunk) β€” Translates a chunk of the loaded theme.json structure. File: `wp-includes/class-wp-theme-json-resolver.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme-json-resolver.php/) ``` class WP_Theme_JSON_Resolver { /** * Container for keep track of registered blocks. * * @since 6.1.0 * @var array */ protected static $blocks_cache = array( 'core' => array(), 'blocks' => array(), 'theme' => array(), 'user' => array(), ); /** * Container for data coming from core. * * @since 5.8.0 * @var WP_Theme_JSON */ protected static $core = null; /** * Container for data coming from the blocks. * * @since 6.1.0 * @var WP_Theme_JSON */ protected static $blocks = null; /** * Container for data coming from the theme. * * @since 5.8.0 * @var WP_Theme_JSON */ protected static $theme = null; /** * Whether or not the theme supports theme.json. * * @since 5.8.0 * @var bool */ protected static $theme_has_support = null; /** * Container for data coming from the user. * * @since 5.9.0 * @var WP_Theme_JSON */ protected static $user = null; /** * Stores the ID of the custom post type * that holds the user data. * * @since 5.9.0 * @var int */ protected static $user_custom_post_type_id = null; /** * Container to keep loaded i18n schema for `theme.json`. * * @since 5.8.0 As `$theme_json_i18n`. * @since 5.9.0 Renamed from `$theme_json_i18n` to `$i18n_schema`. * @var array */ protected static $i18n_schema = null; /** * `theme.json` file cache. * * @since 6.1.0 * @var array */ protected static $theme_json_file_cache = array(); /** * Processes a file that adheres to the theme.json schema * and returns an array with its contents, or a void array if none found. * * @since 5.8.0 * @since 6.1.0 Added caching. * * @param string $file_path Path to file. Empty if no file. * @return array Contents that adhere to the theme.json schema. */ protected static function read_json_file( $file_path ) { if ( $file_path ) { if ( array_key_exists( $file_path, static::$theme_json_file_cache ) ) { return static::$theme_json_file_cache[ $file_path ]; } $decoded_file = wp_json_file_decode( $file_path, array( 'associative' => true ) ); if ( is_array( $decoded_file ) ) { static::$theme_json_file_cache[ $file_path ] = $decoded_file; return static::$theme_json_file_cache[ $file_path ]; } } return array(); } /** * Returns a data structure used in theme.json translation. * * @since 5.8.0 * @deprecated 5.9.0 * * @return array An array of theme.json fields that are translatable and the keys that are translatable. */ public static function get_fields_to_translate() { _deprecated_function( __METHOD__, '5.9.0' ); return array(); } /** * Given a theme.json structure modifies it in place to update certain values * by its translated strings according to the language set by the user. * * @since 5.8.0 * * @param array $theme_json The theme.json to translate. * @param string $domain Optional. Text domain. Unique identifier for retrieving translated strings. * Default 'default'. * @return array Returns the modified $theme_json_structure. */ protected static function translate( $theme_json, $domain = 'default' ) { if ( null === static::$i18n_schema ) { $i18n_schema = wp_json_file_decode( __DIR__ . '/theme-i18n.json' ); static::$i18n_schema = null === $i18n_schema ? array() : $i18n_schema; } return translate_settings_using_i18n_schema( static::$i18n_schema, $theme_json, $domain ); } /** * Returns core's origin config. * * @since 5.8.0 * * @return WP_Theme_JSON Entity that holds core data. */ public static function get_core_data() { if ( null !== static::$core && static::has_same_registered_blocks( 'core' ) ) { return static::$core; } $config = static::read_json_file( __DIR__ . '/theme.json' ); $config = static::translate( $config ); /** * Filters the default data provided by WordPress for global styles & settings. * * @since 6.1.0 * * @param WP_Theme_JSON_Data Class to access and update the underlying data. */ $theme_json = apply_filters( 'wp_theme_json_data_default', new WP_Theme_JSON_Data( $config, 'default' ) ); $config = $theme_json->get_data(); static::$core = new WP_Theme_JSON( $config, 'default' ); return static::$core; } /** * Checks whether the registered blocks were already processed for this origin. * * @since 6.1.0 * * @param string $origin Data source for which to cache the blocks. * Valid values are 'core', 'blocks', 'theme', and 'user'. * @return bool True on success, false otherwise. */ protected static function has_same_registered_blocks( $origin ) { // Bail out if the origin is invalid. if ( ! isset( static::$blocks_cache[ $origin ] ) ) { return false; } $registry = WP_Block_Type_Registry::get_instance(); $blocks = $registry->get_all_registered(); // Is there metadata for all currently registered blocks? $block_diff = array_diff_key( $blocks, static::$blocks_cache[ $origin ] ); if ( empty( $block_diff ) ) { return true; } foreach ( $blocks as $block_name => $block_type ) { static::$blocks_cache[ $origin ][ $block_name ] = true; } return false; } /** * Returns the theme's data. * * Data from theme.json will be backfilled from existing * theme supports, if any. Note that if the same data * is present in theme.json and in theme supports, * the theme.json takes precedence. * * @since 5.8.0 * @since 5.9.0 Theme supports have been inlined and the `$theme_support_data` argument removed. * @since 6.0.0 Added an `$options` parameter to allow the theme data to be returned without theme supports. * * @param array $deprecated Deprecated. Not used. * @param array $options { * Options arguments. * * @type bool $with_supports Whether to include theme supports in the data. Default true. * } * @return WP_Theme_JSON Entity that holds theme data. */ public static function get_theme_data( $deprecated = array(), $options = array() ) { if ( ! empty( $deprecated ) ) { _deprecated_argument( __METHOD__, '5.9.0' ); } $options = wp_parse_args( $options, array( 'with_supports' => true ) ); if ( null === static::$theme || ! static::has_same_registered_blocks( 'theme' ) ) { $theme_json_data = static::read_json_file( static::get_file_path_from_theme( 'theme.json' ) ); $theme_json_data = static::translate( $theme_json_data, wp_get_theme()->get( 'TextDomain' ) ); /** * Filters the data provided by the theme for global styles and settings. * * @since 6.1.0 * * @param WP_Theme_JSON_Data Class to access and update the underlying data. */ $theme_json = apply_filters( 'wp_theme_json_data_theme', new WP_Theme_JSON_Data( $theme_json_data, 'theme' ) ); $theme_json_data = $theme_json->get_data(); static::$theme = new WP_Theme_JSON( $theme_json_data ); } if ( wp_get_theme()->parent() ) { // Get parent theme.json. $parent_theme_json_data = static::read_json_file( static::get_file_path_from_theme( 'theme.json', true ) ); $parent_theme_json_data = static::translate( $parent_theme_json_data, wp_get_theme()->parent()->get( 'TextDomain' ) ); $parent_theme = new WP_Theme_JSON( $parent_theme_json_data ); /* * Merge the child theme.json into the parent theme.json. * The child theme takes precedence over the parent. */ $parent_theme->merge( static::$theme ); static::$theme = $parent_theme; } if ( ! $options['with_supports'] ) { return static::$theme; } /* * We want the presets and settings declared in theme.json * to override the ones declared via theme supports. * So we take theme supports, transform it to theme.json shape * and merge the static::$theme upon that. */ $theme_support_data = WP_Theme_JSON::get_from_editor_settings( get_default_block_editor_settings() ); if ( ! static::theme_has_support() ) { if ( ! isset( $theme_support_data['settings']['color'] ) ) { $theme_support_data['settings']['color'] = array(); } $default_palette = false; if ( current_theme_supports( 'default-color-palette' ) ) { $default_palette = true; } if ( ! isset( $theme_support_data['settings']['color']['palette'] ) ) { // If the theme does not have any palette, we still want to show the core one. $default_palette = true; } $theme_support_data['settings']['color']['defaultPalette'] = $default_palette; $default_gradients = false; if ( current_theme_supports( 'default-gradient-presets' ) ) { $default_gradients = true; } if ( ! isset( $theme_support_data['settings']['color']['gradients'] ) ) { // If the theme does not have any gradients, we still want to show the core ones. $default_gradients = true; } $theme_support_data['settings']['color']['defaultGradients'] = $default_gradients; // Classic themes without a theme.json don't support global duotone. $theme_support_data['settings']['color']['defaultDuotone'] = false; } $with_theme_supports = new WP_Theme_JSON( $theme_support_data ); $with_theme_supports->merge( static::$theme ); return $with_theme_supports; } /** * Gets the styles for blocks from the block.json file. * * @since 6.1.0 * * @return WP_Theme_JSON */ public static function get_block_data() { $registry = WP_Block_Type_Registry::get_instance(); $blocks = $registry->get_all_registered(); if ( null !== static::$blocks && static::has_same_registered_blocks( 'blocks' ) ) { return static::$blocks; } $config = array( 'version' => 2 ); foreach ( $blocks as $block_name => $block_type ) { if ( isset( $block_type->supports['__experimentalStyle'] ) ) { $config['styles']['blocks'][ $block_name ] = static::remove_json_comments( $block_type->supports['__experimentalStyle'] ); } if ( isset( $block_type->supports['spacing']['blockGap']['__experimentalDefault'] ) && null === _wp_array_get( $config, array( 'styles', 'blocks', $block_name, 'spacing', 'blockGap' ), null ) ) { // Ensure an empty placeholder value exists for the block, if it provides a default blockGap value. // The real blockGap value to be used will be determined when the styles are rendered for output. $config['styles']['blocks'][ $block_name ]['spacing']['blockGap'] = null; } } /** * Filters the data provided by the blocks for global styles & settings. * * @since 6.1.0 * * @param WP_Theme_JSON_Data Class to access and update the underlying data. */ $theme_json = apply_filters( 'wp_theme_json_data_blocks', new WP_Theme_JSON_Data( $config, 'blocks' ) ); $config = $theme_json->get_data(); static::$blocks = new WP_Theme_JSON( $config, 'blocks' ); return static::$blocks; } /** * When given an array, this will remove any keys with the name `//`. * * @param array $array The array to filter. * @return array The filtered array. */ private static function remove_json_comments( $array ) { unset( $array['//'] ); foreach ( $array as $k => $v ) { if ( is_array( $v ) ) { $array[ $k ] = static::remove_json_comments( $v ); } } return $array; } /** * Returns the custom post type that contains the user's origin config * for the active theme or a void array if none are found. * * This can also create and return a new draft custom post type. * * @since 5.9.0 * * @param WP_Theme $theme The theme object. If empty, it * defaults to the active theme. * @param bool $create_post Optional. Whether a new custom post * type should be created if none are * found. Default false. * @param array $post_status_filter Optional. Filter custom post type by * post status. Default `array( 'publish' )`, * so it only fetches published posts. * @return array Custom Post Type for the user's origin config. */ public static function get_user_data_from_wp_global_styles( $theme, $create_post = false, $post_status_filter = array( 'publish' ) ) { if ( ! $theme instanceof WP_Theme ) { $theme = wp_get_theme(); } $user_cpt = array(); $post_type_filter = 'wp_global_styles'; $stylesheet = $theme->get_stylesheet(); $args = array( 'posts_per_page' => 1, 'orderby' => 'post_date', 'order' => 'desc', 'post_type' => $post_type_filter, 'post_status' => $post_status_filter, 'ignore_sticky_posts' => true, 'no_found_rows' => true, 'tax_query' => array( array( 'taxonomy' => 'wp_theme', 'field' => 'name', 'terms' => $stylesheet, ), ), ); $global_style_query = new WP_Query(); $recent_posts = $global_style_query->query( $args ); if ( count( $recent_posts ) === 1 ) { $user_cpt = get_post( $recent_posts[0], ARRAY_A ); } elseif ( $create_post ) { $cpt_post_id = wp_insert_post( array( 'post_content' => '{"version": ' . WP_Theme_JSON::LATEST_SCHEMA . ', "isGlobalStylesUserThemeJSON": true }', 'post_status' => 'publish', 'post_title' => 'Custom Styles', // Do not make string translatable, see https://core.trac.wordpress.org/ticket/54518. 'post_type' => $post_type_filter, 'post_name' => sprintf( 'wp-global-styles-%s', urlencode( $stylesheet ) ), 'tax_input' => array( 'wp_theme' => array( $stylesheet ), ), ), true ); if ( ! is_wp_error( $cpt_post_id ) ) { $user_cpt = get_post( $cpt_post_id, ARRAY_A ); } } return $user_cpt; } /** * Returns the user's origin config. * * @since 5.9.0 * * @return WP_Theme_JSON Entity that holds styles for user data. */ public static function get_user_data() { if ( null !== static::$user && static::has_same_registered_blocks( 'user' ) ) { return static::$user; } $config = array(); $user_cpt = static::get_user_data_from_wp_global_styles( wp_get_theme() ); if ( array_key_exists( 'post_content', $user_cpt ) ) { $decoded_data = json_decode( $user_cpt['post_content'], true ); $json_decoding_error = json_last_error(); if ( JSON_ERROR_NONE !== $json_decoding_error ) { trigger_error( 'Error when decoding a theme.json schema for user data. ' . json_last_error_msg() ); /** * Filters the data provided by the user for global styles & settings. * * @since 6.1.0 * * @param WP_Theme_JSON_Data Class to access and update the underlying data. */ $theme_json = apply_filters( 'wp_theme_json_data_user', new WP_Theme_JSON_Data( $config, 'custom' ) ); $config = $theme_json->get_data(); return new WP_Theme_JSON( $config, 'custom' ); } // Very important to verify that the flag isGlobalStylesUserThemeJSON is true. // If it's not true then the content was not escaped and is not safe. if ( is_array( $decoded_data ) && isset( $decoded_data['isGlobalStylesUserThemeJSON'] ) && $decoded_data['isGlobalStylesUserThemeJSON'] ) { unset( $decoded_data['isGlobalStylesUserThemeJSON'] ); $config = $decoded_data; } } /** This filter is documented in wp-includes/class-wp-theme-json-resolver.php */ $theme_json = apply_filters( 'wp_theme_json_data_user', new WP_Theme_JSON_Data( $config, 'custom' ) ); $config = $theme_json->get_data(); static::$user = new WP_Theme_JSON( $config, 'custom' ); return static::$user; } /** * Returns the data merged from multiple origins. * * There are three sources of data (origins) for a site: * default, theme, and custom. The custom's has higher priority * than the theme's, and the theme's higher than default's. * * Unlike the getters * {@link https://developer.wordpress.org/reference/classes/wp_theme_json_resolver/get_core_data/ get_core_data}, * {@link https://developer.wordpress.org/reference/classes/wp_theme_json_resolver/get_theme_data/ get_theme_data}, * and {@link https://developer.wordpress.org/reference/classes/wp_theme_json_resolver/get_user_data/ get_user_data}, * this method returns data after it has been merged with the previous origins. * This means that if the same piece of data is declared in different origins * (user, theme, and core), the last origin overrides the previous. * * For example, if the user has set a background color * for the paragraph block, and the theme has done it as well, * the user preference wins. * * @since 5.8.0 * @since 5.9.0 Added user data, removed the `$settings` parameter, * added the `$origin` parameter. * @since 6.1.0 Added block data and generation of spacingSizes array. * * @param string $origin Optional. To what level should we merge data. * Valid values are 'theme' or 'custom'. Default 'custom'. * @return WP_Theme_JSON */ public static function get_merged_data( $origin = 'custom' ) { if ( is_array( $origin ) ) { _deprecated_argument( __FUNCTION__, '5.9.0' ); } $result = static::get_core_data(); $result->merge( static::get_block_data() ); $result->merge( static::get_theme_data() ); if ( 'custom' === $origin ) { $result->merge( static::get_user_data() ); } // Generate the default spacingSizes array based on the merged spacingScale settings. $result->set_spacing_sizes(); return $result; } /** * Returns the ID of the custom post type * that stores user data. * * @since 5.9.0 * * @return integer|null */ public static function get_user_global_styles_post_id() { if ( null !== static::$user_custom_post_type_id ) { return static::$user_custom_post_type_id; } $user_cpt = static::get_user_data_from_wp_global_styles( wp_get_theme(), true ); if ( array_key_exists( 'ID', $user_cpt ) ) { static::$user_custom_post_type_id = $user_cpt['ID']; } return static::$user_custom_post_type_id; } /** * Determines whether the active theme has a theme.json file. * * @since 5.8.0 * @since 5.9.0 Added a check in the parent theme. * * @return bool */ public static function theme_has_support() { if ( ! isset( static::$theme_has_support ) ) { static::$theme_has_support = ( is_readable( static::get_file_path_from_theme( 'theme.json' ) ) || is_readable( static::get_file_path_from_theme( 'theme.json', true ) ) ); } return static::$theme_has_support; } /** * Builds the path to the given file and checks that it is readable. * * If it isn't, returns an empty string, otherwise returns the whole file path. * * @since 5.8.0 * @since 5.9.0 Adapted to work with child themes, added the `$template` argument. * * @param string $file_name Name of the file. * @param bool $template Optional. Use template theme directory. Default false. * @return string The whole file path or empty if the file doesn't exist. */ protected static function get_file_path_from_theme( $file_name, $template = false ) { $path = $template ? get_template_directory() : get_stylesheet_directory(); $candidate = $path . '/' . $file_name; return is_readable( $candidate ) ? $candidate : ''; } /** * Cleans the cached data so it can be recalculated. * * @since 5.8.0 * @since 5.9.0 Added the `$user`, `$user_custom_post_type_id`, * and `$i18n_schema` variables to reset. * @since 6.1.0 Added the `$blocks` and `$blocks_cache` variables * to reset. */ public static function clean_cached_data() { static::$core = null; static::$blocks = null; static::$blocks_cache = array( 'core' => array(), 'blocks' => array(), 'theme' => array(), 'user' => array(), ); static::$theme = null; static::$user = null; static::$user_custom_post_type_id = null; static::$theme_has_support = null; static::$i18n_schema = null; } /** * Returns the style variations defined by the theme. * * @since 6.0.0 * * @return array */ public static function get_style_variations() { $variations = array(); $base_directory = get_stylesheet_directory() . '/styles'; if ( is_dir( $base_directory ) ) { $nested_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $base_directory ) ); $nested_html_files = iterator_to_array( new RegexIterator( $nested_files, '/^.+\.json$/i', RecursiveRegexIterator::GET_MATCH ) ); ksort( $nested_html_files ); foreach ( $nested_html_files as $path => $file ) { $decoded_file = wp_json_file_decode( $path, array( 'associative' => true ) ); if ( is_array( $decoded_file ) ) { $translated = static::translate( $decoded_file, wp_get_theme()->get( 'TextDomain' ) ); $variation = ( new WP_Theme_JSON( $translated ) )->get_raw_data(); if ( empty( $variation['title'] ) ) { $variation['title'] = basename( $path, '.json' ); } $variations[] = $variation; } } } return $variations; } } ```
programming_docs
wordpress class WP_Filesystem_FTPext {} class WP\_Filesystem\_FTPext {} =============================== WordPress Filesystem Class for implementing FTP. * [WP\_Filesystem\_Base](wp_filesystem_base) * [\_\_construct](wp_filesystem_ftpext/__construct) β€” Constructor. * [\_\_destruct](wp_filesystem_ftpext/__destruct) β€” Destructor. * [atime](wp_filesystem_ftpext/atime) β€” Gets the file's last access time. * [chdir](wp_filesystem_ftpext/chdir) β€” Changes current directory. * [chmod](wp_filesystem_ftpext/chmod) β€” Changes filesystem permissions. * [connect](wp_filesystem_ftpext/connect) β€” Connects filesystem. * [copy](wp_filesystem_ftpext/copy) β€” Copies a file. * [cwd](wp_filesystem_ftpext/cwd) β€” Gets the current working directory. * [delete](wp_filesystem_ftpext/delete) β€” Deletes a file or directory. * [dirlist](wp_filesystem_ftpext/dirlist) β€” Gets details for files in a directory or a specific file. * [exists](wp_filesystem_ftpext/exists) β€” Checks if a file or directory exists. * [get\_contents](wp_filesystem_ftpext/get_contents) β€” Reads entire file into a string. * [get\_contents\_array](wp_filesystem_ftpext/get_contents_array) β€” Reads entire file into an array. * [getchmod](wp_filesystem_ftpext/getchmod) β€” Gets the permissions of the specified file or filepath in their octal format. * [group](wp_filesystem_ftpext/group) β€” Gets the file's group. * [is\_dir](wp_filesystem_ftpext/is_dir) β€” Checks if resource is a directory. * [is\_file](wp_filesystem_ftpext/is_file) β€” Checks if resource is a file. * [is\_readable](wp_filesystem_ftpext/is_readable) β€” Checks if a file is readable. * [is\_writable](wp_filesystem_ftpext/is_writable) β€” Checks if a file or directory is writable. * [mkdir](wp_filesystem_ftpext/mkdir) β€” Creates a directory. * [move](wp_filesystem_ftpext/move) β€” Moves a file. * [mtime](wp_filesystem_ftpext/mtime) β€” Gets the file modification time. * [owner](wp_filesystem_ftpext/owner) β€” Gets the file owner. * [parselisting](wp_filesystem_ftpext/parselisting) * [put\_contents](wp_filesystem_ftpext/put_contents) β€” Writes a string to a file. * [rmdir](wp_filesystem_ftpext/rmdir) β€” Deletes a directory. * [size](wp_filesystem_ftpext/size) β€” Gets the file size (in bytes). * [touch](wp_filesystem_ftpext/touch) β€” Sets the access and modification times of a file. File: `wp-admin/includes/class-wp-filesystem-ftpext.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-ftpext.php/) ``` class WP_Filesystem_FTPext extends WP_Filesystem_Base { /** * @since 2.5.0 * @var resource */ public $link; /** * Constructor. * * @since 2.5.0 * * @param array $opt */ public function __construct( $opt = '' ) { $this->method = 'ftpext'; $this->errors = new WP_Error(); // Check if possible to use ftp functions. if ( ! extension_loaded( 'ftp' ) ) { $this->errors->add( 'no_ftp_ext', __( 'The ftp PHP extension is not available' ) ); return; } // This class uses the timeout on a per-connection basis, others use it on a per-action basis. if ( ! defined( 'FS_TIMEOUT' ) ) { define( 'FS_TIMEOUT', 4 * MINUTE_IN_SECONDS ); } if ( empty( $opt['port'] ) ) { $this->options['port'] = 21; } else { $this->options['port'] = $opt['port']; } if ( empty( $opt['hostname'] ) ) { $this->errors->add( 'empty_hostname', __( 'FTP hostname is required' ) ); } else { $this->options['hostname'] = $opt['hostname']; } // Check if the options provided are OK. if ( empty( $opt['username'] ) ) { $this->errors->add( 'empty_username', __( 'FTP username is required' ) ); } else { $this->options['username'] = $opt['username']; } if ( empty( $opt['password'] ) ) { $this->errors->add( 'empty_password', __( 'FTP password is required' ) ); } else { $this->options['password'] = $opt['password']; } $this->options['ssl'] = false; if ( isset( $opt['connection_type'] ) && 'ftps' === $opt['connection_type'] ) { $this->options['ssl'] = true; } } /** * Connects filesystem. * * @since 2.5.0 * * @return bool True on success, false on failure. */ public function connect() { if ( isset( $this->options['ssl'] ) && $this->options['ssl'] && function_exists( 'ftp_ssl_connect' ) ) { $this->link = @ftp_ssl_connect( $this->options['hostname'], $this->options['port'], FS_CONNECT_TIMEOUT ); } else { $this->link = @ftp_connect( $this->options['hostname'], $this->options['port'], FS_CONNECT_TIMEOUT ); } if ( ! $this->link ) { $this->errors->add( 'connect', sprintf( /* translators: %s: hostname:port */ __( 'Failed to connect to FTP Server %s' ), $this->options['hostname'] . ':' . $this->options['port'] ) ); return false; } if ( ! @ftp_login( $this->link, $this->options['username'], $this->options['password'] ) ) { $this->errors->add( 'auth', sprintf( /* translators: %s: Username. */ __( 'Username/Password incorrect for %s' ), $this->options['username'] ) ); return false; } // Set the connection to use Passive FTP. ftp_pasv( $this->link, true ); if ( @ftp_get_option( $this->link, FTP_TIMEOUT_SEC ) < FS_TIMEOUT ) { @ftp_set_option( $this->link, FTP_TIMEOUT_SEC, FS_TIMEOUT ); } return true; } /** * Reads entire file into a string. * * @since 2.5.0 * * @param string $file Name of the file to read. * @return string|false Read data on success, false if no temporary file could be opened, * or if the file couldn't be retrieved. */ public function get_contents( $file ) { $tempfile = wp_tempnam( $file ); $temphandle = fopen( $tempfile, 'w+' ); if ( ! $temphandle ) { unlink( $tempfile ); return false; } if ( ! ftp_fget( $this->link, $temphandle, $file, FTP_BINARY ) ) { fclose( $temphandle ); unlink( $tempfile ); return false; } fseek( $temphandle, 0 ); // Skip back to the start of the file being written to. $contents = ''; while ( ! feof( $temphandle ) ) { $contents .= fread( $temphandle, 8 * KB_IN_BYTES ); } fclose( $temphandle ); unlink( $tempfile ); return $contents; } /** * Reads entire file into an array. * * @since 2.5.0 * * @param string $file Path to the file. * @return array|false File contents in an array on success, false on failure. */ public function get_contents_array( $file ) { return explode( "\n", $this->get_contents( $file ) ); } /** * Writes a string to a file. * * @since 2.5.0 * * @param string $file Remote path to the file where to write the data. * @param string $contents The data to write. * @param int|false $mode Optional. The file permissions as octal number, usually 0644. * Default false. * @return bool True on success, false on failure. */ public function put_contents( $file, $contents, $mode = false ) { $tempfile = wp_tempnam( $file ); $temphandle = fopen( $tempfile, 'wb+' ); if ( ! $temphandle ) { unlink( $tempfile ); return false; } mbstring_binary_safe_encoding(); $data_length = strlen( $contents ); $bytes_written = fwrite( $temphandle, $contents ); reset_mbstring_encoding(); if ( $data_length !== $bytes_written ) { fclose( $temphandle ); unlink( $tempfile ); return false; } fseek( $temphandle, 0 ); // Skip back to the start of the file being written to. $ret = ftp_fput( $this->link, $file, $temphandle, FTP_BINARY ); fclose( $temphandle ); unlink( $tempfile ); $this->chmod( $file, $mode ); return $ret; } /** * Gets the current working directory. * * @since 2.5.0 * * @return string|false The current working directory on success, false on failure. */ public function cwd() { $cwd = ftp_pwd( $this->link ); if ( $cwd ) { $cwd = trailingslashit( $cwd ); } return $cwd; } /** * Changes current directory. * * @since 2.5.0 * * @param string $dir The new current directory. * @return bool True on success, false on failure. */ public function chdir( $dir ) { return @ftp_chdir( $this->link, $dir ); } /** * Changes filesystem permissions. * * @since 2.5.0 * * @param string $file Path to the file. * @param int|false $mode Optional. The permissions as octal number, usually 0644 for files, * 0755 for directories. Default false. * @param bool $recursive Optional. If set to true, changes file permissions recursively. * Default false. * @return bool True on success, false on failure. */ public function chmod( $file, $mode = false, $recursive = false ) { if ( ! $mode ) { if ( $this->is_file( $file ) ) { $mode = FS_CHMOD_FILE; } elseif ( $this->is_dir( $file ) ) { $mode = FS_CHMOD_DIR; } else { return false; } } // chmod any sub-objects if recursive. if ( $recursive && $this->is_dir( $file ) ) { $filelist = $this->dirlist( $file ); foreach ( (array) $filelist as $filename => $filemeta ) { $this->chmod( $file . '/' . $filename, $mode, $recursive ); } } // chmod the file or directory. if ( ! function_exists( 'ftp_chmod' ) ) { return (bool) ftp_site( $this->link, sprintf( 'CHMOD %o %s', $mode, $file ) ); } return (bool) ftp_chmod( $this->link, $mode, $file ); } /** * Gets the file owner. * * @since 2.5.0 * * @param string $file Path to the file. * @return string|false Username of the owner on success, false on failure. */ public function owner( $file ) { $dir = $this->dirlist( $file ); return $dir[ $file ]['owner']; } /** * Gets the permissions of the specified file or filepath in their octal format. * * @since 2.5.0 * * @param string $file Path to the file. * @return string Mode of the file (the last 3 digits). */ public function getchmod( $file ) { $dir = $this->dirlist( $file ); return $dir[ $file ]['permsn']; } /** * Gets the file's group. * * @since 2.5.0 * * @param string $file Path to the file. * @return string|false The group on success, false on failure. */ public function group( $file ) { $dir = $this->dirlist( $file ); return $dir[ $file ]['group']; } /** * Copies a file. * * @since 2.5.0 * * @param string $source Path to the source file. * @param string $destination Path to the destination file. * @param bool $overwrite Optional. Whether to overwrite the destination file if it exists. * Default false. * @param int|false $mode Optional. The permissions as octal number, usually 0644 for files, * 0755 for dirs. Default false. * @return bool True on success, false on failure. */ public function copy( $source, $destination, $overwrite = false, $mode = false ) { if ( ! $overwrite && $this->exists( $destination ) ) { return false; } $content = $this->get_contents( $source ); if ( false === $content ) { return false; } return $this->put_contents( $destination, $content, $mode ); } /** * Moves a file. * * @since 2.5.0 * * @param string $source Path to the source file. * @param string $destination Path to the destination file. * @param bool $overwrite Optional. Whether to overwrite the destination file if it exists. * Default false. * @return bool True on success, false on failure. */ public function move( $source, $destination, $overwrite = false ) { return ftp_rename( $this->link, $source, $destination ); } /** * Deletes a file or directory. * * @since 2.5.0 * * @param string $file Path to the file or directory. * @param bool $recursive Optional. If set to true, deletes files and folders recursively. * Default false. * @param string|false $type Type of resource. 'f' for file, 'd' for directory. * Default false. * @return bool True on success, false on failure. */ public function delete( $file, $recursive = false, $type = false ) { if ( empty( $file ) ) { return false; } if ( 'f' === $type || $this->is_file( $file ) ) { return ftp_delete( $this->link, $file ); } if ( ! $recursive ) { return ftp_rmdir( $this->link, $file ); } $filelist = $this->dirlist( trailingslashit( $file ) ); if ( ! empty( $filelist ) ) { foreach ( $filelist as $delete_file ) { $this->delete( trailingslashit( $file ) . $delete_file['name'], $recursive, $delete_file['type'] ); } } return ftp_rmdir( $this->link, $file ); } /** * Checks if a file or directory exists. * * @since 2.5.0 * @since 6.1.0 Uses WP_Filesystem_FTPext::is_dir() to check for directory existence * and ftp_rawlist() to check for file existence. * * @param string $path Path to file or directory. * @return bool Whether $path exists or not. */ public function exists( $path ) { if ( $this->is_dir( $path ) ) { return true; } return ! empty( ftp_rawlist( $this->link, $path ) ); } /** * Checks if resource is a file. * * @since 2.5.0 * * @param string $file File path. * @return bool Whether $file is a file. */ public function is_file( $file ) { return $this->exists( $file ) && ! $this->is_dir( $file ); } /** * Checks if resource is a directory. * * @since 2.5.0 * * @param string $path Directory path. * @return bool Whether $path is a directory. */ public function is_dir( $path ) { $cwd = $this->cwd(); $result = @ftp_chdir( $this->link, trailingslashit( $path ) ); if ( $result && $path === $this->cwd() || $this->cwd() !== $cwd ) { @ftp_chdir( $this->link, $cwd ); return true; } return false; } /** * Checks if a file is readable. * * @since 2.5.0 * * @param string $file Path to file. * @return bool Whether $file is readable. */ public function is_readable( $file ) { return true; } /** * Checks if a file or directory is writable. * * @since 2.5.0 * * @param string $path Path to file or directory. * @return bool Whether $path is writable. */ public function is_writable( $path ) { return true; } /** * Gets the file's last access time. * * @since 2.5.0 * * @param string $file Path to file. * @return int|false Unix timestamp representing last access time, false on failure. */ public function atime( $file ) { return false; } /** * Gets the file modification time. * * @since 2.5.0 * * @param string $file Path to file. * @return int|false Unix timestamp representing modification time, false on failure. */ public function mtime( $file ) { return ftp_mdtm( $this->link, $file ); } /** * Gets the file size (in bytes). * * @since 2.5.0 * * @param string $file Path to file. * @return int|false Size of the file in bytes on success, false on failure. */ public function size( $file ) { $size = ftp_size( $this->link, $file ); return ( $size > -1 ) ? $size : false; } /** * Sets the access and modification times of a file. * * Note: If $file doesn't exist, it will be created. * * @since 2.5.0 * * @param string $file Path to file. * @param int $time Optional. Modified time to set for file. * Default 0. * @param int $atime Optional. Access time to set for file. * Default 0. * @return bool True on success, false on failure. */ public function touch( $file, $time = 0, $atime = 0 ) { return false; } /** * Creates a directory. * * @since 2.5.0 * * @param string $path Path for new directory. * @param int|false $chmod Optional. The permissions as octal number (or false to skip chmod). * Default false. * @param string|int|false $chown Optional. A user name or number (or false to skip chown). * Default false. * @param string|int|false $chgrp Optional. A group name or number (or false to skip chgrp). * Default false. * @return bool True on success, false on failure. */ public function mkdir( $path, $chmod = false, $chown = false, $chgrp = false ) { $path = untrailingslashit( $path ); if ( empty( $path ) ) { return false; } if ( ! ftp_mkdir( $this->link, $path ) ) { return false; } $this->chmod( $path, $chmod ); return true; } /** * Deletes a directory. * * @since 2.5.0 * * @param string $path Path to directory. * @param bool $recursive Optional. Whether to recursively remove files/directories. * Default false. * @return bool True on success, false on failure. */ public function rmdir( $path, $recursive = false ) { return $this->delete( $path, $recursive ); } /** * @param string $line * @return array */ public function parselisting( $line ) { static $is_windows = null; if ( is_null( $is_windows ) ) { $is_windows = stripos( ftp_systype( $this->link ), 'win' ) !== false; } if ( $is_windows && preg_match( '/([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|<DIR>) +(.+)/', $line, $lucifer ) ) { $b = array(); if ( $lucifer[3] < 70 ) { $lucifer[3] += 2000; } else { $lucifer[3] += 1900; // 4-digit year fix. } $b['isdir'] = ( '<DIR>' === $lucifer[7] ); if ( $b['isdir'] ) { $b['type'] = 'd'; } else { $b['type'] = 'f'; } $b['size'] = $lucifer[7]; $b['month'] = $lucifer[1]; $b['day'] = $lucifer[2]; $b['year'] = $lucifer[3]; $b['hour'] = $lucifer[4]; $b['minute'] = $lucifer[5]; $b['time'] = mktime( $lucifer[4] + ( strcasecmp( $lucifer[6], 'PM' ) === 0 ? 12 : 0 ), $lucifer[5], 0, $lucifer[1], $lucifer[2], $lucifer[3] ); $b['am/pm'] = $lucifer[6]; $b['name'] = $lucifer[8]; } elseif ( ! $is_windows ) { $lucifer = preg_split( '/[ ]/', $line, 9, PREG_SPLIT_NO_EMPTY ); if ( $lucifer ) { // echo $line."\n"; $lcount = count( $lucifer ); if ( $lcount < 8 ) { return ''; } $b = array(); $b['isdir'] = 'd' === $lucifer[0][0]; $b['islink'] = 'l' === $lucifer[0][0]; if ( $b['isdir'] ) { $b['type'] = 'd'; } elseif ( $b['islink'] ) { $b['type'] = 'l'; } else { $b['type'] = 'f'; } $b['perms'] = $lucifer[0]; $b['permsn'] = $this->getnumchmodfromh( $b['perms'] ); $b['number'] = $lucifer[1]; $b['owner'] = $lucifer[2]; $b['group'] = $lucifer[3]; $b['size'] = $lucifer[4]; if ( 8 === $lcount ) { sscanf( $lucifer[5], '%d-%d-%d', $b['year'], $b['month'], $b['day'] ); sscanf( $lucifer[6], '%d:%d', $b['hour'], $b['minute'] ); $b['time'] = mktime( $b['hour'], $b['minute'], 0, $b['month'], $b['day'], $b['year'] ); $b['name'] = $lucifer[7]; } else { $b['month'] = $lucifer[5]; $b['day'] = $lucifer[6]; if ( preg_match( '/([0-9]{2}):([0-9]{2})/', $lucifer[7], $l2 ) ) { $b['year'] = gmdate( 'Y' ); $b['hour'] = $l2[1]; $b['minute'] = $l2[2]; } else { $b['year'] = $lucifer[7]; $b['hour'] = 0; $b['minute'] = 0; } $b['time'] = strtotime( sprintf( '%d %s %d %02d:%02d', $b['day'], $b['month'], $b['year'], $b['hour'], $b['minute'] ) ); $b['name'] = $lucifer[8]; } } } // Replace symlinks formatted as "source -> target" with just the source name. if ( isset( $b['islink'] ) && $b['islink'] ) { $b['name'] = preg_replace( '/(\s*->\s*.*)$/', '', $b['name'] ); } return $b; } /** * Gets details for files in a directory or a specific file. * * @since 2.5.0 * * @param string $path Path to directory or file. * @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files. * Default true. * @param bool $recursive Optional. Whether to recursively include file details in nested directories. * Default false. * @return array|false { * Array of files. False if unable to list directory contents. * * @type string $name Name of the file or directory. * @type string $perms *nix representation of permissions. * @type string $permsn Octal representation of permissions. * @type string $owner Owner name or ID. * @type int $size Size of file in bytes. * @type int $lastmodunix Last modified unix timestamp. * @type mixed $lastmod Last modified month (3 letter) and day (without leading 0). * @type int $time Last modified time. * @type string $type Type of resource. 'f' for file, 'd' for directory. * @type mixed $files If a directory and `$recursive` is true, contains another array of files. * } */ public function dirlist( $path = '.', $include_hidden = true, $recursive = false ) { if ( $this->is_file( $path ) ) { $limit_file = basename( $path ); $path = dirname( $path ) . '/'; } else { $limit_file = false; } $pwd = ftp_pwd( $this->link ); if ( ! @ftp_chdir( $this->link, $path ) ) { // Can't change to folder = folder doesn't exist. return false; } $list = ftp_rawlist( $this->link, '-a', false ); @ftp_chdir( $this->link, $pwd ); if ( empty( $list ) ) { // Empty array = non-existent folder (real folder will show . at least). return false; } $dirlist = array(); foreach ( $list as $k => $v ) { $entry = $this->parselisting( $v ); if ( empty( $entry ) ) { continue; } if ( '.' === $entry['name'] || '..' === $entry['name'] ) { continue; } if ( ! $include_hidden && '.' === $entry['name'][0] ) { continue; } if ( $limit_file && $entry['name'] !== $limit_file ) { continue; } $dirlist[ $entry['name'] ] = $entry; } $ret = array(); foreach ( (array) $dirlist as $struc ) { if ( 'd' === $struc['type'] ) { if ( $recursive ) { $struc['files'] = $this->dirlist( $path . '/' . $struc['name'], $include_hidden, $recursive ); } else { $struc['files'] = array(); } } $ret[ $struc['name'] ] = $struc; } return $ret; } /** * Destructor. * * @since 2.5.0 */ public function __destruct() { if ( $this->link ) { ftp_close( $this->link ); } } } ``` | Uses | Description | | --- | --- | | [WP\_Filesystem\_Base](wp_filesystem_base) wp-admin/includes/class-wp-filesystem-base.php | Base WordPress Filesystem class which Filesystem implementations extend. | | Version | Description | | --- | --- | | [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
programming_docs
wordpress class Walker_Category {} class Walker\_Category {} ========================= Core class used to create an HTML list of categories. * [Walker](walker) * [end\_el](walker_category/end_el) β€” Ends the element output, if needed. * [end\_lvl](walker_category/end_lvl) β€” Ends the list of after the elements are added. * [start\_el](walker_category/start_el) β€” Starts the element output. * [start\_lvl](walker_category/start_lvl) β€” Starts the list before the elements are added. File: `wp-includes/class-walker-category.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-category.php/) ``` class Walker_Category extends Walker { /** * What the class handles. * * @since 2.1.0 * @var string * * @see Walker::$tree_type */ public $tree_type = 'category'; /** * Database fields to use. * * @since 2.1.0 * @var string[] * * @see Walker::$db_fields * @todo Decouple this */ public $db_fields = array( 'parent' => 'parent', 'id' => 'term_id', ); /** * Starts the list before the elements are added. * * @since 2.1.0 * * @see Walker::start_lvl() * * @param string $output Used to append additional content. Passed by reference. * @param int $depth Optional. Depth of category. Used for tab indentation. Default 0. * @param array $args Optional. An array of arguments. Will only append content if style argument * value is 'list'. See wp_list_categories(). Default empty array. */ public function start_lvl( &$output, $depth = 0, $args = array() ) { if ( 'list' !== $args['style'] ) { return; } $indent = str_repeat( "\t", $depth ); $output .= "$indent<ul class='children'>\n"; } /** * Ends the list of after the elements are added. * * @since 2.1.0 * * @see Walker::end_lvl() * * @param string $output Used to append additional content. Passed by reference. * @param int $depth Optional. Depth of category. Used for tab indentation. Default 0. * @param array $args Optional. An array of arguments. Will only append content if style argument * value is 'list'. See wp_list_categories(). Default empty array. */ public function end_lvl( &$output, $depth = 0, $args = array() ) { if ( 'list' !== $args['style'] ) { return; } $indent = str_repeat( "\t", $depth ); $output .= "$indent</ul>\n"; } /** * Starts the element output. * * @since 2.1.0 * @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. * * @see Walker::start_el() * * @param string $output Used to append additional content (passed by reference). * @param WP_Term $data_object Category data object. * @param int $depth Optional. Depth of category in reference to parents. Default 0. * @param array $args Optional. An array of arguments. See wp_list_categories(). * Default empty array. * @param int $current_object_id Optional. ID of the current category. Default 0. */ public function start_el( &$output, $data_object, $depth = 0, $args = array(), $current_object_id = 0 ) { // Restores the more descriptive, specific name for use within this method. $category = $data_object; /** This filter is documented in wp-includes/category-template.php */ $cat_name = apply_filters( 'list_cats', esc_attr( $category->name ), $category ); // Don't generate an element if the category name is empty. if ( '' === $cat_name ) { return; } $atts = array(); $atts['href'] = get_term_link( $category ); if ( $args['use_desc_for_title'] && ! empty( $category->description ) ) { /** * Filters the category description for display. * * @since 1.2.0 * * @param string $description Category description. * @param WP_Term $category Category object. */ $atts['title'] = strip_tags( apply_filters( 'category_description', $category->description, $category ) ); } /** * Filters the HTML attributes applied to a category list item's anchor element. * * @since 5.2.0 * * @param array $atts { * The HTML attributes applied to the list item's `<a>` element, empty strings are ignored. * * @type string $href The href attribute. * @type string $title The title attribute. * } * @param WP_Term $category Term data object. * @param int $depth Depth of category, used for padding. * @param array $args An array of arguments. * @param int $current_object_id ID of the current category. */ $atts = apply_filters( 'category_list_link_attributes', $atts, $category, $depth, $args, $current_object_id ); $attributes = ''; foreach ( $atts as $attr => $value ) { if ( is_scalar( $value ) && '' !== $value && false !== $value ) { $value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value ); $attributes .= ' ' . $attr . '="' . $value . '"'; } } $link = sprintf( '<a%s>%s</a>', $attributes, $cat_name ); if ( ! empty( $args['feed_image'] ) || ! empty( $args['feed'] ) ) { $link .= ' '; if ( empty( $args['feed_image'] ) ) { $link .= '('; } $link .= '<a href="' . esc_url( get_term_feed_link( $category, $category->taxonomy, $args['feed_type'] ) ) . '"'; if ( empty( $args['feed'] ) ) { /* translators: %s: Category name. */ $alt = ' alt="' . sprintf( __( 'Feed for all posts filed under %s' ), $cat_name ) . '"'; } else { $alt = ' alt="' . $args['feed'] . '"'; $name = $args['feed']; $link .= empty( $args['title'] ) ? '' : $args['title']; } $link .= '>'; if ( empty( $args['feed_image'] ) ) { $link .= $name; } else { $link .= "<img src='" . esc_url( $args['feed_image'] ) . "'$alt" . ' />'; } $link .= '</a>'; if ( empty( $args['feed_image'] ) ) { $link .= ')'; } } if ( ! empty( $args['show_count'] ) ) { $link .= ' (' . number_format_i18n( $category->count ) . ')'; } if ( 'list' === $args['style'] ) { $output .= "\t<li"; $css_classes = array( 'cat-item', 'cat-item-' . $category->term_id, ); if ( ! empty( $args['current_category'] ) ) { // 'current_category' can be an array, so we use `get_terms()`. $_current_terms = get_terms( array( 'taxonomy' => $category->taxonomy, 'include' => $args['current_category'], 'hide_empty' => false, ) ); foreach ( $_current_terms as $_current_term ) { if ( $category->term_id == $_current_term->term_id ) { $css_classes[] = 'current-cat'; $link = str_replace( '<a', '<a aria-current="page"', $link ); } elseif ( $category->term_id == $_current_term->parent ) { $css_classes[] = 'current-cat-parent'; } while ( $_current_term->parent ) { if ( $category->term_id == $_current_term->parent ) { $css_classes[] = 'current-cat-ancestor'; break; } $_current_term = get_term( $_current_term->parent, $category->taxonomy ); } } } /** * Filters the list of CSS classes to include with each category in the list. * * @since 4.2.0 * * @see wp_list_categories() * * @param string[] $css_classes An array of CSS classes to be applied to each list item. * @param WP_Term $category Category data object. * @param int $depth Depth of page, used for padding. * @param array $args An array of wp_list_categories() arguments. */ $css_classes = implode( ' ', apply_filters( 'category_css_class', $css_classes, $category, $depth, $args ) ); $css_classes = $css_classes ? ' class="' . esc_attr( $css_classes ) . '"' : ''; $output .= $css_classes; $output .= ">$link\n"; } elseif ( isset( $args['separator'] ) ) { $output .= "\t$link" . $args['separator'] . "\n"; } else { $output .= "\t$link<br />\n"; } } /** * Ends the element output, if needed. * * @since 2.1.0 * @since 5.9.0 Renamed `$page` to `$data_object` to match parent class for PHP 8 named parameter support. * * @see Walker::end_el() * * @param string $output Used to append additional content (passed by reference). * @param object $data_object Category data object. Not used. * @param int $depth Optional. Depth of category. Not used. * @param array $args Optional. An array of arguments. Only uses 'list' for whether should * append to output. See wp_list_categories(). Default empty array. */ public function end_el( &$output, $data_object, $depth = 0, $args = array() ) { if ( 'list' !== $args['style'] ) { return; } $output .= "</li>\n"; } } ``` | Uses | Description | | --- | --- | | [Walker](walker) wp-includes/class-wp-walker.php | A class for displaying various tree-like structures. | | Version | Description | | --- | --- | | [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. | wordpress class AtomFeed {} class AtomFeed {} ================= Structure that store common Atom Feed Properties File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/) ``` class AtomFeed { /** * Stores Links * @var array * @access public */ var $links = array(); /** * Stores Categories * @var array * @access public */ var $categories = array(); /** * Stores Entries * * @var array * @access public */ var $entries = array(); } ``` wordpress class WP_Image_Editor_GD {} class WP\_Image\_Editor\_GD {} ============================== WordPress Image Editor Class for Image Manipulation through GD * [WP\_Image\_Editor](wp_image_editor) * [\_\_destruct](wp_image_editor_gd/__destruct) * [\_resize](wp_image_editor_gd/_resize) * [\_save](wp_image_editor_gd/_save) * [crop](wp_image_editor_gd/crop) β€” Crops Image. * [flip](wp_image_editor_gd/flip) β€” Flips current image. * [load](wp_image_editor_gd/load) β€” Loads image from $this->file into new GD Resource. * [make\_image](wp_image_editor_gd/make_image) β€” Either calls editor's save function or handles file as a stream. * [make\_subsize](wp_image_editor_gd/make_subsize) β€” Create an image sub-size and return the image meta data value for it. * [multi\_resize](wp_image_editor_gd/multi_resize) β€” Create multiple smaller images from a single source. * [resize](wp_image_editor_gd/resize) β€” Resizes current image. * [rotate](wp_image_editor_gd/rotate) β€” Rotates current image counter-clockwise by $angle. * [save](wp_image_editor_gd/save) β€” Saves current in-memory image to file. * [stream](wp_image_editor_gd/stream) β€” Returns stream of current image. * [supports\_mime\_type](wp_image_editor_gd/supports_mime_type) β€” Checks to see if editor supports the mime-type specified. * [test](wp_image_editor_gd/test) β€” Checks to see if current environment supports GD. * [update\_size](wp_image_editor_gd/update_size) β€” Sets or updates current image size. File: `wp-includes/class-wp-image-editor-gd.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor-gd.php/) ``` class WP_Image_Editor_GD extends WP_Image_Editor { /** * GD Resource. * * @var resource|GdImage */ protected $image; public function __destruct() { if ( $this->image ) { // We don't need the original in memory anymore. imagedestroy( $this->image ); } } /** * Checks to see if current environment supports GD. * * @since 3.5.0 * * @param array $args * @return bool */ public static function test( $args = array() ) { if ( ! extension_loaded( 'gd' ) || ! function_exists( 'gd_info' ) ) { return false; } // On some setups GD library does not provide imagerotate() - Ticket #11536. if ( isset( $args['methods'] ) && in_array( 'rotate', $args['methods'], true ) && ! function_exists( 'imagerotate' ) ) { return false; } return true; } /** * Checks to see if editor supports the mime-type specified. * * @since 3.5.0 * * @param string $mime_type * @return bool */ public static function supports_mime_type( $mime_type ) { $image_types = imagetypes(); switch ( $mime_type ) { case 'image/jpeg': return ( $image_types & IMG_JPG ) != 0; case 'image/png': return ( $image_types & IMG_PNG ) != 0; case 'image/gif': return ( $image_types & IMG_GIF ) != 0; case 'image/webp': return ( $image_types & IMG_WEBP ) != 0; } return false; } /** * Loads image from $this->file into new GD Resource. * * @since 3.5.0 * * @return true|WP_Error True if loaded successfully; WP_Error on failure. */ public function load() { if ( $this->image ) { return true; } if ( ! is_file( $this->file ) && ! preg_match( '|^https?://|', $this->file ) ) { return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file ); } // Set artificially high because GD uses uncompressed images in memory. wp_raise_memory_limit( 'image' ); $file_contents = @file_get_contents( $this->file ); if ( ! $file_contents ) { return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file ); } // WebP may not work with imagecreatefromstring(). if ( function_exists( 'imagecreatefromwebp' ) && ( 'image/webp' === wp_get_image_mime( $this->file ) ) ) { $this->image = @imagecreatefromwebp( $this->file ); } else { $this->image = @imagecreatefromstring( $file_contents ); } if ( ! is_gd_image( $this->image ) ) { return new WP_Error( 'invalid_image', __( 'File is not an image.' ), $this->file ); } $size = wp_getimagesize( $this->file ); if ( ! $size ) { return new WP_Error( 'invalid_image', __( 'Could not read image size.' ), $this->file ); } if ( function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' ) ) { imagealphablending( $this->image, false ); imagesavealpha( $this->image, true ); } $this->update_size( $size[0], $size[1] ); $this->mime_type = $size['mime']; return $this->set_quality(); } /** * Sets or updates current image size. * * @since 3.5.0 * * @param int $width * @param int $height * @return true */ protected function update_size( $width = false, $height = false ) { if ( ! $width ) { $width = imagesx( $this->image ); } if ( ! $height ) { $height = imagesy( $this->image ); } return parent::update_size( $width, $height ); } /** * Resizes current image. * * Wraps `::_resize()` which returns a GD resource or GdImage instance. * * At minimum, either a height or width must be provided. If one of the two is set * to null, the resize will maintain aspect ratio according to the provided dimension. * * @since 3.5.0 * * @param int|null $max_w Image width. * @param int|null $max_h Image height. * @param bool $crop * @return true|WP_Error */ public function resize( $max_w, $max_h, $crop = false ) { if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) ) { return true; } $resized = $this->_resize( $max_w, $max_h, $crop ); if ( is_gd_image( $resized ) ) { imagedestroy( $this->image ); $this->image = $resized; return true; } elseif ( is_wp_error( $resized ) ) { return $resized; } return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ), $this->file ); } /** * @param int $max_w * @param int $max_h * @param bool|array $crop * @return resource|GdImage|WP_Error */ protected function _resize( $max_w, $max_h, $crop = false ) { $dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop ); if ( ! $dims ) { return new WP_Error( 'error_getting_dimensions', __( 'Could not calculate resized image dimensions' ), $this->file ); } list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims; $resized = wp_imagecreatetruecolor( $dst_w, $dst_h ); imagecopyresampled( $resized, $this->image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ); if ( is_gd_image( $resized ) ) { $this->update_size( $dst_w, $dst_h ); return $resized; } return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ), $this->file ); } /** * 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. * * @since 3.5.0 * * @param array $sizes { * An array of image size data arrays. * * Either a height or width must be provided. * If one of the two is set to null, the resize will * maintain aspect ratio according to the source image. * * @type array ...$0 { * Array of height, width values, and whether to crop. * * @type int $width Image width. Optional if `$height` is specified. * @type int $height Image height. Optional if `$width` is specified. * @type bool $crop Optional. Whether to crop the image. Default false. * } * } * @return array An array of resized images' metadata by size. */ 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; } /** * Create an image sub-size and return the image meta data value for it. * * @since 5.3.0 * * @param array $size_data { * Array of size data. * * @type int $width The maximum width in pixels. * @type int $height The maximum height in pixels. * @type bool $crop Whether to crop the image to exact dimensions. * } * @return array|WP_Error The image data array for inclusion in the `sizes` array in the image meta, * WP_Error object on error. */ public function make_subsize( $size_data ) { if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) { return new WP_Error( 'image_subsize_create_error', __( 'Cannot resize the image. Both width and height are not set.' ) ); } $orig_size = $this->size; if ( ! isset( $size_data['width'] ) ) { $size_data['width'] = null; } if ( ! isset( $size_data['height'] ) ) { $size_data['height'] = null; } if ( ! isset( $size_data['crop'] ) ) { $size_data['crop'] = false; } $resized = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] ); if ( is_wp_error( $resized ) ) { $saved = $resized; } else { $saved = $this->_save( $resized ); imagedestroy( $resized ); } $this->size = $orig_size; if ( ! is_wp_error( $saved ) ) { unset( $saved['path'] ); } return $saved; } /** * Crops Image. * * @since 3.5.0 * * @param int $src_x The start x position to crop from. * @param int $src_y The start y position to crop from. * @param int $src_w The width to crop. * @param int $src_h The height to crop. * @param int $dst_w Optional. The destination width. * @param int $dst_h Optional. The destination height. * @param bool $src_abs Optional. If the source crop points are absolute. * @return true|WP_Error */ public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) { // If destination width/height isn't specified, // use same as width/height from source. if ( ! $dst_w ) { $dst_w = $src_w; } if ( ! $dst_h ) { $dst_h = $src_h; } foreach ( array( $src_w, $src_h, $dst_w, $dst_h ) as $value ) { if ( ! is_numeric( $value ) || (int) $value <= 0 ) { return new WP_Error( 'image_crop_error', __( 'Image crop failed.' ), $this->file ); } } $dst = wp_imagecreatetruecolor( (int) $dst_w, (int) $dst_h ); if ( $src_abs ) { $src_w -= $src_x; $src_h -= $src_y; } if ( function_exists( 'imageantialias' ) ) { imageantialias( $dst, true ); } imagecopyresampled( $dst, $this->image, 0, 0, (int) $src_x, (int) $src_y, (int) $dst_w, (int) $dst_h, (int) $src_w, (int) $src_h ); if ( is_gd_image( $dst ) ) { imagedestroy( $this->image ); $this->image = $dst; $this->update_size(); return true; } return new WP_Error( 'image_crop_error', __( 'Image crop failed.' ), $this->file ); } /** * Rotates current image counter-clockwise by $angle. * Ported from image-edit.php * * @since 3.5.0 * * @param float $angle * @return true|WP_Error */ public function rotate( $angle ) { if ( function_exists( 'imagerotate' ) ) { $transparency = imagecolorallocatealpha( $this->image, 255, 255, 255, 127 ); $rotated = imagerotate( $this->image, $angle, $transparency ); if ( is_gd_image( $rotated ) ) { imagealphablending( $rotated, true ); imagesavealpha( $rotated, true ); imagedestroy( $this->image ); $this->image = $rotated; $this->update_size(); return true; } } return new WP_Error( 'image_rotate_error', __( 'Image rotate failed.' ), $this->file ); } /** * Flips current image. * * @since 3.5.0 * * @param bool $horz Flip along Horizontal Axis. * @param bool $vert Flip along Vertical Axis. * @return true|WP_Error */ public function flip( $horz, $vert ) { $w = $this->size['width']; $h = $this->size['height']; $dst = wp_imagecreatetruecolor( $w, $h ); if ( is_gd_image( $dst ) ) { $sx = $vert ? ( $w - 1 ) : 0; $sy = $horz ? ( $h - 1 ) : 0; $sw = $vert ? -$w : $w; $sh = $horz ? -$h : $h; if ( imagecopyresampled( $dst, $this->image, 0, 0, $sx, $sy, $w, $h, $sw, $sh ) ) { imagedestroy( $this->image ); $this->image = $dst; return true; } } return new WP_Error( 'image_flip_error', __( 'Image flip failed.' ), $this->file ); } /** * Saves current in-memory image to file. * * @since 3.5.0 * @since 5.9.0 Renamed `$filename` to `$destfilename` to match parent class * for PHP 8 named parameter support. * @since 6.0.0 The `$filesize` value was added to the returned array. * * @param string|null $destfilename Optional. Destination filename. Default null. * @param string|null $mime_type Optional. The mime-type. Default null. * @return array|WP_Error { * Array on success or WP_Error if the file failed to save. * * @type string $path Path to the image file. * @type string $file Name of the image file. * @type int $width Image width. * @type int $height Image height. * @type string $mime-type The mime type of the image. * @type int $filesize File size of the image. * } */ public function save( $destfilename = null, $mime_type = null ) { $saved = $this->_save( $this->image, $destfilename, $mime_type ); if ( ! is_wp_error( $saved ) ) { $this->file = $saved['path']; $this->mime_type = $saved['mime-type']; } return $saved; } /** * @since 3.5.0 * @since 6.0.0 The `$filesize` value was added to the returned array. * * @param resource|GdImage $image * @param string|null $filename * @param string|null $mime_type * @return array|WP_Error { * Array on success or WP_Error if the file failed to save. * * @type string $path Path to the image file. * @type string $file Name of the image file. * @type int $width Image width. * @type int $height Image height. * @type string $mime-type The mime type of the image. * @type int $filesize File size of the image. * } */ protected function _save( $image, $filename = null, $mime_type = null ) { list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type ); if ( ! $filename ) { $filename = $this->generate_filename( null, null, $extension ); } if ( 'image/gif' === $mime_type ) { if ( ! $this->make_image( $filename, 'imagegif', array( $image, $filename ) ) ) { return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) ); } } elseif ( 'image/png' === $mime_type ) { // Convert from full colors to index colors, like original PNG. if ( function_exists( 'imageistruecolor' ) && ! imageistruecolor( $image ) ) { imagetruecolortopalette( $image, false, imagecolorstotal( $image ) ); } if ( ! $this->make_image( $filename, 'imagepng', array( $image, $filename ) ) ) { return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) ); } } elseif ( 'image/jpeg' === $mime_type ) { if ( ! $this->make_image( $filename, 'imagejpeg', array( $image, $filename, $this->get_quality() ) ) ) { return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) ); } } elseif ( 'image/webp' == $mime_type ) { if ( ! function_exists( 'imagewebp' ) || ! $this->make_image( $filename, 'imagewebp', array( $image, $filename, $this->get_quality() ) ) ) { return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) ); } } else { return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) ); } // Set correct file permissions. $stat = stat( dirname( $filename ) ); $perms = $stat['mode'] & 0000666; // Same permissions as parent folder, strip off the executable bits. chmod( $filename, $perms ); return array( 'path' => $filename, /** * Filters the name of the saved image file. * * @since 2.6.0 * * @param string $filename Name of the file. */ 'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ), 'width' => $this->size['width'], 'height' => $this->size['height'], 'mime-type' => $mime_type, 'filesize' => wp_filesize( $filename ), ); } /** * Returns stream of current image. * * @since 3.5.0 * * @param string $mime_type The mime type of the image. * @return bool True on success, false on failure. */ public function stream( $mime_type = null ) { list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type ); switch ( $mime_type ) { case 'image/png': header( 'Content-Type: image/png' ); return imagepng( $this->image ); case 'image/gif': header( 'Content-Type: image/gif' ); return imagegif( $this->image ); case 'image/webp': if ( function_exists( 'imagewebp' ) ) { header( 'Content-Type: image/webp' ); return imagewebp( $this->image, null, $this->get_quality() ); } // Fall back to the default if webp isn't supported. default: header( 'Content-Type: image/jpeg' ); return imagejpeg( $this->image, null, $this->get_quality() ); } } /** * Either calls editor's save function or handles file as a stream. * * @since 3.5.0 * * @param string $filename * @param callable $callback * @param array $arguments * @return bool */ protected function make_image( $filename, $callback, $arguments ) { if ( wp_is_stream( $filename ) ) { $arguments[1] = null; } return parent::make_image( $filename, $callback, $arguments ); } } ``` | Uses | Description | | --- | --- | | [WP\_Image\_Editor](wp_image_editor) wp-includes/class-wp-image-editor.php | Base image editor class from which implementations extend | | Version | Description | | --- | --- | | [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Attachments_Controller {} class WP\_REST\_Attachments\_Controller {} ========================================== Core controller used to access attachments via the REST API. * [WP\_REST\_Posts\_Controller](wp_rest_posts_controller) * [check\_upload\_size](wp_rest_attachments_controller/check_upload_size) β€” Determine if uploaded file exceeds space quota on multisite. * [create\_item](wp_rest_attachments_controller/create_item) β€” Creates a single attachment. * [create\_item\_permissions\_check](wp_rest_attachments_controller/create_item_permissions_check) β€” Checks if a given request has access to create an attachment. * [edit\_media\_item](wp_rest_attachments_controller/edit_media_item) β€” Applies edits to a media item and creates a new attachment record. * [edit\_media\_item\_permissions\_check](wp_rest_attachments_controller/edit_media_item_permissions_check) β€” Checks if a given request has access to editing media. * [get\_collection\_params](wp_rest_attachments_controller/get_collection_params) β€” Retrieves the query params for collections of attachments. * [get\_edit\_media\_item\_args](wp_rest_attachments_controller/get_edit_media_item_args) β€” Gets the request args for the edit item route. * [get\_filename\_from\_disposition](wp_rest_attachments_controller/get_filename_from_disposition) β€” Parses filename from a Content-Disposition header value. * [get\_item\_schema](wp_rest_attachments_controller/get_item_schema) β€” Retrieves the attachment's schema, conforming to JSON Schema. * [get\_media\_types](wp_rest_attachments_controller/get_media_types) β€” Retrieves the supported media types. * [insert\_attachment](wp_rest_attachments_controller/insert_attachment) β€” Inserts the attachment post in the database. Does not update the attachment meta. * [post\_process\_item](wp_rest_attachments_controller/post_process_item) β€” Performs post processing on an attachment. * [post\_process\_item\_permissions\_check](wp_rest_attachments_controller/post_process_item_permissions_check) β€” Checks if a given request can perform post processing on an attachment. * [prepare\_item\_for\_database](wp_rest_attachments_controller/prepare_item_for_database) β€” Prepares a single attachment for create or update. * [prepare\_item\_for\_response](wp_rest_attachments_controller/prepare_item_for_response) β€” Prepares a single attachment output for response. * [prepare\_items\_query](wp_rest_attachments_controller/prepare_items_query) β€” Determines the allowed query\_vars for a get\_items() response and prepares for WP\_Query. * [register\_routes](wp_rest_attachments_controller/register_routes) β€” Registers the routes for attachments. * [update\_item](wp_rest_attachments_controller/update_item) β€” Updates a single attachment. * [upload\_from\_data](wp_rest_attachments_controller/upload_from_data) β€” Handles an upload via raw POST data. * [upload\_from\_file](wp_rest_attachments_controller/upload_from_file) β€” Handles an upload via multipart/form-data ($\_FILES). File: `wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php/) ``` class WP_REST_Attachments_Controller extends WP_REST_Posts_Controller { /** * Whether the controller supports batching. * * @since 5.9.0 * @var false */ protected $allow_batch = false; /** * Registers the routes for attachments. * * @since 5.3.0 * * @see register_rest_route() */ public function register_routes() { parent::register_routes(); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)/post-process', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'post_process_item' ), 'permission_callback' => array( $this, 'post_process_item_permissions_check' ), 'args' => array( 'id' => array( 'description' => __( 'Unique identifier for the attachment.' ), 'type' => 'integer', ), 'action' => array( 'type' => 'string', 'enum' => array( 'create-image-subsizes' ), 'required' => true, ), ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)/edit', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'edit_media_item' ), 'permission_callback' => array( $this, 'edit_media_item_permissions_check' ), 'args' => $this->get_edit_media_item_args(), ) ); } /** * Determines the allowed query_vars for a get_items() response and * prepares for WP_Query. * * @since 4.7.0 * * @param array $prepared_args Optional. Array of prepared arguments. Default empty array. * @param WP_REST_Request $request Optional. Request to prepare items for. * @return array Array of query arguments. */ protected function prepare_items_query( $prepared_args = array(), $request = null ) { $query_args = parent::prepare_items_query( $prepared_args, $request ); if ( empty( $query_args['post_status'] ) ) { $query_args['post_status'] = 'inherit'; } $media_types = $this->get_media_types(); if ( ! empty( $request['media_type'] ) && isset( $media_types[ $request['media_type'] ] ) ) { $query_args['post_mime_type'] = $media_types[ $request['media_type'] ]; } if ( ! empty( $request['mime_type'] ) ) { $parts = explode( '/', $request['mime_type'] ); if ( isset( $media_types[ $parts[0] ] ) && in_array( $request['mime_type'], $media_types[ $parts[0] ], true ) ) { $query_args['post_mime_type'] = $request['mime_type']; } } // Filter query clauses to include filenames. if ( isset( $query_args['s'] ) ) { add_filter( 'wp_allow_query_attachment_by_filename', '__return_true' ); } return $query_args; } /** * Checks if a given request has access to create an attachment. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error Boolean true if the attachment may be created, or a WP_Error if not. */ public function create_item_permissions_check( $request ) { $ret = parent::create_item_permissions_check( $request ); if ( ! $ret || is_wp_error( $ret ) ) { return $ret; } if ( ! current_user_can( 'upload_files' ) ) { return new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to upload media on this site.' ), array( 'status' => 400 ) ); } // Attaching media to a post requires ability to edit said post. if ( ! empty( $request['post'] ) && ! current_user_can( 'edit_post', (int) $request['post'] ) ) { return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to upload media to this post.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Creates a single attachment. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure. */ public function create_item( $request ) { if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) { return new WP_Error( 'rest_invalid_param', __( 'Invalid parent type.' ), array( 'status' => 400 ) ); } $insert = $this->insert_attachment( $request ); if ( is_wp_error( $insert ) ) { return $insert; } $schema = $this->get_item_schema(); // Extract by name. $attachment_id = $insert['attachment_id']; $file = $insert['file']; if ( isset( $request['alt_text'] ) ) { update_post_meta( $attachment_id, '_wp_attachment_image_alt', sanitize_text_field( $request['alt_text'] ) ); } if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { $meta_update = $this->meta->update_value( $request['meta'], $attachment_id ); if ( is_wp_error( $meta_update ) ) { return $meta_update; } } $attachment = get_post( $attachment_id ); $fields_update = $this->update_additional_fields_for_object( $attachment, $request ); if ( is_wp_error( $fields_update ) ) { return $fields_update; } $request->set_param( 'context', 'edit' ); /** * Fires after a single attachment is completely created or updated via the REST API. * * @since 5.0.0 * * @param WP_Post $attachment Inserted or updated attachment object. * @param WP_REST_Request $request Request object. * @param bool $creating True when creating an attachment, false when updating. */ do_action( 'rest_after_insert_attachment', $attachment, $request, true ); wp_after_insert_post( $attachment, false, null ); if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) { // Set a custom header with the attachment_id. // Used by the browser/client to resume creating image sub-sizes after a PHP fatal error. header( 'X-WP-Upload-Attachment-ID: ' . $attachment_id ); } // Include media and image functions to get access to wp_generate_attachment_metadata(). require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; // Post-process the upload (create image sub-sizes, make PDF thumbnails, etc.) and insert attachment meta. // At this point the server may run out of resources and post-processing of uploaded images may fail. wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) ); $response = $this->prepare_item_for_response( $attachment, $request ); $response = rest_ensure_response( $response ); $response->set_status( 201 ); $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $attachment_id ) ) ); return $response; } /** * Inserts the attachment post in the database. Does not update the attachment meta. * * @since 5.3.0 * * @param WP_REST_Request $request * @return array|WP_Error */ protected function insert_attachment( $request ) { // Get the file via $_FILES or raw data. $files = $request->get_file_params(); $headers = $request->get_headers(); if ( ! empty( $files ) ) { $file = $this->upload_from_file( $files, $headers ); } else { $file = $this->upload_from_data( $request->get_body(), $headers ); } if ( is_wp_error( $file ) ) { return $file; } $name = wp_basename( $file['file'] ); $name_parts = pathinfo( $name ); $name = trim( substr( $name, 0, -( 1 + strlen( $name_parts['extension'] ) ) ) ); $url = $file['url']; $type = $file['type']; $file = $file['file']; // Include image functions to get access to wp_read_image_metadata(). require_once ABSPATH . 'wp-admin/includes/image.php'; // Use image exif/iptc data for title and caption defaults if possible. $image_meta = wp_read_image_metadata( $file ); if ( ! empty( $image_meta ) ) { if ( empty( $request['title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) { $request['title'] = $image_meta['title']; } if ( empty( $request['caption'] ) && trim( $image_meta['caption'] ) ) { $request['caption'] = $image_meta['caption']; } } $attachment = $this->prepare_item_for_database( $request ); $attachment->post_mime_type = $type; $attachment->guid = $url; if ( empty( $attachment->post_title ) ) { $attachment->post_title = preg_replace( '/\.[^.]+$/', '', wp_basename( $file ) ); } // $post_parent is inherited from $attachment['post_parent']. $id = wp_insert_attachment( wp_slash( (array) $attachment ), $file, 0, true, false ); if ( is_wp_error( $id ) ) { if ( 'db_update_error' === $id->get_error_code() ) { $id->add_data( array( 'status' => 500 ) ); } else { $id->add_data( array( 'status' => 400 ) ); } return $id; } $attachment = get_post( $id ); /** * Fires after a single attachment is created or updated via the REST API. * * @since 4.7.0 * * @param WP_Post $attachment Inserted or updated attachment * object. * @param WP_REST_Request $request The request sent to the API. * @param bool $creating True when creating an attachment, false when updating. */ do_action( 'rest_insert_attachment', $attachment, $request, true ); return array( 'attachment_id' => $id, 'file' => $file, ); } /** * Updates a single attachment. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure. */ public function update_item( $request ) { if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) { return new WP_Error( 'rest_invalid_param', __( 'Invalid parent type.' ), array( 'status' => 400 ) ); } $attachment_before = get_post( $request['id'] ); $response = parent::update_item( $request ); if ( is_wp_error( $response ) ) { return $response; } $response = rest_ensure_response( $response ); $data = $response->get_data(); if ( isset( $request['alt_text'] ) ) { update_post_meta( $data['id'], '_wp_attachment_image_alt', $request['alt_text'] ); } $attachment = get_post( $request['id'] ); $fields_update = $this->update_additional_fields_for_object( $attachment, $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-attachments-controller.php */ do_action( 'rest_after_insert_attachment', $attachment, $request, false ); wp_after_insert_post( $attachment, true, $attachment_before ); $response = $this->prepare_item_for_response( $attachment, $request ); $response = rest_ensure_response( $response ); return $response; } /** * Performs post processing on an attachment. * * @since 5.3.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure. */ public function post_process_item( $request ) { switch ( $request['action'] ) { case 'create-image-subsizes': require_once ABSPATH . 'wp-admin/includes/image.php'; wp_update_image_subsizes( $request['id'] ); break; } $request['context'] = 'edit'; return $this->prepare_item_for_response( get_post( $request['id'] ), $request ); } /** * Checks if a given request can perform post processing on an attachment. * * @since 5.3.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to update the item, WP_Error object otherwise. */ public function post_process_item_permissions_check( $request ) { return $this->update_item_permissions_check( $request ); } /** * Checks if a given request has access to editing media. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function edit_media_item_permissions_check( $request ) { if ( ! current_user_can( 'upload_files' ) ) { return new WP_Error( 'rest_cannot_edit_image', __( 'Sorry, you are not allowed to upload media on this site.' ), array( 'status' => rest_authorization_required_code() ) ); } return $this->update_item_permissions_check( $request ); } /** * Applies edits to a media item and creates a new attachment record. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure. */ public function edit_media_item( $request ) { require_once ABSPATH . 'wp-admin/includes/image.php'; $attachment_id = $request['id']; // This also confirms the attachment is an image. $image_file = wp_get_original_image_path( $attachment_id ); $image_meta = wp_get_attachment_metadata( $attachment_id ); if ( ! $image_meta || ! $image_file || ! wp_image_file_matches_image_meta( $request['src'], $image_meta, $attachment_id ) ) { return new WP_Error( 'rest_unknown_attachment', __( 'Unable to get meta information for file.' ), array( 'status' => 404 ) ); } $supported_types = array( 'image/jpeg', 'image/png', 'image/gif', 'image/webp' ); $mime_type = get_post_mime_type( $attachment_id ); if ( ! in_array( $mime_type, $supported_types, true ) ) { return new WP_Error( 'rest_cannot_edit_file_type', __( 'This type of file cannot be edited.' ), array( 'status' => 400 ) ); } // The `modifiers` param takes precedence over the older format. if ( isset( $request['modifiers'] ) ) { $modifiers = $request['modifiers']; } else { $modifiers = array(); if ( ! empty( $request['rotation'] ) ) { $modifiers[] = array( 'type' => 'rotate', 'args' => array( 'angle' => $request['rotation'], ), ); } if ( isset( $request['x'], $request['y'], $request['width'], $request['height'] ) ) { $modifiers[] = array( 'type' => 'crop', 'args' => array( 'left' => $request['x'], 'top' => $request['y'], 'width' => $request['width'], 'height' => $request['height'], ), ); } if ( 0 === count( $modifiers ) ) { return new WP_Error( 'rest_image_not_edited', __( 'The image was not edited. Edit the image before applying the changes.' ), array( 'status' => 400 ) ); } } /* * If the file doesn't exist, attempt a URL fopen on the src link. * This can occur with certain file replication plugins. * Keep the original file path to get a modified name later. */ $image_file_to_edit = $image_file; if ( ! file_exists( $image_file_to_edit ) ) { $image_file_to_edit = _load_image_to_edit_path( $attachment_id ); } $image_editor = wp_get_image_editor( $image_file_to_edit ); if ( is_wp_error( $image_editor ) ) { return new WP_Error( 'rest_unknown_image_file_type', __( 'Unable to edit this image.' ), array( 'status' => 500 ) ); } foreach ( $modifiers as $modifier ) { $args = $modifier['args']; switch ( $modifier['type'] ) { case 'rotate': // Rotation direction: clockwise vs. counter clockwise. $rotate = 0 - $args['angle']; if ( 0 !== $rotate ) { $result = $image_editor->rotate( $rotate ); if ( is_wp_error( $result ) ) { return new WP_Error( 'rest_image_rotation_failed', __( 'Unable to rotate this image.' ), array( 'status' => 500 ) ); } } break; case 'crop': $size = $image_editor->get_size(); $crop_x = round( ( $size['width'] * $args['left'] ) / 100.0 ); $crop_y = round( ( $size['height'] * $args['top'] ) / 100.0 ); $width = round( ( $size['width'] * $args['width'] ) / 100.0 ); $height = round( ( $size['height'] * $args['height'] ) / 100.0 ); if ( $size['width'] !== $width && $size['height'] !== $height ) { $result = $image_editor->crop( $crop_x, $crop_y, $width, $height ); if ( is_wp_error( $result ) ) { return new WP_Error( 'rest_image_crop_failed', __( 'Unable to crop this image.' ), array( 'status' => 500 ) ); } } break; } } // Calculate the file name. $image_ext = pathinfo( $image_file, PATHINFO_EXTENSION ); $image_name = wp_basename( $image_file, ".{$image_ext}" ); // Do not append multiple `-edited` to the file name. // The user may be editing a previously edited image. if ( preg_match( '/-edited(-\d+)?$/', $image_name ) ) { // Remove any `-1`, `-2`, etc. `wp_unique_filename()` will add the proper number. $image_name = preg_replace( '/-edited(-\d+)?$/', '-edited', $image_name ); } else { // Append `-edited` before the extension. $image_name .= '-edited'; } $filename = "{$image_name}.{$image_ext}"; // Create the uploads sub-directory if needed. $uploads = wp_upload_dir(); // Make the file name unique in the (new) upload directory. $filename = wp_unique_filename( $uploads['path'], $filename ); // Save to disk. $saved = $image_editor->save( $uploads['path'] . "/$filename" ); if ( is_wp_error( $saved ) ) { return $saved; } // Create new attachment post. $new_attachment_post = array( 'post_mime_type' => $saved['mime-type'], 'guid' => $uploads['url'] . "/$filename", 'post_title' => $image_name, 'post_content' => '', ); // Copy post_content, post_excerpt, and post_title from the edited image's attachment post. $attachment_post = get_post( $attachment_id ); if ( $attachment_post ) { $new_attachment_post['post_content'] = $attachment_post->post_content; $new_attachment_post['post_excerpt'] = $attachment_post->post_excerpt; $new_attachment_post['post_title'] = $attachment_post->post_title; } $new_attachment_id = wp_insert_attachment( wp_slash( $new_attachment_post ), $saved['path'], 0, true ); if ( is_wp_error( $new_attachment_id ) ) { if ( 'db_update_error' === $new_attachment_id->get_error_code() ) { $new_attachment_id->add_data( array( 'status' => 500 ) ); } else { $new_attachment_id->add_data( array( 'status' => 400 ) ); } return $new_attachment_id; } // Copy the image alt text from the edited image. $image_alt = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ); if ( ! empty( $image_alt ) ) { // update_post_meta() expects slashed. update_post_meta( $new_attachment_id, '_wp_attachment_image_alt', wp_slash( $image_alt ) ); } if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) { // Set a custom header with the attachment_id. // Used by the browser/client to resume creating image sub-sizes after a PHP fatal error. header( 'X-WP-Upload-Attachment-ID: ' . $new_attachment_id ); } // Generate image sub-sizes and meta. $new_image_meta = wp_generate_attachment_metadata( $new_attachment_id, $saved['path'] ); // Copy the EXIF metadata from the original attachment if not generated for the edited image. if ( isset( $image_meta['image_meta'] ) && isset( $new_image_meta['image_meta'] ) && is_array( $new_image_meta['image_meta'] ) ) { // Merge but skip empty values. foreach ( (array) $image_meta['image_meta'] as $key => $value ) { if ( empty( $new_image_meta['image_meta'][ $key ] ) && ! empty( $value ) ) { $new_image_meta['image_meta'][ $key ] = $value; } } } // Reset orientation. At this point the image is edited and orientation is correct. if ( ! empty( $new_image_meta['image_meta']['orientation'] ) ) { $new_image_meta['image_meta']['orientation'] = 1; } // The attachment_id may change if the site is exported and imported. $new_image_meta['parent_image'] = array( 'attachment_id' => $attachment_id, // Path to the originally uploaded image file relative to the uploads directory. 'file' => _wp_relative_upload_path( $image_file ), ); /** * Filters the meta data for the new image created by editing an existing image. * * @since 5.5.0 * * @param array $new_image_meta Meta data for the new image. * @param int $new_attachment_id Attachment post ID for the new image. * @param int $attachment_id Attachment post ID for the edited (parent) image. */ $new_image_meta = apply_filters( 'wp_edited_image_metadata', $new_image_meta, $new_attachment_id, $attachment_id ); wp_update_attachment_metadata( $new_attachment_id, $new_image_meta ); $response = $this->prepare_item_for_response( get_post( $new_attachment_id ), $request ); $response->set_status( 201 ); $response->header( 'Location', rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $new_attachment_id ) ) ); return $response; } /** * Prepares a single attachment for create or update. * * @since 4.7.0 * * @param WP_REST_Request $request Request object. * @return stdClass|WP_Error Post object. */ protected function prepare_item_for_database( $request ) { $prepared_attachment = parent::prepare_item_for_database( $request ); // Attachment caption (post_excerpt internally). if ( isset( $request['caption'] ) ) { if ( is_string( $request['caption'] ) ) { $prepared_attachment->post_excerpt = $request['caption']; } elseif ( isset( $request['caption']['raw'] ) ) { $prepared_attachment->post_excerpt = $request['caption']['raw']; } } // Attachment description (post_content internally). if ( isset( $request['description'] ) ) { if ( is_string( $request['description'] ) ) { $prepared_attachment->post_content = $request['description']; } elseif ( isset( $request['description']['raw'] ) ) { $prepared_attachment->post_content = $request['description']['raw']; } } if ( isset( $request['post'] ) ) { $prepared_attachment->post_parent = (int) $request['post']; } return $prepared_attachment; } /** * Prepares a single attachment output for response. * * @since 4.7.0 * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Post $item Attachment object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $post = $item; $response = parent::prepare_item_for_response( $post, $request ); $fields = $this->get_fields_for_response( $request ); $data = $response->get_data(); if ( in_array( 'description', $fields, true ) ) { $data['description'] = array( 'raw' => $post->post_content, /** This filter is documented in wp-includes/post-template.php */ 'rendered' => apply_filters( 'the_content', $post->post_content ), ); } if ( in_array( 'caption', $fields, true ) ) { /** This filter is documented in wp-includes/post-template.php */ $caption = apply_filters( 'get_the_excerpt', $post->post_excerpt, $post ); /** This filter is documented in wp-includes/post-template.php */ $caption = apply_filters( 'the_excerpt', $caption ); $data['caption'] = array( 'raw' => $post->post_excerpt, 'rendered' => $caption, ); } if ( in_array( 'alt_text', $fields, true ) ) { $data['alt_text'] = get_post_meta( $post->ID, '_wp_attachment_image_alt', true ); } if ( in_array( 'media_type', $fields, true ) ) { $data['media_type'] = wp_attachment_is_image( $post->ID ) ? 'image' : 'file'; } if ( in_array( 'mime_type', $fields, true ) ) { $data['mime_type'] = $post->post_mime_type; } if ( in_array( 'media_details', $fields, true ) ) { $data['media_details'] = wp_get_attachment_metadata( $post->ID ); // Ensure empty details is an empty object. if ( empty( $data['media_details'] ) ) { $data['media_details'] = new stdClass; } elseif ( ! empty( $data['media_details']['sizes'] ) ) { foreach ( $data['media_details']['sizes'] as $size => &$size_data ) { if ( isset( $size_data['mime-type'] ) ) { $size_data['mime_type'] = $size_data['mime-type']; unset( $size_data['mime-type'] ); } // Use the same method image_downsize() does. $image_src = wp_get_attachment_image_src( $post->ID, $size ); if ( ! $image_src ) { continue; } $size_data['source_url'] = $image_src[0]; } $full_src = wp_get_attachment_image_src( $post->ID, 'full' ); if ( ! empty( $full_src ) ) { $data['media_details']['sizes']['full'] = array( 'file' => wp_basename( $full_src[0] ), 'width' => $full_src[1], 'height' => $full_src[2], 'mime_type' => $post->post_mime_type, 'source_url' => $full_src[0], ); } } else { $data['media_details']['sizes'] = new stdClass; } } if ( in_array( 'post', $fields, true ) ) { $data['post'] = ! empty( $post->post_parent ) ? (int) $post->post_parent : null; } if ( in_array( 'source_url', $fields, true ) ) { $data['source_url'] = wp_get_attachment_url( $post->ID ); } if ( in_array( 'missing_image_sizes', $fields, true ) ) { require_once ABSPATH . 'wp-admin/includes/image.php'; $data['missing_image_sizes'] = array_keys( wp_get_missing_image_subsizes( $post->ID ) ); } $context = ! empty( $request['context'] ) ? $request['context'] : 'view'; $data = $this->filter_response_by_context( $data, $context ); $links = $response->get_links(); // Wrap the data in a response object. $response = rest_ensure_response( $data ); foreach ( $links as $rel => $rel_links ) { foreach ( $rel_links as $link ) { $response->add_link( $rel, $link['href'], $link['attributes'] ); } } /** * Filters an attachment returned from the REST API. * * Allows modification of the attachment right before it is returned. * * @since 4.7.0 * * @param WP_REST_Response $response The response object. * @param WP_Post $post The original attachment post. * @param WP_REST_Request $request Request used to generate the response. */ return apply_filters( 'rest_prepare_attachment', $response, $post, $request ); } /** * Retrieves the attachment's schema, conforming to JSON Schema. * * @since 4.7.0 * * @return array Item schema as an array. */ public function get_item_schema() { if ( $this->schema ) { return $this->add_additional_fields_schema( $this->schema ); } $schema = parent::get_item_schema(); $schema['properties']['alt_text'] = array( 'description' => __( 'Alternative text to display when attachment is not displayed.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ); $schema['properties']['caption'] = array( 'description' => __( 'The attachment caption.' ), 'type' => 'object', 'context' => array( 'view', 'edit', 'embed' ), 'arg_options' => array( 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database(). 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database(). ), 'properties' => array( 'raw' => array( 'description' => __( 'Caption for the attachment, as it exists in the database.' ), 'type' => 'string', 'context' => array( 'edit' ), ), 'rendered' => array( 'description' => __( 'HTML caption for the attachment, transformed for display.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), ), ); $schema['properties']['description'] = array( 'description' => __( 'The attachment description.' ), 'type' => 'object', 'context' => array( 'view', 'edit' ), 'arg_options' => array( 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database(). 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database(). ), 'properties' => array( 'raw' => array( 'description' => __( 'Description for the attachment, as it exists in the database.' ), 'type' => 'string', 'context' => array( 'edit' ), ), 'rendered' => array( 'description' => __( 'HTML description for the attachment, transformed for display.' ), 'type' => 'string', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), ), ); $schema['properties']['media_type'] = array( 'description' => __( 'Attachment type.' ), 'type' => 'string', 'enum' => array( 'image', 'file' ), 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ); $schema['properties']['mime_type'] = array( 'description' => __( 'The attachment MIME type.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ); $schema['properties']['media_details'] = array( 'description' => __( 'Details about the media file, specific to its type.' ), 'type' => 'object', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ); $schema['properties']['post'] = array( 'description' => __( 'The ID for the associated post of the attachment.' ), 'type' => 'integer', 'context' => array( 'view', 'edit' ), ); $schema['properties']['source_url'] = array( 'description' => __( 'URL to the original attachment file.' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ); $schema['properties']['missing_image_sizes'] = array( 'description' => __( 'List of the missing image sizes of the attachment.' ), 'type' => 'array', 'items' => array( 'type' => 'string' ), 'context' => array( 'edit' ), 'readonly' => true, ); unset( $schema['properties']['password'] ); $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * Handles an upload via raw POST data. * * @since 4.7.0 * * @param array $data Supplied file data. * @param array $headers HTTP headers from the request. * @return array|WP_Error Data from wp_handle_sideload(). */ protected function upload_from_data( $data, $headers ) { if ( empty( $data ) ) { return new WP_Error( 'rest_upload_no_data', __( 'No data supplied.' ), array( 'status' => 400 ) ); } if ( empty( $headers['content_type'] ) ) { return new WP_Error( 'rest_upload_no_content_type', __( 'No Content-Type supplied.' ), array( 'status' => 400 ) ); } if ( empty( $headers['content_disposition'] ) ) { return new WP_Error( 'rest_upload_no_content_disposition', __( 'No Content-Disposition supplied.' ), array( 'status' => 400 ) ); } $filename = self::get_filename_from_disposition( $headers['content_disposition'] ); if ( empty( $filename ) ) { return new WP_Error( 'rest_upload_invalid_disposition', __( 'Invalid Content-Disposition supplied. Content-Disposition needs to be formatted as `attachment; filename="image.png"` or similar.' ), array( 'status' => 400 ) ); } if ( ! empty( $headers['content_md5'] ) ) { $content_md5 = array_shift( $headers['content_md5'] ); $expected = trim( $content_md5 ); $actual = md5( $data ); if ( $expected !== $actual ) { return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) ); } } // Get the content-type. $type = array_shift( $headers['content_type'] ); // Include filesystem functions to get access to wp_tempnam() and wp_handle_sideload(). require_once ABSPATH . 'wp-admin/includes/file.php'; // Save the file. $tmpfname = wp_tempnam( $filename ); $fp = fopen( $tmpfname, 'w+' ); if ( ! $fp ) { return new WP_Error( 'rest_upload_file_error', __( 'Could not open file handle.' ), array( 'status' => 500 ) ); } fwrite( $fp, $data ); fclose( $fp ); // Now, sideload it in. $file_data = array( 'error' => null, 'tmp_name' => $tmpfname, 'name' => $filename, 'type' => $type, ); $size_check = self::check_upload_size( $file_data ); if ( is_wp_error( $size_check ) ) { return $size_check; } $overrides = array( 'test_form' => false, ); $sideloaded = wp_handle_sideload( $file_data, $overrides ); if ( isset( $sideloaded['error'] ) ) { @unlink( $tmpfname ); return new WP_Error( 'rest_upload_sideload_error', $sideloaded['error'], array( 'status' => 500 ) ); } return $sideloaded; } /** * Parses filename from a Content-Disposition header value. * * As per RFC6266: * * content-disposition = "Content-Disposition" ":" * disposition-type *( ";" disposition-parm ) * * disposition-type = "inline" | "attachment" | disp-ext-type * ; case-insensitive * disp-ext-type = token * * disposition-parm = filename-parm | disp-ext-parm * * filename-parm = "filename" "=" value * | "filename*" "=" ext-value * * disp-ext-parm = token "=" value * | ext-token "=" ext-value * ext-token = <the characters in token, followed by "*"> * * @since 4.7.0 * * @link https://tools.ietf.org/html/rfc2388 * @link https://tools.ietf.org/html/rfc6266 * * @param string[] $disposition_header List of Content-Disposition header values. * @return string|null Filename if available, or null if not found. */ public static function get_filename_from_disposition( $disposition_header ) { // Get the filename. $filename = null; foreach ( $disposition_header as $value ) { $value = trim( $value ); if ( strpos( $value, ';' ) === false ) { continue; } list( $type, $attr_parts ) = explode( ';', $value, 2 ); $attr_parts = explode( ';', $attr_parts ); $attributes = array(); foreach ( $attr_parts as $part ) { if ( strpos( $part, '=' ) === false ) { continue; } list( $key, $value ) = explode( '=', $part, 2 ); $attributes[ trim( $key ) ] = trim( $value ); } if ( empty( $attributes['filename'] ) ) { continue; } $filename = trim( $attributes['filename'] ); // Unquote quoted filename, but after trimming. if ( substr( $filename, 0, 1 ) === '"' && substr( $filename, -1, 1 ) === '"' ) { $filename = substr( $filename, 1, -1 ); } } return $filename; } /** * Retrieves the query params for collections of attachments. * * @since 4.7.0 * * @return array Query parameters for the attachment collection as an array. */ public function get_collection_params() { $params = parent::get_collection_params(); $params['status']['default'] = 'inherit'; $params['status']['items']['enum'] = array( 'inherit', 'private', 'trash' ); $media_types = $this->get_media_types(); $params['media_type'] = array( 'default' => null, 'description' => __( 'Limit result set to attachments of a particular media type.' ), 'type' => 'string', 'enum' => array_keys( $media_types ), ); $params['mime_type'] = array( 'default' => null, 'description' => __( 'Limit result set to attachments of a particular MIME type.' ), 'type' => 'string', ); return $params; } /** * Handles an upload via multipart/form-data ($_FILES). * * @since 4.7.0 * * @param array $files Data from the `$_FILES` superglobal. * @param array $headers HTTP headers from the request. * @return array|WP_Error Data from wp_handle_upload(). */ protected function upload_from_file( $files, $headers ) { if ( empty( $files ) ) { return new WP_Error( 'rest_upload_no_data', __( 'No data supplied.' ), array( 'status' => 400 ) ); } // Verify hash, if given. if ( ! empty( $headers['content_md5'] ) ) { $content_md5 = array_shift( $headers['content_md5'] ); $expected = trim( $content_md5 ); $actual = md5_file( $files['file']['tmp_name'] ); if ( $expected !== $actual ) { return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) ); } } // Pass off to WP to handle the actual upload. $overrides = array( 'test_form' => false, ); // Bypasses is_uploaded_file() when running unit tests. if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) { $overrides['action'] = 'wp_handle_mock_upload'; } $size_check = self::check_upload_size( $files['file'] ); if ( is_wp_error( $size_check ) ) { return $size_check; } // Include filesystem functions to get access to wp_handle_upload(). require_once ABSPATH . 'wp-admin/includes/file.php'; $file = wp_handle_upload( $files['file'], $overrides ); if ( isset( $file['error'] ) ) { return new WP_Error( 'rest_upload_unknown_error', $file['error'], array( 'status' => 500 ) ); } return $file; } /** * Retrieves the supported media types. * * Media types are considered the MIME type category. * * @since 4.7.0 * * @return array Array of supported media types. */ protected function get_media_types() { $media_types = array(); foreach ( get_allowed_mime_types() as $mime_type ) { $parts = explode( '/', $mime_type ); if ( ! isset( $media_types[ $parts[0] ] ) ) { $media_types[ $parts[0] ] = array(); } $media_types[ $parts[0] ][] = $mime_type; } return $media_types; } /** * Determine if uploaded file exceeds space quota on multisite. * * Replicates check_upload_size(). * * @since 4.9.8 * * @param array $file $_FILES array for a given file. * @return true|WP_Error True if can upload, error for errors. */ protected function check_upload_size( $file ) { if ( ! is_multisite() ) { return true; } if ( get_site_option( 'upload_space_check_disabled' ) ) { return true; } $space_left = get_upload_space_available(); $file_size = filesize( $file['tmp_name'] ); if ( $space_left < $file_size ) { return new WP_Error( 'rest_upload_limited_space', /* translators: %s: Required disk space in kilobytes. */ sprintf( __( 'Not enough space to upload. %s KB needed.' ), number_format( ( $file_size - $space_left ) / KB_IN_BYTES ) ), array( 'status' => 400 ) ); } if ( $file_size > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) { return new WP_Error( 'rest_upload_file_too_big', /* translators: %s: Maximum allowed file size in kilobytes. */ sprintf( __( 'This file is too big. Files must be less than %s KB in size.' ), get_site_option( 'fileupload_maxk', 1500 ) ), array( 'status' => 400 ) ); } // Include multisite admin functions to get access to upload_is_user_over_quota(). require_once ABSPATH . 'wp-admin/includes/ms.php'; if ( upload_is_user_over_quota( false ) ) { return new WP_Error( 'rest_upload_user_quota_exceeded', __( 'You have used your space quota. Please delete files before uploading.' ), array( 'status' => 400 ) ); } return true; } /** * Gets the request args for the edit item route. * * @since 5.5.0 * * @return array */ protected function get_edit_media_item_args() { return array( 'src' => array( 'description' => __( 'URL to the edited image file.' ), 'type' => 'string', 'format' => 'uri', 'required' => true, ), 'modifiers' => array( 'description' => __( 'Array of image edits.' ), 'type' => 'array', 'minItems' => 1, 'items' => array( 'description' => __( 'Image edit.' ), 'type' => 'object', 'required' => array( 'type', 'args', ), 'oneOf' => array( array( 'title' => __( 'Rotation' ), 'properties' => array( 'type' => array( 'description' => __( 'Rotation type.' ), 'type' => 'string', 'enum' => array( 'rotate' ), ), 'args' => array( 'description' => __( 'Rotation arguments.' ), 'type' => 'object', 'required' => array( 'angle', ), 'properties' => array( 'angle' => array( 'description' => __( 'Angle to rotate clockwise in degrees.' ), 'type' => 'number', ), ), ), ), ), array( 'title' => __( 'Crop' ), 'properties' => array( 'type' => array( 'description' => __( 'Crop type.' ), 'type' => 'string', 'enum' => array( 'crop' ), ), 'args' => array( 'description' => __( 'Crop arguments.' ), 'type' => 'object', 'required' => array( 'left', 'top', 'width', 'height', ), 'properties' => array( 'left' => array( 'description' => __( 'Horizontal position from the left to begin the crop as a percentage of the image width.' ), 'type' => 'number', ), 'top' => array( 'description' => __( 'Vertical position from the top to begin the crop as a percentage of the image height.' ), 'type' => 'number', ), 'width' => array( 'description' => __( 'Width of the crop as a percentage of the image width.' ), 'type' => 'number', ), 'height' => array( 'description' => __( 'Height of the crop as a percentage of the image height.' ), 'type' => 'number', ), ), ), ), ), ), ), ), 'rotation' => array( 'description' => __( 'The amount to rotate the image clockwise in degrees. DEPRECATED: Use `modifiers` instead.' ), 'type' => 'integer', 'minimum' => 0, 'exclusiveMinimum' => true, 'maximum' => 360, 'exclusiveMaximum' => true, ), 'x' => array( 'description' => __( 'As a percentage of the image, the x position to start the crop from. DEPRECATED: Use `modifiers` instead.' ), 'type' => 'number', 'minimum' => 0, 'maximum' => 100, ), 'y' => array( 'description' => __( 'As a percentage of the image, the y position to start the crop from. DEPRECATED: Use `modifiers` instead.' ), 'type' => 'number', 'minimum' => 0, 'maximum' => 100, ), 'width' => array( 'description' => __( 'As a percentage of the image, the width to crop the image to. DEPRECATED: Use `modifiers` instead.' ), 'type' => 'number', 'minimum' => 0, 'maximum' => 100, ), 'height' => array( 'description' => __( 'As a percentage of the image, the height to crop the image to. DEPRECATED: Use `modifiers` instead.' ), 'type' => 'number', 'minimum' => 0, 'maximum' => 100, ), ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Posts\_Controller](wp_rest_posts_controller) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Core class to access posts via the REST API. | | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
programming_docs
wordpress class Requests_Exception_HTTP_410 {} class Requests\_Exception\_HTTP\_410 {} ======================================= Exception for 410 Gone responses File: `wp-includes/Requests/Exception/HTTP/410.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/410.php/) ``` class Requests_Exception_HTTP_410 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 410; /** * Reason phrase * * @var string */ protected $reason = 'Gone'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class RSSCache {} class RSSCache {} ================= * [\_\_construct](rsscache/__construct) β€” PHP5 constructor. * [check\_cache](rsscache/check_cache) * [debug](rsscache/debug) * [error](rsscache/error) * [file\_name](rsscache/file_name) * [get](rsscache/get) * [RSSCache](rsscache/rsscache) β€” PHP4 constructor. * [serialize](rsscache/serialize) * [set](rsscache/set) * [unserialize](rsscache/unserialize) File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/) ``` class RSSCache { var $BASE_CACHE; // where the cache files are stored var $MAX_AGE = 43200; // when are files stale, default twelve hours var $ERROR = ''; // accumulate error messages /** * PHP5 constructor. */ function __construct( $base = '', $age = '' ) { $this->BASE_CACHE = WP_CONTENT_DIR . '/cache'; if ( $base ) { $this->BASE_CACHE = $base; } if ( $age ) { $this->MAX_AGE = $age; } } /** * PHP4 constructor. */ public function RSSCache( $base = '', $age = '' ) { self::__construct( $base, $age ); } /*=======================================================================*\ Function: set Purpose: add an item to the cache, keyed on url Input: url from which the rss file was fetched Output: true on success \*=======================================================================*/ function set ($url, $rss) { $cache_option = 'rss_' . $this->file_name( $url ); set_transient($cache_option, $rss, $this->MAX_AGE); return $cache_option; } /*=======================================================================*\ Function: get Purpose: fetch an item from the cache Input: url from which the rss file was fetched Output: cached object on HIT, false on MISS \*=======================================================================*/ 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; } /*=======================================================================*\ Function: check_cache Purpose: check a url for membership in the cache and whether the object is older then MAX_AGE (ie. STALE) Input: url from which the rss file was fetched Output: cached object on HIT, false on MISS \*=======================================================================*/ 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'; } } /*=======================================================================*\ Function: serialize \*=======================================================================*/ function serialize ( $rss ) { return serialize( $rss ); } /*=======================================================================*\ Function: unserialize \*=======================================================================*/ function unserialize ( $data ) { return unserialize( $data ); } /*=======================================================================*\ Function: file_name Purpose: map url to location in cache Input: url from which the rss file was fetched Output: a file name \*=======================================================================*/ function file_name ($url) { return md5( $url ); } /*=======================================================================*\ Function: error Purpose: register error \*=======================================================================*/ function error ($errormsg, $lvl=E_USER_WARNING) { $this->ERROR = $errormsg; if ( MAGPIE_DEBUG ) { trigger_error( $errormsg, $lvl); } else { error_log( $errormsg, 0); } } function debug ($debugmsg, $lvl=E_USER_NOTICE) { if ( MAGPIE_DEBUG ) { $this->error("MagpieRSS [debug] $debugmsg", $lvl); } } } ``` wordpress class WP_REST_Edit_Site_Export_Controller {} class WP\_REST\_Edit\_Site\_Export\_Controller {} ================================================= Controller which provides REST endpoint for exporting current templates and template parts. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_edit_site_export_controller/__construct) β€” Constructor. * [export](wp_rest_edit_site_export_controller/export) β€” Output a ZIP file with an export of the current templates and template parts from the site editor, and close the connection. * [permissions\_check](wp_rest_edit_site_export_controller/permissions_check) β€” Checks whether a given request has permission to export. * [register\_routes](wp_rest_edit_site_export_controller/register_routes) β€” Registers the site export route. File: `wp-includes/rest-api/endpoints/class-wp-rest-edit-site-export-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-edit-site-export-controller.php/) ``` class WP_REST_Edit_Site_Export_Controller extends WP_REST_Controller { /** * Constructor. * * @since 5.9.0 */ public function __construct() { $this->namespace = 'wp-block-editor/v1'; $this->rest_base = 'export'; } /** * Registers the site export route. * * @since 5.9.0 */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'export' ), 'permission_callback' => array( $this, 'permissions_check' ), ), ) ); } /** * Checks whether a given request has permission to export. * * @since 5.9.0 * * @return WP_Error|true True if the request has access, or WP_Error object. */ public function permissions_check() { if ( current_user_can( 'edit_theme_options' ) ) { return true; } return new WP_Error( 'rest_cannot_export_templates', __( 'Sorry, you are not allowed to export templates and template parts.' ), array( 'status' => rest_authorization_required_code() ) ); } /** * Output a ZIP file with an export of the current templates * and template parts from the site editor, and close the connection. * * @since 5.9.0 * * @return WP_Error|void */ public function export() { // Generate the export file. $filename = wp_generate_block_templates_export_file(); if ( is_wp_error( $filename ) ) { $filename->add_data( array( 'status' => 500 ) ); return $filename; } $theme_name = basename( get_stylesheet() ); header( 'Content-Type: application/zip' ); header( 'Content-Disposition: attachment; filename=' . $theme_name . '.zip' ); header( 'Content-Length: ' . filesize( $filename ) ); flush(); readfile( $filename ); unlink( $filename ); exit; } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. | wordpress class WP_Site_Icon {} class WP\_Site\_Icon {} ======================= Core class used to implement site icon functionality. * [\_\_construct](wp_site_icon/__construct) β€” Registers actions and filters. * [additional\_sizes](wp_site_icon/additional_sizes) β€” Adds additional sizes to be made when creating the site icon images. * [create\_attachment\_object](wp_site_icon/create_attachment_object) β€” Creates an attachment 'object'. * [delete\_attachment\_data](wp_site_icon/delete_attachment_data) β€” Deletes the Site Icon when the image file is deleted. * [get\_post\_metadata](wp_site_icon/get_post_metadata) β€” Adds custom image sizes when meta data for an image is requested, that happens to be used as Site Icon. * [insert\_attachment](wp_site_icon/insert_attachment) β€” Inserts an attachment. * [intermediate\_image\_sizes](wp_site_icon/intermediate_image_sizes) β€” Adds Site Icon sizes to the array of image sizes on demand. File: `wp-admin/includes/class-wp-site-icon.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-icon.php/) ``` class WP_Site_Icon { /** * The minimum size of the site icon. * * @since 4.3.0 * @var int */ public $min_size = 512; /** * The size to which to crop the image so that we can display it in the UI nicely. * * @since 4.3.0 * @var int */ public $page_crop = 512; /** * List of site icon sizes. * * @since 4.3.0 * @var int[] */ public $site_icon_sizes = array( /* * Square, medium sized tiles for IE11+. * * See https://msdn.microsoft.com/library/dn455106(v=vs.85).aspx */ 270, /* * App icon for Android/Chrome. * * @link https://developers.google.com/web/updates/2014/11/Support-for-theme-color-in-Chrome-39-for-Android * @link https://developer.chrome.com/multidevice/android/installtohomescreen */ 192, /* * App icons up to iPhone 6 Plus. * * See https://developer.apple.com/library/prerelease/ios/documentation/UserExperience/Conceptual/MobileHIG/IconMatrix.html */ 180, // Our regular Favicon. 32, ); /** * Registers actions and filters. * * @since 4.3.0 */ public function __construct() { add_action( 'delete_attachment', array( $this, 'delete_attachment_data' ) ); add_filter( 'get_post_metadata', array( $this, 'get_post_metadata' ), 10, 4 ); } /** * Creates an attachment 'object'. * * @since 4.3.0 * * @param string $cropped Cropped image URL. * @param int $parent_attachment_id Attachment ID of parent image. * @return array An array with attachment object data. */ public function create_attachment_object( $cropped, $parent_attachment_id ) { $parent = get_post( $parent_attachment_id ); $parent_url = wp_get_attachment_url( $parent->ID ); $url = str_replace( wp_basename( $parent_url ), wp_basename( $cropped ), $parent_url ); $size = wp_getimagesize( $cropped ); $image_type = ( $size ) ? $size['mime'] : 'image/jpeg'; $attachment = array( 'ID' => $parent_attachment_id, 'post_title' => wp_basename( $cropped ), 'post_content' => $url, 'post_mime_type' => $image_type, 'guid' => $url, 'context' => 'site-icon', ); return $attachment; } /** * Inserts an attachment. * * @since 4.3.0 * * @param array $attachment An array with attachment object data. * @param string $file File path of the attached image. * @return int Attachment ID. */ public function insert_attachment( $attachment, $file ) { $attachment_id = wp_insert_attachment( $attachment, $file ); $metadata = wp_generate_attachment_metadata( $attachment_id, $file ); /** * Filters the site icon attachment metadata. * * @since 4.3.0 * * @see wp_generate_attachment_metadata() * * @param array $metadata Attachment metadata. */ $metadata = apply_filters( 'site_icon_attachment_metadata', $metadata ); wp_update_attachment_metadata( $attachment_id, $metadata ); return $attachment_id; } /** * Adds additional sizes to be made when creating the site icon images. * * @since 4.3.0 * * @param array[] $sizes Array of arrays containing information for additional sizes. * @return array[] Array of arrays containing additional image sizes. */ public function additional_sizes( $sizes = array() ) { $only_crop_sizes = array(); /** * Filters the different dimensions that a site icon is saved in. * * @since 4.3.0 * * @param int[] $site_icon_sizes Array of sizes available for the Site Icon. */ $this->site_icon_sizes = apply_filters( 'site_icon_image_sizes', $this->site_icon_sizes ); // Use a natural sort of numbers. natsort( $this->site_icon_sizes ); $this->site_icon_sizes = array_reverse( $this->site_icon_sizes ); // Ensure that we only resize the image into sizes that allow cropping. foreach ( $sizes as $name => $size_array ) { if ( isset( $size_array['crop'] ) ) { $only_crop_sizes[ $name ] = $size_array; } } foreach ( $this->site_icon_sizes as $size ) { if ( $size < $this->min_size ) { $only_crop_sizes[ 'site_icon-' . $size ] = array( 'width ' => $size, 'height' => $size, 'crop' => true, ); } } return $only_crop_sizes; } /** * Adds Site Icon sizes to the array of image sizes on demand. * * @since 4.3.0 * * @param string[] $sizes Array of image size names. * @return string[] Array of image size names. */ public function intermediate_image_sizes( $sizes = array() ) { /** This filter is documented in wp-admin/includes/class-wp-site-icon.php */ $this->site_icon_sizes = apply_filters( 'site_icon_image_sizes', $this->site_icon_sizes ); foreach ( $this->site_icon_sizes as $size ) { $sizes[] = 'site_icon-' . $size; } return $sizes; } /** * Deletes the Site Icon when the image file is deleted. * * @since 4.3.0 * * @param int $post_id Attachment ID. */ public function delete_attachment_data( $post_id ) { $site_icon_id = get_option( 'site_icon' ); if ( $site_icon_id && $post_id == $site_icon_id ) { delete_option( 'site_icon' ); } } /** * Adds custom image sizes when meta data for an image is requested, that happens to be used as Site Icon. * * @since 4.3.0 * * @param null|array|string $value The value get_metadata() should return a single metadata value, or an * array of values. * @param int $post_id Post ID. * @param string $meta_key Meta key. * @param bool $single Whether to return only the first value of the specified `$meta_key`. * @return array|null|string The attachment metadata value, array of values, or null. */ public function get_post_metadata( $value, $post_id, $meta_key, $single ) { if ( $single && '_wp_attachment_backup_sizes' === $meta_key ) { $site_icon_id = get_option( 'site_icon' ); if ( $post_id == $site_icon_id ) { add_filter( 'intermediate_image_sizes', array( $this, 'intermediate_image_sizes' ) ); } } return $value; } } ``` | Version | Description | | --- | --- | | [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. | wordpress class WP_Sitemaps_Posts {} class WP\_Sitemaps\_Posts {} ============================ Posts XML sitemap provider. * [\_\_construct](wp_sitemaps_posts/__construct) β€” WP\_Sitemaps\_Posts constructor. * [get\_max\_num\_pages](wp_sitemaps_posts/get_max_num_pages) β€” Gets the max number of pages available for the object type. * [get\_object\_subtypes](wp_sitemaps_posts/get_object_subtypes) β€” Returns the public post types, which excludes nav\_items and similar types. * [get\_posts\_query\_args](wp_sitemaps_posts/get_posts_query_args) β€” Returns the query args for retrieving posts to list in the sitemap. * [get\_url\_list](wp_sitemaps_posts/get_url_list) β€” Gets a URL list for a post type 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/) ``` class WP_Sitemaps_Posts extends WP_Sitemaps_Provider { /** * WP_Sitemaps_Posts constructor. * * @since 5.5.0 */ public function __construct() { $this->name = 'posts'; $this->object_type = 'post'; } /** * Returns the public post types, which excludes nav_items and similar types. * Attachments are also excluded. This includes custom post types with public = true. * * @since 5.5.0 * * @return WP_Post_Type[] Array of registered post type objects keyed by their name. */ 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 ); } /** * Gets a URL list for a post type sitemap. * * @since 5.5.0 * @since 5.9.0 Renamed `$post_type` to `$object_subtype` to match parent class * for PHP 8 named parameter support. * * @param int $page_num Page of results. * @param string $object_subtype Optional. Post type name. Default empty. * * @return array[] Array of URL information for a sitemap. */ 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; } /** * Gets the max number of pages available for the object type. * * @since 5.5.0 * @since 5.9.0 Renamed `$post_type` to `$object_subtype` to match parent class * for PHP 8 named parameter support. * * @param string $object_subtype Optional. Post type name. Default empty. * @return int Total number of pages. */ 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; } /** * Returns the query args for retrieving posts to list in the sitemap. * * @since 5.5.0 * @since 6.1.0 Added `ignore_sticky_posts` default parameter. * * @param string $post_type Post type name. * @return array Array of WP_Query arguments. */ 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; } } ``` | Uses | Description | | --- | --- | | [WP\_Sitemaps\_Provider](wp_sitemaps_provider) wp-includes/sitemaps/class-wp-sitemaps-provider.php | Class [WP\_Sitemaps\_Provider](wp_sitemaps_provider). | | Version | Description | | --- | --- | | [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
programming_docs
wordpress class Requests_Exception_HTTP_502 {} class Requests\_Exception\_HTTP\_502 {} ======================================= Exception for 502 Bad Gateway responses File: `wp-includes/Requests/Exception/HTTP/502.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/502.php/) ``` class Requests_Exception_HTTP_502 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 502; /** * Reason phrase * * @var string */ protected $reason = 'Bad Gateway'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_User_Meta_Session_Tokens {} class WP\_User\_Meta\_Session\_Tokens {} ======================================== Meta-based user sessions token manager. * [WP\_Session\_Tokens](wp_session_tokens) * [destroy\_all\_sessions](wp_user_meta_session_tokens/destroy_all_sessions) β€” Destroys all session tokens for the user. * [destroy\_other\_sessions](wp_user_meta_session_tokens/destroy_other_sessions) β€” Destroys all sessions for this user, except the single session with the given verifier. * [drop\_sessions](wp_user_meta_session_tokens/drop_sessions) β€” Destroys all sessions for all users. * [get\_session](wp_user_meta_session_tokens/get_session) β€” Retrieves a session based on its verifier (token hash). * [get\_sessions](wp_user_meta_session_tokens/get_sessions) β€” Retrieves all sessions of the user. * [prepare\_session](wp_user_meta_session_tokens/prepare_session) β€” Converts an expiration to an array of session information. * [update\_session](wp_user_meta_session_tokens/update_session) β€” Updates a session based on its verifier (token hash). * [update\_sessions](wp_user_meta_session_tokens/update_sessions) β€” Updates the user's sessions in the usermeta table. File: `wp-includes/class-wp-user-meta-session-tokens.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-meta-session-tokens.php/) ``` class WP_User_Meta_Session_Tokens extends WP_Session_Tokens { /** * Retrieves all sessions of the user. * * @since 4.0.0 * * @return array Sessions of the user. */ protected function get_sessions() { $sessions = get_user_meta( $this->user_id, 'session_tokens', true ); if ( ! is_array( $sessions ) ) { return array(); } $sessions = array_map( array( $this, 'prepare_session' ), $sessions ); return array_filter( $sessions, array( $this, 'is_still_valid' ) ); } /** * Converts an expiration to an array of session information. * * @param mixed $session Session or expiration. * @return array Session. */ protected function prepare_session( $session ) { if ( is_int( $session ) ) { return array( 'expiration' => $session ); } return $session; } /** * Retrieves a session based on its verifier (token hash). * * @since 4.0.0 * * @param string $verifier Verifier for the session to retrieve. * @return array|null The session, or null if it does not exist */ protected function get_session( $verifier ) { $sessions = $this->get_sessions(); if ( isset( $sessions[ $verifier ] ) ) { return $sessions[ $verifier ]; } return null; } /** * Updates a session based on its verifier (token hash). * * @since 4.0.0 * * @param string $verifier Verifier for the session to update. * @param array $session Optional. Session. Omitting this argument destroys the session. */ protected function update_session( $verifier, $session = null ) { $sessions = $this->get_sessions(); if ( $session ) { $sessions[ $verifier ] = $session; } else { unset( $sessions[ $verifier ] ); } $this->update_sessions( $sessions ); } /** * Updates the user's sessions in the usermeta table. * * @since 4.0.0 * * @param array $sessions Sessions. */ protected function update_sessions( $sessions ) { if ( $sessions ) { update_user_meta( $this->user_id, 'session_tokens', $sessions ); } else { delete_user_meta( $this->user_id, 'session_tokens' ); } } /** * Destroys all sessions for this user, except the single session with the given verifier. * * @since 4.0.0 * * @param string $verifier Verifier of the session to keep. */ protected function destroy_other_sessions( $verifier ) { $session = $this->get_session( $verifier ); $this->update_sessions( array( $verifier => $session ) ); } /** * Destroys all session tokens for the user. * * @since 4.0.0 */ protected function destroy_all_sessions() { $this->update_sessions( array() ); } /** * Destroys all sessions for all users. * * @since 4.0.0 */ public static function drop_sessions() { delete_metadata( 'user', 0, 'session_tokens', false, true ); } } ``` | Uses | Description | | --- | --- | | [WP\_Session\_Tokens](wp_session_tokens) wp-includes/class-wp-session-tokens.php | Abstract class for managing user session tokens. | | Version | Description | | --- | --- | | [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. | wordpress class WP_REST_Comments_Controller {} class WP\_REST\_Comments\_Controller {} ======================================= Core controller used to access comments via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_comments_controller/__construct) β€” Constructor. * [check\_comment\_author\_email](wp_rest_comments_controller/check_comment_author_email) β€” Checks a comment author email for validity. * [check\_edit\_permission](wp_rest_comments_controller/check_edit_permission) β€” Checks if a comment can be edited or deleted. * [check\_is\_comment\_content\_allowed](wp_rest_comments_controller/check_is_comment_content_allowed) β€” If empty comments are not allowed, checks if the provided comment content is not empty. * [check\_read\_permission](wp_rest_comments_controller/check_read_permission) β€” Checks if the comment can be read. * [check\_read\_post\_permission](wp_rest_comments_controller/check_read_post_permission) β€” Checks if the post can be read. * [create\_item](wp_rest_comments_controller/create_item) β€” Creates a comment. * [create\_item\_permissions\_check](wp_rest_comments_controller/create_item_permissions_check) β€” Checks if a given request has access to create a comment. * [delete\_item](wp_rest_comments_controller/delete_item) β€” Deletes a comment. * [delete\_item\_permissions\_check](wp_rest_comments_controller/delete_item_permissions_check) β€” Checks if a given request has access to delete a comment. * [get\_collection\_params](wp_rest_comments_controller/get_collection_params) β€” Retrieves the query params for collections. * [get\_comment](wp_rest_comments_controller/get_comment) β€” Get the comment, if the ID is valid. * [get\_item](wp_rest_comments_controller/get_item) β€” Retrieves a comment. * [get\_item\_permissions\_check](wp_rest_comments_controller/get_item_permissions_check) β€” Checks if a given request has access to read the comment. * [get\_item\_schema](wp_rest_comments_controller/get_item_schema) β€” Retrieves the comment's schema, conforming to JSON Schema. * [get\_items](wp_rest_comments_controller/get_items) β€” Retrieves a list of comment items. * [get\_items\_permissions\_check](wp_rest_comments_controller/get_items_permissions_check) β€” Checks if a given request has access to read comments. * [handle\_status\_param](wp_rest_comments_controller/handle_status_param) β€” Sets the comment\_status of a given comment object when creating or updating a comment. * [normalize\_query\_param](wp_rest_comments_controller/normalize_query_param) β€” Prepends internal property prefix to query parameters to match our response fields. * [prepare\_item\_for\_database](wp_rest_comments_controller/prepare_item_for_database) β€” Prepares a single comment to be inserted into the database. * [prepare\_item\_for\_response](wp_rest_comments_controller/prepare_item_for_response) β€” Prepares a single comment output for response. * [prepare\_links](wp_rest_comments_controller/prepare_links) β€” Prepares links for the request. * [prepare\_status\_response](wp_rest_comments_controller/prepare_status_response) β€” Checks comment\_approved to set comment status for single comment output. * [register\_routes](wp_rest_comments_controller/register_routes) β€” Registers the routes for comments. * [update\_item](wp_rest_comments_controller/update_item) β€” Updates a comment. * [update\_item\_permissions\_check](wp_rest_comments_controller/update_item_permissions_check) β€” Checks if a given REST request has access to update a comment. File: `wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php/) ``` class WP_REST_Comments_Controller extends WP_REST_Controller { /** * Instance of a comment meta fields object. * * @since 4.7.0 * @var WP_REST_Comment_Meta_Fields */ protected $meta; /** * Constructor. * * @since 4.7.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'comments'; $this->meta = new WP_REST_Comment_Meta_Fields(); } /** * Registers the routes for comments. * * @since 4.7.0 * * @see register_rest_route() */ 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 ), ), '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 comment.' ), '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' ) ), 'password' => array( 'description' => __( 'The password for the parent post of the comment (if the post is password protected).' ), 'type' => 'string', ), ), ), 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' => __( 'Whether to bypass Trash and force deletion.' ), ), 'password' => array( 'description' => __( 'The password for the parent post of the comment (if the post is password protected).' ), 'type' => 'string', ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks if a given request has access to read comments. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, error object otherwise. */ public function get_items_permissions_check( $request ) { if ( ! empty( $request['post'] ) ) { foreach ( (array) $request['post'] as $post_id ) { $post = get_post( $post_id ); if ( ! empty( $post_id ) && $post && ! $this->check_read_post_permission( $post, $request ) ) { return new WP_Error( 'rest_cannot_read_post', __( 'Sorry, you are not allowed to read the post for this comment.' ), array( 'status' => rest_authorization_required_code() ) ); } elseif ( 0 === $post_id && ! current_user_can( 'moderate_comments' ) ) { return new WP_Error( 'rest_cannot_read', __( 'Sorry, you are not allowed to read comments without a post.' ), array( 'status' => rest_authorization_required_code() ) ); } } } if ( ! empty( $request['context'] ) && 'edit' === $request['context'] && ! current_user_can( 'moderate_comments' ) ) { return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit comments.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( ! current_user_can( 'edit_posts' ) ) { $protected_params = array( 'author', 'author_exclude', 'author_email', 'type', 'status' ); $forbidden_params = array(); foreach ( $protected_params as $param ) { if ( 'status' === $param ) { if ( 'approve' !== $request[ $param ] ) { $forbidden_params[] = $param; } } elseif ( 'type' === $param ) { if ( 'comment' !== $request[ $param ] ) { $forbidden_params[] = $param; } } elseif ( ! empty( $request[ $param ] ) ) { $forbidden_params[] = $param; } } if ( ! empty( $forbidden_params ) ) { return new WP_Error( 'rest_forbidden_param', /* translators: %s: List of forbidden parameters. */ sprintf( __( 'Query parameter not permitted: %s' ), implode( ', ', $forbidden_params ) ), array( 'status' => rest_authorization_required_code() ) ); } } return true; } /** * Retrieves a list of comment items. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or error object on failure. */ 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( 'author' => 'author__in', 'author_email' => 'author_email', 'author_exclude' => 'author__not_in', 'exclude' => 'comment__not_in', 'include' => 'comment__in', 'offset' => 'offset', 'order' => 'order', 'parent' => 'parent__in', 'parent_exclude' => 'parent__not_in', 'per_page' => 'number', 'post' => 'post__in', 'search' => 'search', 'status' => 'status', 'type' => 'type', ); $prepared_args = array(); /* * 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 ]; } } // Ensure certain parameter values default to empty strings. foreach ( array( 'author_email', 'search' ) as $param ) { if ( ! isset( $prepared_args[ $param ] ) ) { $prepared_args[ $param ] = ''; } } if ( isset( $registered['orderby'] ) ) { $prepared_args['orderby'] = $this->normalize_query_param( $request['orderby'] ); } $prepared_args['no_found_rows'] = false; $prepared_args['update_comment_post_cache'] = true; $prepared_args['date_query'] = array(); // Set before into date query. Date query must be specified as an array of an array. if ( isset( $registered['before'], $request['before'] ) ) { $prepared_args['date_query'][0]['before'] = $request['before']; } // Set after into date query. Date query must be specified as an array of an array. if ( isset( $registered['after'], $request['after'] ) ) { $prepared_args['date_query'][0]['after'] = $request['after']; } if ( isset( $registered['page'] ) && empty( $request['offset'] ) ) { $prepared_args['offset'] = $prepared_args['number'] * ( absint( $request['page'] ) - 1 ); } /** * Filters WP_Comment_Query arguments when querying comments via the REST API. * * @since 4.7.0 * * @link https://developer.wordpress.org/reference/classes/wp_comment_query/ * * @param array $prepared_args Array of arguments for WP_Comment_Query. * @param WP_REST_Request $request The REST API request. */ $prepared_args = apply_filters( 'rest_comment_query', $prepared_args, $request ); $query = new WP_Comment_Query; $query_result = $query->query( $prepared_args ); $comments = array(); foreach ( $query_result as $comment ) { if ( ! $this->check_read_permission( $comment, $request ) ) { continue; } $data = $this->prepare_item_for_response( $comment, $request ); $comments[] = $this->prepare_response_for_collection( $data ); } $total_comments = (int) $query->found_comments; $max_pages = (int) $query->max_num_pages; if ( $total_comments < 1 ) { // Out-of-bounds, run the query again without LIMIT for total count. unset( $prepared_args['number'], $prepared_args['offset'] ); $query = new WP_Comment_Query; $prepared_args['count'] = true; $total_comments = $query->query( $prepared_args ); $max_pages = ceil( $total_comments / $request['per_page'] ); } $response = rest_ensure_response( $comments ); $response->header( 'X-WP-Total', $total_comments ); $response->header( 'X-WP-TotalPages', $max_pages ); $base = add_query_arg( urlencode_deep( $request->get_query_params() ), rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) ); if ( $request['page'] > 1 ) { $prev_page = $request['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 > $request['page'] ) { $next_page = $request['page'] + 1; $next_link = add_query_arg( 'page', $next_page, $base ); $response->link_header( 'next', $next_link ); } return $response; } /** * Get the comment, if the ID is valid. * * @since 4.7.2 * * @param int $id Supplied ID. * @return WP_Comment|WP_Error Comment object if ID is valid, WP_Error otherwise. */ protected function get_comment( $id ) { $error = new WP_Error( 'rest_comment_invalid_id', __( 'Invalid comment ID.' ), array( 'status' => 404 ) ); if ( (int) $id <= 0 ) { return $error; } $id = (int) $id; $comment = get_comment( $id ); if ( empty( $comment ) ) { return $error; } if ( ! empty( $comment->comment_post_ID ) ) { $post = get_post( (int) $comment->comment_post_ID ); if ( empty( $post ) ) { return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 404 ) ); } } return $comment; } /** * Checks if a given request has access to read the comment. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, error object otherwise. */ public function get_item_permissions_check( $request ) { $comment = $this->get_comment( $request['id'] ); if ( is_wp_error( $comment ) ) { return $comment; } if ( ! empty( $request['context'] ) && 'edit' === $request['context'] && ! current_user_can( 'moderate_comments' ) ) { return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit comments.' ), array( 'status' => rest_authorization_required_code() ) ); } $post = get_post( $comment->comment_post_ID ); if ( ! $this->check_read_permission( $comment, $request ) ) { return new WP_Error( 'rest_cannot_read', __( 'Sorry, you are not allowed to read this comment.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( $post && ! $this->check_read_post_permission( $post, $request ) ) { return new WP_Error( 'rest_cannot_read_post', __( 'Sorry, you are not allowed to read the post for this comment.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Retrieves a comment. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or error object on failure. */ public function get_item( $request ) { $comment = $this->get_comment( $request['id'] ); if ( is_wp_error( $comment ) ) { return $comment; } $data = $this->prepare_item_for_response( $comment, $request ); $response = rest_ensure_response( $data ); return $response; } /** * Checks if a given request has access to create a comment. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to create items, error object otherwise. */ public function create_item_permissions_check( $request ) { if ( ! is_user_logged_in() ) { if ( get_option( 'comment_registration' ) ) { return new WP_Error( 'rest_comment_login_required', __( 'Sorry, you must be logged in to comment.' ), array( 'status' => 401 ) ); } /** * Filters whether comments can be created via the REST API without authentication. * * Enables creating comments for anonymous users. * * @since 4.7.0 * * @param bool $allow_anonymous Whether to allow anonymous comments to * be created. Default `false`. * @param WP_REST_Request $request Request used to generate the * response. */ $allow_anonymous = apply_filters( 'rest_allow_anonymous_comments', false, $request ); if ( ! $allow_anonymous ) { return new WP_Error( 'rest_comment_login_required', __( 'Sorry, you must be logged in to comment.' ), array( 'status' => 401 ) ); } } // Limit who can set comment `author`, `author_ip` or `status` to anything other than the default. if ( isset( $request['author'] ) && get_current_user_id() !== $request['author'] && ! current_user_can( 'moderate_comments' ) ) { return new WP_Error( 'rest_comment_invalid_author', /* translators: %s: Request parameter. */ sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author' ), array( 'status' => rest_authorization_required_code() ) ); } if ( isset( $request['author_ip'] ) && ! current_user_can( 'moderate_comments' ) ) { if ( empty( $_SERVER['REMOTE_ADDR'] ) || $request['author_ip'] !== $_SERVER['REMOTE_ADDR'] ) { return new WP_Error( 'rest_comment_invalid_author_ip', /* translators: %s: Request parameter. */ sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'author_ip' ), array( 'status' => rest_authorization_required_code() ) ); } } if ( isset( $request['status'] ) && ! current_user_can( 'moderate_comments' ) ) { return new WP_Error( 'rest_comment_invalid_status', /* translators: %s: Request parameter. */ sprintf( __( "Sorry, you are not allowed to edit '%s' for comments." ), 'status' ), array( 'status' => rest_authorization_required_code() ) ); } if ( empty( $request['post'] ) ) { return new WP_Error( 'rest_comment_invalid_post_id', __( 'Sorry, you are not allowed to create this comment without a post.' ), array( 'status' => 403 ) ); } $post = get_post( (int) $request['post'] ); if ( ! $post ) { return new WP_Error( 'rest_comment_invalid_post_id', __( 'Sorry, you are not allowed to create this comment without a post.' ), array( 'status' => 403 ) ); } if ( 'draft' === $post->post_status ) { return new WP_Error( 'rest_comment_draft_post', __( 'Sorry, you are not allowed to create a comment on this post.' ), array( 'status' => 403 ) ); } if ( 'trash' === $post->post_status ) { return new WP_Error( 'rest_comment_trash_post', __( 'Sorry, you are not allowed to create a comment on this post.' ), array( 'status' => 403 ) ); } if ( ! $this->check_read_post_permission( $post, $request ) ) { return new WP_Error( 'rest_cannot_read_post', __( 'Sorry, you are not allowed to read the post for this comment.' ), array( 'status' => rest_authorization_required_code() ) ); } if ( ! comments_open( $post->ID ) ) { return new WP_Error( 'rest_comment_closed', __( 'Sorry, comments are closed for this item.' ), array( 'status' => 403 ) ); } return true; } /** * Creates a comment. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or error object on failure. */ public function create_item( $request ) { if ( ! empty( $request['id'] ) ) { return new WP_Error( 'rest_comment_exists', __( 'Cannot create existing comment.' ), array( 'status' => 400 ) ); } // Do not allow comments to be created with a non-default type. if ( ! empty( $request['type'] ) && 'comment' !== $request['type'] ) { return new WP_Error( 'rest_invalid_comment_type', __( 'Cannot create a comment with that type.' ), array( 'status' => 400 ) ); } $prepared_comment = $this->prepare_item_for_database( $request ); if ( is_wp_error( $prepared_comment ) ) { return $prepared_comment; } $prepared_comment['comment_type'] = 'comment'; if ( ! isset( $prepared_comment['comment_content'] ) ) { $prepared_comment['comment_content'] = ''; } if ( ! $this->check_is_comment_content_allowed( $prepared_comment ) ) { return new WP_Error( 'rest_comment_content_invalid', __( 'Invalid comment content.' ), array( 'status' => 400 ) ); } // Setting remaining values before wp_insert_comment so we can use wp_allow_comment(). if ( ! isset( $prepared_comment['comment_date_gmt'] ) ) { $prepared_comment['comment_date_gmt'] = current_time( 'mysql', true ); } // Set author data if the user's logged in. $missing_author = empty( $prepared_comment['user_id'] ) && empty( $prepared_comment['comment_author'] ) && empty( $prepared_comment['comment_author_email'] ) && empty( $prepared_comment['comment_author_url'] ); if ( is_user_logged_in() && $missing_author ) { $user = wp_get_current_user(); $prepared_comment['user_id'] = $user->ID; $prepared_comment['comment_author'] = $user->display_name; $prepared_comment['comment_author_email'] = $user->user_email; $prepared_comment['comment_author_url'] = $user->user_url; } // Honor the discussion setting that requires a name and email address of the comment author. if ( get_option( 'require_name_email' ) ) { if ( empty( $prepared_comment['comment_author'] ) || empty( $prepared_comment['comment_author_email'] ) ) { return new WP_Error( 'rest_comment_author_data_required', __( 'Creating a comment requires valid author name and email values.' ), array( 'status' => 400 ) ); } } if ( ! isset( $prepared_comment['comment_author_email'] ) ) { $prepared_comment['comment_author_email'] = ''; } if ( ! isset( $prepared_comment['comment_author_url'] ) ) { $prepared_comment['comment_author_url'] = ''; } if ( ! isset( $prepared_comment['comment_agent'] ) ) { $prepared_comment['comment_agent'] = ''; } $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_comment ); if ( is_wp_error( $check_comment_lengths ) ) { $error_code = $check_comment_lengths->get_error_code(); return new WP_Error( $error_code, __( 'Comment field exceeds maximum length allowed.' ), array( 'status' => 400 ) ); } $prepared_comment['comment_approved'] = wp_allow_comment( $prepared_comment, true ); if ( is_wp_error( $prepared_comment['comment_approved'] ) ) { $error_code = $prepared_comment['comment_approved']->get_error_code(); $error_message = $prepared_comment['comment_approved']->get_error_message(); if ( 'comment_duplicate' === $error_code ) { return new WP_Error( $error_code, $error_message, array( 'status' => 409 ) ); } if ( 'comment_flood' === $error_code ) { return new WP_Error( $error_code, $error_message, array( 'status' => 400 ) ); } return $prepared_comment['comment_approved']; } /** * Filters a comment before it is inserted via the REST API. * * Allows modification of the comment right before it is inserted via wp_insert_comment(). * Returning a WP_Error value from the filter will short-circuit insertion and allow * skipping further processing. * * @since 4.7.0 * @since 4.8.0 `$prepared_comment` can now be a WP_Error to short-circuit insertion. * * @param array|WP_Error $prepared_comment The prepared comment data for wp_insert_comment(). * @param WP_REST_Request $request Request used to insert the comment. */ $prepared_comment = apply_filters( 'rest_pre_insert_comment', $prepared_comment, $request ); if ( is_wp_error( $prepared_comment ) ) { return $prepared_comment; } $comment_id = wp_insert_comment( wp_filter_comment( wp_slash( (array) $prepared_comment ) ) ); if ( ! $comment_id ) { return new WP_Error( 'rest_comment_failed_create', __( 'Creating comment failed.' ), array( 'status' => 500 ) ); } if ( isset( $request['status'] ) ) { $this->handle_status_param( $request['status'], $comment_id ); } $comment = get_comment( $comment_id ); /** * Fires after a comment is created or updated via the REST API. * * @since 4.7.0 * * @param WP_Comment $comment Inserted or updated comment object. * @param WP_REST_Request $request Request object. * @param bool $creating True when creating a comment, false * when updating. */ do_action( 'rest_insert_comment', $comment, $request, true ); $schema = $this->get_item_schema(); if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { $meta_update = $this->meta->update_value( $request['meta'], $comment_id ); if ( is_wp_error( $meta_update ) ) { return $meta_update; } } $fields_update = $this->update_additional_fields_for_object( $comment, $request ); if ( is_wp_error( $fields_update ) ) { return $fields_update; } $context = current_user_can( 'moderate_comments' ) ? 'edit' : 'view'; $request->set_param( 'context', $context ); /** * Fires completely after a comment is created or updated via the REST API. * * @since 5.0.0 * * @param WP_Comment $comment Inserted or updated comment object. * @param WP_REST_Request $request Request object. * @param bool $creating True when creating a comment, false * when updating. */ do_action( 'rest_after_insert_comment', $comment, $request, true ); $response = $this->prepare_item_for_response( $comment, $request ); $response = rest_ensure_response( $response ); $response->set_status( 201 ); $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment_id ) ) ); return $response; } /** * Checks if a given REST request has access to update a comment. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to update the item, error object otherwise. */ public function update_item_permissions_check( $request ) { $comment = $this->get_comment( $request['id'] ); if ( is_wp_error( $comment ) ) { return $comment; } if ( ! $this->check_edit_permission( $comment ) ) { return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this comment.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Updates a comment. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or error object on failure. */ public function update_item( $request ) { $comment = $this->get_comment( $request['id'] ); if ( is_wp_error( $comment ) ) { return $comment; } $id = $comment->comment_ID; if ( isset( $request['type'] ) && get_comment_type( $id ) !== $request['type'] ) { return new WP_Error( 'rest_comment_invalid_type', __( 'Sorry, you are not allowed to change the comment type.' ), array( 'status' => 404 ) ); } $prepared_args = $this->prepare_item_for_database( $request ); if ( is_wp_error( $prepared_args ) ) { return $prepared_args; } if ( ! empty( $prepared_args['comment_post_ID'] ) ) { $post = get_post( $prepared_args['comment_post_ID'] ); if ( empty( $post ) ) { return new WP_Error( 'rest_comment_invalid_post_id', __( 'Invalid post ID.' ), array( 'status' => 403 ) ); } } if ( empty( $prepared_args ) && isset( $request['status'] ) ) { // Only the comment status is being changed. $change = $this->handle_status_param( $request['status'], $id ); if ( ! $change ) { return new WP_Error( 'rest_comment_failed_edit', __( 'Updating comment status failed.' ), array( 'status' => 500 ) ); } } elseif ( ! empty( $prepared_args ) ) { if ( is_wp_error( $prepared_args ) ) { return $prepared_args; } if ( isset( $prepared_args['comment_content'] ) && empty( $prepared_args['comment_content'] ) ) { return new WP_Error( 'rest_comment_content_invalid', __( 'Invalid comment content.' ), array( 'status' => 400 ) ); } $prepared_args['comment_ID'] = $id; $check_comment_lengths = wp_check_comment_data_max_lengths( $prepared_args ); if ( is_wp_error( $check_comment_lengths ) ) { $error_code = $check_comment_lengths->get_error_code(); return new WP_Error( $error_code, __( 'Comment field exceeds maximum length allowed.' ), array( 'status' => 400 ) ); } $updated = wp_update_comment( wp_slash( (array) $prepared_args ), true ); if ( is_wp_error( $updated ) ) { return new WP_Error( 'rest_comment_failed_edit', __( 'Updating comment failed.' ), array( 'status' => 500 ) ); } if ( isset( $request['status'] ) ) { $this->handle_status_param( $request['status'], $id ); } } $comment = get_comment( $id ); /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php */ do_action( 'rest_insert_comment', $comment, $request, false ); $schema = $this->get_item_schema(); if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { $meta_update = $this->meta->update_value( $request['meta'], $id ); if ( is_wp_error( $meta_update ) ) { return $meta_update; } } $fields_update = $this->update_additional_fields_for_object( $comment, $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-comments-controller.php */ do_action( 'rest_after_insert_comment', $comment, $request, false ); $response = $this->prepare_item_for_response( $comment, $request ); return rest_ensure_response( $response ); } /** * Checks if a given request has access to delete a comment. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to delete the item, error object otherwise. */ public function delete_item_permissions_check( $request ) { $comment = $this->get_comment( $request['id'] ); if ( is_wp_error( $comment ) ) { return $comment; } if ( ! $this->check_edit_permission( $comment ) ) { return new WP_Error( 'rest_cannot_delete', __( 'Sorry, you are not allowed to delete this comment.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Deletes a comment. * * @since 4.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or error object on failure. */ public function delete_item( $request ) { $comment = $this->get_comment( $request['id'] ); if ( is_wp_error( $comment ) ) { return $comment; } $force = isset( $request['force'] ) ? (bool) $request['force'] : false; /** * Filters whether a comment can be trashed via the REST API. * * Return false to disable trash support for the comment. * * @since 4.7.0 * * @param bool $supports_trash Whether the comment supports trashing. * @param WP_Comment $comment The comment object being considered for trashing support. */ $supports_trash = apply_filters( 'rest_comment_trashable', ( EMPTY_TRASH_DAYS > 0 ), $comment ); $request->set_param( 'context', 'edit' ); if ( $force ) { $previous = $this->prepare_item_for_response( $comment, $request ); $result = wp_delete_comment( $comment->comment_ID, true ); $response = new WP_REST_Response(); $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data(), ) ); } else { // If this type doesn't support trashing, error out. if ( ! $supports_trash ) { return new WP_Error( 'rest_trash_not_supported', /* translators: %s: force=true */ sprintf( __( "The comment does not support trashing. Set '%s' to delete." ), 'force=true' ), array( 'status' => 501 ) ); } if ( 'trash' === $comment->comment_approved ) { return new WP_Error( 'rest_already_trashed', __( 'The comment has already been trashed.' ), array( 'status' => 410 ) ); } $result = wp_trash_comment( $comment->comment_ID ); $comment = get_comment( $comment->comment_ID ); $response = $this->prepare_item_for_response( $comment, $request ); } if ( ! $result ) { return new WP_Error( 'rest_cannot_delete', __( 'The comment cannot be deleted.' ), array( 'status' => 500 ) ); } /** * Fires after a comment is deleted via the REST API. * * @since 4.7.0 * * @param WP_Comment $comment The deleted comment data. * @param WP_REST_Response $response The response returned from the API. * @param WP_REST_Request $request The request sent to the API. */ do_action( 'rest_delete_comment', $comment, $response, $request ); return $response; } /** * Prepares a single comment output for response. * * @since 4.7.0 * @since 5.9.0 Renamed `$comment` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Comment $item Comment object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $comment = $item; $fields = $this->get_fields_for_response( $request ); $data = array(); if ( in_array( 'id', $fields, true ) ) { $data['id'] = (int) $comment->comment_ID; } if ( in_array( 'post', $fields, true ) ) { $data['post'] = (int) $comment->comment_post_ID; } if ( in_array( 'parent', $fields, true ) ) { $data['parent'] = (int) $comment->comment_parent; } if ( in_array( 'author', $fields, true ) ) { $data['author'] = (int) $comment->user_id; } if ( in_array( 'author_name', $fields, true ) ) { $data['author_name'] = $comment->comment_author; } if ( in_array( 'author_email', $fields, true ) ) { $data['author_email'] = $comment->comment_author_email; } if ( in_array( 'author_url', $fields, true ) ) { $data['author_url'] = $comment->comment_author_url; } if ( in_array( 'author_ip', $fields, true ) ) { $data['author_ip'] = $comment->comment_author_IP; } if ( in_array( 'author_user_agent', $fields, true ) ) { $data['author_user_agent'] = $comment->comment_agent; } if ( in_array( 'date', $fields, true ) ) { $data['date'] = mysql_to_rfc3339( $comment->comment_date ); } if ( in_array( 'date_gmt', $fields, true ) ) { $data['date_gmt'] = mysql_to_rfc3339( $comment->comment_date_gmt ); } if ( in_array( 'content', $fields, true ) ) { $data['content'] = array( /** This filter is documented in wp-includes/comment-template.php */ 'rendered' => apply_filters( 'comment_text', $comment->comment_content, $comment ), 'raw' => $comment->comment_content, ); } if ( in_array( 'link', $fields, true ) ) { $data['link'] = get_comment_link( $comment ); } if ( in_array( 'status', $fields, true ) ) { $data['status'] = $this->prepare_status_response( $comment->comment_approved ); } if ( in_array( 'type', $fields, true ) ) { $data['type'] = get_comment_type( $comment->comment_ID ); } if ( in_array( 'author_avatar_urls', $fields, true ) ) { $data['author_avatar_urls'] = rest_get_avatar_urls( $comment ); } if ( in_array( 'meta', $fields, true ) ) { $data['meta'] = $this->meta->get_value( $comment->comment_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 ); // Wrap the data in a response object. $response = rest_ensure_response( $data ); if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { $response->add_links( $this->prepare_links( $comment ) ); } /** * Filters a comment returned from the REST API. * * Allows modification of the comment right before it is returned. * * @since 4.7.0 * * @param WP_REST_Response $response The response object. * @param WP_Comment $comment The original comment object. * @param WP_REST_Request $request Request used to generate the response. */ return apply_filters( 'rest_prepare_comment', $response, $comment, $request ); } /** * Prepares links for the request. * * @since 4.7.0 * * @param WP_Comment $comment Comment object. * @return array Links for the given comment. */ protected function prepare_links( $comment ) { $links = array( 'self' => array( 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_ID ) ), ), 'collection' => array( 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ), ), ); if ( 0 !== (int) $comment->user_id ) { $links['author'] = array( 'href' => rest_url( 'wp/v2/users/' . $comment->user_id ), 'embeddable' => true, ); } if ( 0 !== (int) $comment->comment_post_ID ) { $post = get_post( $comment->comment_post_ID ); $post_route = rest_get_route_for_post( $post ); if ( ! empty( $post->ID ) && $post_route ) { $links['up'] = array( 'href' => rest_url( $post_route ), 'embeddable' => true, 'post_type' => $post->post_type, ); } } if ( 0 !== (int) $comment->comment_parent ) { $links['in-reply-to'] = array( 'href' => rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $comment->comment_parent ) ), 'embeddable' => true, ); } // Only grab one comment to verify the comment has children. $comment_children = $comment->get_children( array( 'number' => 1, 'count' => true, ) ); if ( ! empty( $comment_children ) ) { $args = array( 'parent' => $comment->comment_ID, ); $rest_url = add_query_arg( $args, rest_url( $this->namespace . '/' . $this->rest_base ) ); $links['children'] = array( 'href' => $rest_url, 'embeddable' => true, ); } return $links; } /** * Prepends internal property prefix to query parameters to match our response fields. * * @since 4.7.0 * * @param string $query_param Query parameter. * @return string The normalized query parameter. */ protected function normalize_query_param( $query_param ) { $prefix = 'comment_'; switch ( $query_param ) { case 'id': $normalized = $prefix . 'ID'; break; case 'post': $normalized = $prefix . 'post_ID'; break; case 'parent': $normalized = $prefix . 'parent'; break; case 'include': $normalized = 'comment__in'; break; default: $normalized = $prefix . $query_param; break; } return $normalized; } /** * Checks comment_approved to set comment status for single comment output. * * @since 4.7.0 * * @param string|int $comment_approved comment status. * @return string Comment status. */ protected function prepare_status_response( $comment_approved ) { switch ( $comment_approved ) { case 'hold': case '0': $status = 'hold'; break; case 'approve': case '1': $status = 'approved'; break; case 'spam': case 'trash': default: $status = $comment_approved; break; } return $status; } /** * Prepares a single comment to be inserted into the database. * * @since 4.7.0 * * @param WP_REST_Request $request Request object. * @return array|WP_Error Prepared comment, otherwise WP_Error object. */ protected function prepare_item_for_database( $request ) { $prepared_comment = array(); /* * Allow the comment_content to be set via the 'content' or * the 'content.raw' properties of the Request object. */ if ( isset( $request['content'] ) && is_string( $request['content'] ) ) { $prepared_comment['comment_content'] = trim( $request['content'] ); } elseif ( isset( $request['content']['raw'] ) && is_string( $request['content']['raw'] ) ) { $prepared_comment['comment_content'] = trim( $request['content']['raw'] ); } if ( isset( $request['post'] ) ) { $prepared_comment['comment_post_ID'] = (int) $request['post']; } if ( isset( $request['parent'] ) ) { $prepared_comment['comment_parent'] = $request['parent']; } if ( isset( $request['author'] ) ) { $user = new WP_User( $request['author'] ); if ( $user->exists() ) { $prepared_comment['user_id'] = $user->ID; $prepared_comment['comment_author'] = $user->display_name; $prepared_comment['comment_author_email'] = $user->user_email; $prepared_comment['comment_author_url'] = $user->user_url; } else { return new WP_Error( 'rest_comment_author_invalid', __( 'Invalid comment author ID.' ), array( 'status' => 400 ) ); } } if ( isset( $request['author_name'] ) ) { $prepared_comment['comment_author'] = $request['author_name']; } if ( isset( $request['author_email'] ) ) { $prepared_comment['comment_author_email'] = $request['author_email']; } if ( isset( $request['author_url'] ) ) { $prepared_comment['comment_author_url'] = $request['author_url']; } if ( isset( $request['author_ip'] ) && current_user_can( 'moderate_comments' ) ) { $prepared_comment['comment_author_IP'] = $request['author_ip']; } elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) && rest_is_ip_address( $_SERVER['REMOTE_ADDR'] ) ) { $prepared_comment['comment_author_IP'] = $_SERVER['REMOTE_ADDR']; } else { $prepared_comment['comment_author_IP'] = '127.0.0.1'; } if ( ! empty( $request['author_user_agent'] ) ) { $prepared_comment['comment_agent'] = $request['author_user_agent']; } elseif ( $request->get_header( 'user_agent' ) ) { $prepared_comment['comment_agent'] = $request->get_header( 'user_agent' ); } if ( ! empty( $request['date'] ) ) { $date_data = rest_get_date_with_gmt( $request['date'] ); if ( ! empty( $date_data ) ) { list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data; } } elseif ( ! empty( $request['date_gmt'] ) ) { $date_data = rest_get_date_with_gmt( $request['date_gmt'], true ); if ( ! empty( $date_data ) ) { list( $prepared_comment['comment_date'], $prepared_comment['comment_date_gmt'] ) = $date_data; } } /** * Filters a comment added via the REST API after it is prepared for insertion into the database. * * Allows modification of the comment right after it is prepared for the database. * * @since 4.7.0 * * @param array $prepared_comment The prepared comment data for `wp_insert_comment`. * @param WP_REST_Request $request The current request. */ return apply_filters( 'rest_preprocess_comment', $prepared_comment, $request ); } /** * Retrieves the comment's schema, conforming to JSON Schema. * * @since 4.7.0 * * @return array */ 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' => 'comment', 'type' => 'object', 'properties' => array( 'id' => array( 'description' => __( 'Unique identifier for the comment.' ), 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'author' => array( 'description' => __( 'The ID of the user object, if author was a user.' ), 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), ), 'author_email' => array( 'description' => __( 'Email address for the comment author.' ), 'type' => 'string', 'format' => 'email', 'context' => array( 'edit' ), 'arg_options' => array( 'sanitize_callback' => array( $this, 'check_comment_author_email' ), 'validate_callback' => null, // Skip built-in validation of 'email'. ), ), 'author_ip' => array( 'description' => __( 'IP address for the comment author.' ), 'type' => 'string', 'format' => 'ip', 'context' => array( 'edit' ), ), 'author_name' => array( 'description' => __( 'Display name for the comment author.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'author_url' => array( 'description' => __( 'URL for the comment author.' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'view', 'edit', 'embed' ), ), 'author_user_agent' => array( 'description' => __( 'User agent for the comment author.' ), 'type' => 'string', 'context' => array( 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_text_field', ), ), 'content' => array( 'description' => __( 'The content for the comment.' ), 'type' => 'object', 'context' => array( 'view', 'edit', 'embed' ), 'arg_options' => array( 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database(). 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database(). ), 'properties' => array( 'raw' => array( 'description' => __( 'Content for the comment, as it exists in the database.' ), 'type' => 'string', 'context' => array( 'edit' ), ), 'rendered' => array( 'description' => __( 'HTML content for the comment, transformed for display.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), ), ), 'date' => array( 'description' => __( "The date the comment was published, in the site's timezone." ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'view', 'edit', 'embed' ), ), 'date_gmt' => array( 'description' => __( 'The date the comment was published, as GMT.' ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'view', 'edit' ), ), 'link' => array( 'description' => __( 'URL to the comment.' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'parent' => array( 'description' => __( 'The ID for the parent of the comment.' ), 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), 'default' => 0, ), 'post' => array( 'description' => __( 'The ID of the associated post object.' ), 'type' => 'integer', 'context' => array( 'view', 'edit' ), 'default' => 0, ), 'status' => array( 'description' => __( 'State of the comment.' ), 'type' => 'string', 'context' => array( 'view', 'edit' ), 'arg_options' => array( 'sanitize_callback' => 'sanitize_key', ), ), 'type' => array( 'description' => __( 'Type of the comment.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), ), ); if ( get_option( 'show_avatars' ) ) { $avatar_properties = array(); $avatar_sizes = rest_get_avatar_sizes(); foreach ( $avatar_sizes as $size ) { $avatar_properties[ $size ] = array( /* translators: %d: Avatar image size in pixels. */ 'description' => sprintf( __( 'Avatar URL with image size of %d pixels.' ), $size ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'embed', 'view', 'edit' ), ); } $schema['properties']['author_avatar_urls'] = array( 'description' => __( 'Avatar URLs for the comment author.' ), 'type' => 'object', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, 'properties' => $avatar_properties, ); } $schema['properties']['meta'] = $this->meta->get_field_schema(); $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the query params for collections. * * @since 4.7.0 * * @return array Comments collection parameters. */ public function get_collection_params() { $query_params = parent::get_collection_params(); $query_params['context']['default'] = 'view'; $query_params['after'] = array( 'description' => __( 'Limit response to comments published after a given ISO8601 compliant date.' ), 'type' => 'string', 'format' => 'date-time', ); $query_params['author'] = array( 'description' => __( 'Limit result set to comments assigned to specific user IDs. Requires authorization.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), ); $query_params['author_exclude'] = array( 'description' => __( 'Ensure result set excludes comments assigned to specific user IDs. Requires authorization.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), ); $query_params['author_email'] = array( 'default' => null, 'description' => __( 'Limit result set to that from a specific author email. Requires authorization.' ), 'format' => 'email', 'type' => 'string', ); $query_params['before'] = array( 'description' => __( 'Limit response to comments published before a given ISO8601 compliant date.' ), 'type' => 'string', 'format' => 'date-time', ); $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(), ); $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' => 'desc', 'enum' => array( 'asc', 'desc', ), ); $query_params['orderby'] = array( 'description' => __( 'Sort collection by comment attribute.' ), 'type' => 'string', 'default' => 'date_gmt', 'enum' => array( 'date', 'date_gmt', 'id', 'include', 'post', 'parent', 'type', ), ); $query_params['parent'] = array( 'default' => array(), 'description' => __( 'Limit result set to comments of specific parent IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), ); $query_params['parent_exclude'] = array( 'default' => array(), 'description' => __( 'Ensure result set excludes specific parent IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), ); $query_params['post'] = array( 'default' => array(), 'description' => __( 'Limit result set to comments assigned to specific post IDs.' ), 'type' => 'array', 'items' => array( 'type' => 'integer', ), ); $query_params['status'] = array( 'default' => 'approve', 'description' => __( 'Limit result set to comments assigned a specific status. Requires authorization.' ), 'sanitize_callback' => 'sanitize_key', 'type' => 'string', 'validate_callback' => 'rest_validate_request_arg', ); $query_params['type'] = array( 'default' => 'comment', 'description' => __( 'Limit result set to comments assigned a specific type. Requires authorization.' ), 'sanitize_callback' => 'sanitize_key', 'type' => 'string', 'validate_callback' => 'rest_validate_request_arg', ); $query_params['password'] = array( 'description' => __( 'The password for the post if it is password protected.' ), 'type' => 'string', ); /** * Filters REST API collection parameters for the comments controller. * * This filter registers the collection parameter, but does not map the * collection parameter to an internal WP_Comment_Query parameter. Use the * `rest_comment_query` filter to set WP_Comment_Query parameters. * * @since 4.7.0 * * @param array $query_params JSON Schema-formatted collection parameters. */ return apply_filters( 'rest_comment_collection_params', $query_params ); } /** * Sets the comment_status of a given comment object when creating or updating a comment. * * @since 4.7.0 * * @param string|int $new_status New comment status. * @param int $comment_id Comment ID. * @return bool Whether the status was changed. */ protected function handle_status_param( $new_status, $comment_id ) { $old_status = wp_get_comment_status( $comment_id ); if ( $new_status === $old_status ) { return false; } switch ( $new_status ) { case 'approved': case 'approve': case '1': $changed = wp_set_comment_status( $comment_id, 'approve' ); break; case 'hold': case '0': $changed = wp_set_comment_status( $comment_id, 'hold' ); break; case 'spam': $changed = wp_spam_comment( $comment_id ); break; case 'unspam': $changed = wp_unspam_comment( $comment_id ); break; case 'trash': $changed = wp_trash_comment( $comment_id ); break; case 'untrash': $changed = wp_untrash_comment( $comment_id ); break; default: $changed = false; break; } return $changed; } /** * Checks if the post can be read. * * Correctly handles posts with the inherit status. * * @since 4.7.0 * * @param WP_Post $post Post object. * @param WP_REST_Request $request Request data to check. * @return bool Whether post can be read. */ protected function check_read_post_permission( $post, $request ) { $post_type = get_post_type_object( $post->post_type ); // Return false if custom post type doesn't exist if ( ! $post_type ) { return false; } $posts_controller = $post_type->get_rest_controller(); // Ensure the posts controller is specifically a WP_REST_Posts_Controller instance // before using methods specific to that controller. if ( ! $posts_controller instanceof WP_REST_Posts_Controller ) { $posts_controller = new WP_REST_Posts_Controller( $post->post_type ); } $has_password_filter = false; // Only check password if a specific post was queried for or a single comment $requested_post = ! empty( $request['post'] ) && ( ! is_array( $request['post'] ) || 1 === count( $request['post'] ) ); $requested_comment = ! empty( $request['id'] ); if ( ( $requested_post || $requested_comment ) && $posts_controller->can_access_password_content( $post, $request ) ) { add_filter( 'post_password_required', '__return_false' ); $has_password_filter = true; } if ( post_password_required( $post ) ) { $result = current_user_can( 'edit_post', $post->ID ); } else { $result = $posts_controller->check_read_permission( $post ); } if ( $has_password_filter ) { remove_filter( 'post_password_required', '__return_false' ); } return $result; } /** * Checks if the comment can be read. * * @since 4.7.0 * * @param WP_Comment $comment Comment object. * @param WP_REST_Request $request Request data to check. * @return bool Whether the comment can be read. */ protected function check_read_permission( $comment, $request ) { if ( ! empty( $comment->comment_post_ID ) ) { $post = get_post( $comment->comment_post_ID ); if ( $post ) { if ( $this->check_read_post_permission( $post, $request ) && 1 === (int) $comment->comment_approved ) { return true; } } } if ( 0 === get_current_user_id() ) { return false; } if ( empty( $comment->comment_post_ID ) && ! current_user_can( 'moderate_comments' ) ) { return false; } if ( ! empty( $comment->user_id ) && get_current_user_id() === (int) $comment->user_id ) { return true; } return current_user_can( 'edit_comment', $comment->comment_ID ); } /** * Checks if a comment can be edited or deleted. * * @since 4.7.0 * * @param WP_Comment $comment Comment object. * @return bool Whether the comment can be edited or deleted. */ protected function check_edit_permission( $comment ) { if ( 0 === (int) get_current_user_id() ) { return false; } if ( current_user_can( 'moderate_comments' ) ) { return true; } return current_user_can( 'edit_comment', $comment->comment_ID ); } /** * Checks a comment author email for validity. * * Accepts either a valid email address or empty string as a valid comment * author email address. Setting the comment author email to an empty * string is allowed when a comment is being updated. * * @since 4.7.0 * * @param string $value Author email value submitted. * @param WP_REST_Request $request Full details about the request. * @param string $param The parameter name. * @return string|WP_Error The sanitized email address, if valid, * otherwise an error. */ public function check_comment_author_email( $value, $request, $param ) { $email = (string) $value; if ( empty( $email ) ) { return $email; } $check_email = rest_validate_request_arg( $email, $request, $param ); if ( is_wp_error( $check_email ) ) { return $check_email; } return $email; } /** * If empty comments are not allowed, checks if the provided comment content is not empty. * * @since 5.6.0 * * @param array $prepared_comment The prepared comment data. * @return bool True if the content is allowed, false otherwise. */ protected function check_is_comment_content_allowed( $prepared_comment ) { $check = wp_parse_args( $prepared_comment, array( 'comment_post_ID' => 0, 'comment_author' => null, 'comment_author_email' => null, 'comment_author_url' => null, 'comment_parent' => 0, 'user_id' => 0, ) ); /** This filter is documented in wp-includes/comment.php */ $allow_empty = apply_filters( 'allow_empty_comment', false, $check ); if ( $allow_empty ) { return true; } /* * Do not allow a comment to be created with missing or empty * comment_content. See wp_handle_comment_submission(). */ return '' !== $check['comment_content']; } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
programming_docs
wordpress class Requests_IDNAEncoder {} class Requests\_IDNAEncoder {} ============================== IDNA URL encoder Note: Not fully compliant, as nameprep does nothing yet. * <https://tools.ietf.org/html/rfc3490>: IDNA specification * <https://tools.ietf.org/html/rfc3492>: Punycode/Bootstrap specification * [adapt](requests_idnaencoder/adapt) β€” Adapt the bias * [digit\_to\_char](requests_idnaencoder/digit_to_char) β€” Convert a digit to its respective character * [encode](requests_idnaencoder/encode) β€” Encode a hostname using Punycode * [is\_ascii](requests_idnaencoder/is_ascii) β€” Check whether a given string contains only ASCII characters * [nameprep](requests_idnaencoder/nameprep) β€” Prepare a string for use as an IDNA name * [punycode\_encode](requests_idnaencoder/punycode_encode) β€” RFC3492-compliant encoder * [to\_ascii](requests_idnaencoder/to_ascii) β€” Convert a UTF-8 string to an ASCII string using Punycode * [utf8\_to\_codepoints](requests_idnaencoder/utf8_to_codepoints) β€” Convert a UTF-8 string to a UCS-4 codepoint array File: `wp-includes/Requests/IDNAEncoder.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/idnaencoder.php/) ``` class Requests_IDNAEncoder { /** * ACE prefix used for IDNA * * @see https://tools.ietf.org/html/rfc3490#section-5 * @var string */ const ACE_PREFIX = 'xn--'; /**#@+ * Bootstrap constant for Punycode * * @see https://tools.ietf.org/html/rfc3492#section-5 * @var int */ const BOOTSTRAP_BASE = 36; const BOOTSTRAP_TMIN = 1; const BOOTSTRAP_TMAX = 26; const BOOTSTRAP_SKEW = 38; const BOOTSTRAP_DAMP = 700; const BOOTSTRAP_INITIAL_BIAS = 72; const BOOTSTRAP_INITIAL_N = 128; /**#@-*/ /** * Encode a hostname using Punycode * * @param string $string Hostname * @return string Punycode-encoded hostname */ public static function encode($string) { $parts = explode('.', $string); foreach ($parts as &$part) { $part = self::to_ascii($part); } return implode('.', $parts); } /** * Convert a UTF-8 string to an ASCII string using Punycode * * @throws Requests_Exception Provided string longer than 64 ASCII characters (`idna.provided_too_long`) * @throws Requests_Exception Prepared string longer than 64 ASCII characters (`idna.prepared_too_long`) * @throws Requests_Exception Provided string already begins with xn-- (`idna.provided_is_prefixed`) * @throws Requests_Exception Encoded string longer than 64 ASCII characters (`idna.encoded_too_long`) * * @param string $string ASCII or UTF-8 string (max length 64 characters) * @return string ASCII string */ 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); } /** * Check whether a given string contains only ASCII characters * * @internal (Testing found regex was the fastest implementation) * * @param string $string * @return bool Is the string ASCII-only? */ protected static function is_ascii($string) { return (preg_match('/(?:[^\x00-\x7F])/', $string) !== 1); } /** * Prepare a string for use as an IDNA name * * @todo Implement this based on RFC 3491 and the newer 5891 * @param string $string * @return string Prepared string */ protected static function nameprep($string) { return $string; } /** * Convert a UTF-8 string to a UCS-4 codepoint array * * Based on Requests_IRI::replace_invalid_with_pct_encoding() * * @throws Requests_Exception Invalid UTF-8 codepoint (`idna.invalidcodepoint`) * @param string $input * @return array Unicode code points */ 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; } /** * RFC3492-compliant encoder * * @internal Pseudo-code from Section 6.3 is commented with "#" next to relevant code * @throws Requests_Exception On character outside of the domain (never happens with Punycode) (`idna.character_outside_domain`) * * @param string $input UTF-8 encoded string to encode * @return string Punycode-encoded string */ 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; } /** * Convert a digit to its respective character * * @see https://tools.ietf.org/html/rfc3492#section-5 * @throws Requests_Exception On invalid digit (`idna.invalid_digit`) * * @param int $digit Digit in the range 0-35 * @return string Single character corresponding to digit */ 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); } /** * Adapt the bias * * @see https://tools.ietf.org/html/rfc3492#section-6.1 * @param int $delta * @param int $numpoints * @param bool $firsttime * @return int New bias * * function adapt(delta,numpoints,firsttime): */ 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)); } } ``` wordpress class Theme_Upgrader_Skin {} class Theme\_Upgrader\_Skin {} ============================== Theme Upgrader Skin for WordPress Theme Upgrades. * [WP\_Upgrader\_Skin](wp_upgrader_skin) * [\_\_construct](theme_upgrader_skin/__construct) β€” Constructor. * [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/) ``` class Theme_Upgrader_Skin extends WP_Upgrader_Skin { /** * Holds the theme slug in the Theme Directory. * * @since 2.8.0 * * @var string */ public $theme = ''; /** * Constructor. * * Sets up the theme upgrader skin. * * @since 2.8.0 * * @param array $args Optional. The theme upgrader skin arguments to * override default options. Default empty array. */ 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 ); } /** * Action to perform following a single theme update. * * @since 2.8.0 */ 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 &#8220;%s&#8221;' ), $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 &#8220;%s&#8221;' ), $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 &#8220;%s&#8221;', '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 ) ); } } } ``` | Uses | Description | | --- | --- | | [WP\_Upgrader\_Skin](wp_upgrader_skin) wp-admin/includes/class-wp-upgrader-skin.php | Generic Skin for the WordPress Upgrader classes. This skin is designed to be extended for specific purposes. | | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php. | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. | wordpress class Requests_Exception_HTTP_406 {} class Requests\_Exception\_HTTP\_406 {} ======================================= Exception for 406 Not Acceptable responses File: `wp-includes/Requests/Exception/HTTP/406.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/406.php/) ``` class Requests_Exception_HTTP_406 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 406; /** * Reason phrase * * @var string */ protected $reason = 'Not Acceptable'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_REST_Post_Format_Search_Handler {} class WP\_REST\_Post\_Format\_Search\_Handler {} ================================================ Core class representing a search handler for post formats in the REST API. * [WP\_REST\_Search\_Handler](wp_rest_search_handler) * [\_\_construct](wp_rest_post_format_search_handler/__construct) β€” Constructor. * [prepare\_item](wp_rest_post_format_search_handler/prepare_item) β€” Prepares the search result for a given ID. * [prepare\_item\_links](wp_rest_post_format_search_handler/prepare_item_links) β€” Prepares links for the search result. * [search\_items](wp_rest_post_format_search_handler/search_items) β€” Searches the object type content for a given search request. File: `wp-includes/rest-api/search/class-wp-rest-post-format-search-handler.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/search/class-wp-rest-post-format-search-handler.php/) ``` class WP_REST_Post_Format_Search_Handler extends WP_REST_Search_Handler { /** * Constructor. * * @since 5.6.0 */ public function __construct() { $this->type = 'post-format'; } /** * Searches the object type content for a given search request. * * @since 5.6.0 * * @param WP_REST_Request $request Full REST request. * @return array Associative array containing an `WP_REST_Search_Handler::RESULT_IDS` containing * an array of found IDs and `WP_REST_Search_Handler::RESULT_TOTAL` containing the * total count for the matching search results. */ public function search_items( WP_REST_Request $request ) { $format_strings = get_post_format_strings(); $format_slugs = array_keys( $format_strings ); $query_args = array(); if ( ! empty( $request['search'] ) ) { $query_args['search'] = $request['search']; } /** * Filters the query arguments for a REST API search request. * * Enables adding extra arguments or setting defaults for a post format search request. * * @since 5.6.0 * * @param array $query_args Key value array of query var to query value. * @param WP_REST_Request $request The request used. */ $query_args = apply_filters( 'rest_post_format_search_query', $query_args, $request ); $found_ids = array(); foreach ( $format_slugs as $index => $format_slug ) { if ( ! empty( $query_args['search'] ) ) { $format_string = get_post_format_string( $format_slug ); $format_slug_match = stripos( $format_slug, $query_args['search'] ) !== false; $format_string_match = stripos( $format_string, $query_args['search'] ) !== false; if ( ! $format_slug_match && ! $format_string_match ) { continue; } } $format_link = get_post_format_link( $format_slug ); if ( $format_link ) { $found_ids[] = $format_slug; } } $page = (int) $request['page']; $per_page = (int) $request['per_page']; return array( self::RESULT_IDS => array_slice( $found_ids, ( $page - 1 ) * $per_page, $per_page ), self::RESULT_TOTAL => count( $found_ids ), ); } /** * Prepares the search result for a given ID. * * @since 5.6.0 * * @param string $id Item ID, the post format slug. * @param array $fields Fields to include for the item. * @return array Associative array containing all fields for the item. */ public function prepare_item( $id, array $fields ) { $data = array(); if ( in_array( WP_REST_Search_Controller::PROP_ID, $fields, true ) ) { $data[ WP_REST_Search_Controller::PROP_ID ] = $id; } if ( in_array( WP_REST_Search_Controller::PROP_TITLE, $fields, true ) ) { $data[ WP_REST_Search_Controller::PROP_TITLE ] = get_post_format_string( $id ); } if ( in_array( WP_REST_Search_Controller::PROP_URL, $fields, true ) ) { $data[ WP_REST_Search_Controller::PROP_URL ] = get_post_format_link( $id ); } if ( in_array( WP_REST_Search_Controller::PROP_TYPE, $fields, true ) ) { $data[ WP_REST_Search_Controller::PROP_TYPE ] = $this->type; } return $data; } /** * Prepares links for the search result. * * @since 5.6.0 * * @param string $id Item ID, the post format slug. * @return array Links for the given item. */ public function prepare_item_links( $id ) { return array(); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Search\_Handler](wp_rest_search_handler) wp-includes/rest-api/search/class-wp-rest-search-handler.php | Core base class representing a search handler for an object type in the REST API. | | Version | Description | | --- | --- | | [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
programming_docs
wordpress class WP_Customize_Partial {} class WP\_Customize\_Partial {} =============================== Core Customizer class for implementing selective refresh partials. Representation of a rendered region in the previewed page that gets selectively refreshed when an associated setting is changed. This class is analogous of [WP\_Customize\_Control](wp_customize_control). * [\_\_construct](wp_customize_partial/__construct) β€” Constructor. * [check\_capabilities](wp_customize_partial/check_capabilities) β€” Checks if the user can refresh this partial. * [id\_data](wp_customize_partial/id_data) β€” Retrieves parsed ID data for multidimensional setting. * [json](wp_customize_partial/json) β€” Retrieves the data to export to the client via JSON. * [render](wp_customize_partial/render) β€” Renders the template partial involving the associated settings. * [render\_callback](wp_customize_partial/render_callback) β€” Default callback used when invoking WP\_Customize\_Control::render(). File: `wp-includes/customize/class-wp-customize-partial.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-partial.php/) ``` class WP_Customize_Partial { /** * Component. * * @since 4.5.0 * @var WP_Customize_Selective_Refresh */ public $component; /** * Unique identifier for the partial. * * If the partial is used to display a single setting, this would generally * be the same as the associated setting's ID. * * @since 4.5.0 * @var string */ public $id; /** * Parsed ID. * * @since 4.5.0 * @var array { * @type string $base ID base. * @type array $keys Keys for multidimensional. * } */ protected $id_data = array(); /** * Type of this partial. * * @since 4.5.0 * @var string */ public $type = 'default'; /** * The jQuery selector to find the container element for the partial. * * @since 4.5.0 * @var string */ public $selector; /** * IDs for settings tied to the partial. * * @since 4.5.0 * @var string[] */ public $settings; /** * The ID for the setting that this partial is primarily responsible for rendering. * * If not supplied, it will default to the ID of the first setting. * * @since 4.5.0 * @var string */ public $primary_setting; /** * Capability required to edit this partial. * * Normally this is empty and the capability is derived from the capabilities * of the associated `$settings`. * * @since 4.5.0 * @var string */ public $capability; /** * Render callback. * * @since 4.5.0 * * @see WP_Customize_Partial::render() * @var callable Callback is called with one argument, the instance of * WP_Customize_Partial. The callback can either echo the * partial or return the partial as a string, or return false if error. */ public $render_callback; /** * Whether the container element is included in the partial, or if only the contents are rendered. * * @since 4.5.0 * @var bool */ public $container_inclusive = false; /** * Whether to refresh the entire preview in case a partial cannot be refreshed. * * A partial render is considered a failure if the render_callback returns false. * * @since 4.5.0 * @var bool */ public $fallback_refresh = true; /** * Constructor. * * Supplied `$args` override class property defaults. * * If `$args['settings']` is not defined, use the $id as the setting ID. * * @since 4.5.0 * * @param WP_Customize_Selective_Refresh $component Customize Partial Refresh plugin instance. * @param string $id Control ID. * @param array $args { * Optional. Array of properties for the new Partials object. Default empty array. * * @type string $type Type of the partial to be created. * @type string $selector The jQuery selector to find the container element for the partial, that is, * a partial's placement. * @type string[] $settings IDs for settings tied to the partial. If undefined, `$id` will be used. * @type string $primary_setting The ID for the setting that this partial is primarily responsible for * rendering. If not supplied, it will default to the ID of the first setting. * @type string $capability Capability required to edit this partial. * Normally this is empty and the capability is derived from the capabilities * of the associated `$settings`. * @type callable $render_callback Render callback. * Callback is called with one argument, the instance of WP_Customize_Partial. * The callback can either echo the partial or return the partial as a string, * or return false if error. * @type bool $container_inclusive Whether the container element is included in the partial, or if only * the contents are rendered. * @type bool $fallback_refresh Whether to refresh the entire preview in case a partial cannot be refreshed. * A partial render is considered a failure if the render_callback returns * false. * } */ public function __construct( WP_Customize_Selective_Refresh $component, $id, $args = array() ) { $keys = array_keys( get_object_vars( $this ) ); foreach ( $keys as $key ) { if ( isset( $args[ $key ] ) ) { $this->$key = $args[ $key ]; } } $this->component = $component; $this->id = $id; $this->id_data['keys'] = preg_split( '/\[/', str_replace( ']', '', $this->id ) ); $this->id_data['base'] = array_shift( $this->id_data['keys'] ); if ( empty( $this->render_callback ) ) { $this->render_callback = array( $this, 'render_callback' ); } // Process settings. if ( ! isset( $this->settings ) ) { $this->settings = array( $id ); } elseif ( is_string( $this->settings ) ) { $this->settings = array( $this->settings ); } if ( empty( $this->primary_setting ) ) { $this->primary_setting = current( $this->settings ); } } /** * Retrieves parsed ID data for multidimensional setting. * * @since 4.5.0 * * @return array { * ID data for multidimensional partial. * * @type string $base ID base. * @type array $keys Keys for multidimensional array. * } */ final public function id_data() { return $this->id_data; } /** * Renders the template partial involving the associated settings. * * @since 4.5.0 * * @param array $container_context Optional. Array of context data associated with the target container (placement). * Default empty array. * @return string|array|false The rendered partial as a string, raw data array (for client-side JS template), * or false if no render applied. */ final public function render( $container_context = array() ) { $partial = $this; $rendered = false; if ( ! empty( $this->render_callback ) ) { ob_start(); $return_render = call_user_func( $this->render_callback, $this, $container_context ); $ob_render = ob_get_clean(); if ( null !== $return_render && '' !== $ob_render ) { _doing_it_wrong( __FUNCTION__, __( 'Partial render must echo the content or return the content string (or array), but not both.' ), '4.5.0' ); } /* * Note that the string return takes precedence because the $ob_render may just\ * include PHP warnings or notices. */ $rendered = null !== $return_render ? $return_render : $ob_render; } /** * Filters partial rendering. * * @since 4.5.0 * * @param string|array|false $rendered The partial value. Default false. * @param WP_Customize_Partial $partial WP_Customize_Setting instance. * @param array $container_context Optional array of context data associated with * the target container. */ $rendered = apply_filters( 'customize_partial_render', $rendered, $partial, $container_context ); /** * Filters partial rendering for a specific partial. * * The dynamic portion of the hook name, `$partial->ID` refers to the partial ID. * * @since 4.5.0 * * @param string|array|false $rendered The partial value. Default false. * @param WP_Customize_Partial $partial WP_Customize_Setting instance. * @param array $container_context Optional array of context data associated with * the target container. */ $rendered = apply_filters( "customize_partial_render_{$partial->id}", $rendered, $partial, $container_context ); return $rendered; } /** * Default callback used when invoking WP_Customize_Control::render(). * * Note that this method may echo the partial *or* return the partial as * a string or array, but not both. Output buffering is performed when this * is called. Subclasses can override this with their specific logic, or they * may provide an 'render_callback' argument to the constructor. * * This method may return an HTML string for straight DOM injection, or it * may return an array for supporting Partial JS subclasses to render by * applying to client-side templating. * * @since 4.5.0 * * @param WP_Customize_Partial $partial Partial. * @param array $context Context. * @return string|array|false */ public function render_callback( WP_Customize_Partial $partial, $context = array() ) { unset( $partial, $context ); return false; } /** * Retrieves the data to export to the client via JSON. * * @since 4.5.0 * * @return array Array of parameters passed to the JavaScript. */ public function json() { $exports = array( 'settings' => $this->settings, 'primarySetting' => $this->primary_setting, 'selector' => $this->selector, 'type' => $this->type, 'fallbackRefresh' => $this->fallback_refresh, 'containerInclusive' => $this->container_inclusive, ); return $exports; } /** * Checks if the user can refresh this partial. * * Returns false if the user cannot manipulate one of the associated settings, * or if one of the associated settings does not exist. * * @since 4.5.0 * * @return bool False if user can't edit one of the related settings, * or if one of the associated settings does not exist. */ final public function check_capabilities() { if ( ! empty( $this->capability ) && ! current_user_can( $this->capability ) ) { return false; } foreach ( $this->settings as $setting_id ) { $setting = $this->component->manager->get_setting( $setting_id ); if ( ! $setting || ! $setting->check_capabilities() ) { return false; } } return true; } } ``` | Version | Description | | --- | --- | | [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. | wordpress class WP_Customize_Control {} class WP\_Customize\_Control {} =============================== Customize Control class. This class is used with the Theme Customization API to render an input control on the Theme Customizer in WordPress 3.4 or newer. $manager (*[WP\_Customize\_Manager](wp_customize_manager)*) (*required*) Customizer bootstrap instance. Default: *None* $id ([*string*](https://codex.wordpress.org/How_to_Pass_Tag_Parameters#String "How to Pass Tag Parameters")) (*required*) Control ID. Default: *None* $args (*array*) (*required*) An associative array containing arguments for the setting. Default: *None* settings All settings tied to the control. If undefined, `$id` will be used. setting The primary setting for the control (if there is one). priority Order priority to load the control. Default 10. section Section the control belongs to. Default empty. label Label for the control. Default empty. description Description for the control. Default empty. choices List of choices for β€˜radio’ or β€˜select’ type controls, where values are the keys, and labels are the values. Default empty array. input\_attrs List 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. Default empty array. type Control 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’. With this class you can create the following input types: * text (default) * checkbox * radio (requires choices array in $args) * select (requires choices array in $args) * dropdown-pages * textarea (since WordPress 4.0) Note: Since WordPress 4.0, input types such as ’email’, β€˜url’, β€˜number’, β€˜hidden’ and β€˜date’ are supported implicitly as variations of the β€˜text’ input type. * [\_\_construct](wp_customize_control/__construct) β€” Constructor. * [active](wp_customize_control/active) β€” Check whether control is active to current Customizer preview. * [active\_callback](wp_customize_control/active_callback) β€” Default callback used when invoking WP\_Customize\_Control::active(). * [check\_capabilities](wp_customize_control/check_capabilities) β€” Checks if the user can use this control. * [content\_template](wp_customize_control/content_template) β€” An Underscore (JS) template for this control's content (but not its container). * [enqueue](wp_customize_control/enqueue) β€” Enqueue control related scripts/styles. * [get\_content](wp_customize_control/get_content) β€” Get the control's content for insertion into the Customizer pane. * [get\_link](wp_customize_control/get_link) β€” Get the data link attribute for a setting. * [input\_attrs](wp_customize_control/input_attrs) β€” Render the custom attributes for the control's input element. * [json](wp_customize_control/json) β€” Get the data to export to the client via JSON. * [link](wp_customize_control/link) β€” Render the data link attribute for the control's input element. * [maybe\_render](wp_customize_control/maybe_render) β€” Check capabilities and render the control. * [print\_template](wp_customize_control/print_template) β€” Render the control's JS template. * [render](wp_customize_control/render) β€” Renders the control wrapper and calls $this->render\_content() for the internals. * [render\_content](wp_customize_control/render_content) β€” Render the control's content. * [to\_json](wp_customize_control/to_json) β€” Refresh the parameters passed to the JavaScript via JSON. * [value](wp_customize_control/value) β€” Fetch a setting's value. File: `wp-includes/class-wp-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-control.php/) ``` class WP_Customize_Control { /** * Incremented with each new class instantiation, then stored in $instance_number. * * Used when sorting two instances whose priorities are equal. * * @since 4.1.0 * @var int */ protected static $instance_count = 0; /** * Order in which this instance was created in relation to other instances. * * @since 4.1.0 * @var int */ public $instance_number; /** * Customizer manager. * * @since 3.4.0 * @var WP_Customize_Manager */ public $manager; /** * Control ID. * * @since 3.4.0 * @var string */ public $id; /** * All settings tied to the control. * * @since 3.4.0 * @var array */ public $settings; /** * The primary setting for the control (if there is one). * * @since 3.4.0 * @var string|WP_Customize_Setting|null */ public $setting = 'default'; /** * Capability required to use this control. * * Normally this is empty and the capability is derived from the capabilities * of the associated `$settings`. * * @since 4.5.0 * @var string */ public $capability; /** * Order priority to load the control in Customizer. * * @since 3.4.0 * @var int */ public $priority = 10; /** * Section the control belongs to. * * @since 3.4.0 * @var string */ public $section = ''; /** * Label for the control. * * @since 3.4.0 * @var string */ public $label = ''; /** * Description for the control. * * @since 4.0.0 * @var string */ public $description = ''; /** * List of choices for 'radio' or 'select' type controls, where values are the keys, and labels are the values. * * @since 3.4.0 * @var array */ public $choices = array(); /** * List 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. * * @since 4.0.0 * @var array */ public $input_attrs = array(); /** * Show UI for adding new content, currently only used for the dropdown-pages control. * * @since 4.7.0 * @var bool */ public $allow_addition = false; /** * @deprecated It is better to just call the json() method * @since 3.4.0 * @var array */ public $json = array(); /** * Control's Type. * * @since 3.4.0 * @var string */ public $type = 'text'; /** * Callback. * * @since 4.0.0 * * @see WP_Customize_Control::active() * * @var callable Callback is called with one argument, the instance of * WP_Customize_Control, and returns bool to indicate whether * the control is active (such as it relates to the URL * currently being previewed). */ public $active_callback = ''; /** * Constructor. * * Supplied `$args` override class property defaults. * * If `$args['settings']` is not defined, use the `$id` as the setting ID. * * @since 3.4.0 * * @param WP_Customize_Manager $manager Customizer bootstrap instance. * @param string $id Control ID. * @param array $args { * Optional. Array of properties for the new Control object. Default empty array. * * @type int $instance_number Order in which this instance was created in relation * to other instances. * @type WP_Customize_Manager $manager Customizer bootstrap instance. * @type string $id Control ID. * @type array $settings All settings tied to the control. If undefined, `$id` will * be used. * @type string $setting The primary setting for the control (if there is one). * Default 'default'. * @type string $capability Capability required to use this control. Normally this is empty * and the capability is derived from `$settings`. * @type int $priority Order priority to load the control. Default 10. * @type string $section Section the control belongs to. Default empty. * @type string $label Label for the control. Default empty. * @type string $description Description for the control. Default empty. * @type array $choices List of choices for 'radio' or 'select' type controls, where * values are the keys, and labels are the values. * Default empty array. * @type array $input_attrs List 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. Default empty array. * @type bool $allow_addition Show UI for adding new content, currently only used for the * dropdown-pages control. Default false. * @type array $json Deprecated. Use WP_Customize_Control::json() instead. * @type string $type Control 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'. * @type callable $active_callback Active callback. * } */ 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; } /** * Enqueue control related scripts/styles. * * @since 3.4.0 */ public function enqueue() {} /** * Check whether control is active to current Customizer preview. * * @since 4.0.0 * * @return bool Whether the control is active to the current preview. */ 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; } /** * Default callback used when invoking WP_Customize_Control::active(). * * Subclasses can override this with their specific logic, or they may * provide an 'active_callback' argument to the constructor. * * @since 4.0.0 * * @return true Always true. */ public function active_callback() { return true; } /** * Fetch a setting's value. * Grabs the main setting by default. * * @since 3.4.0 * * @param string $setting_key * @return mixed The requested setting's value, if the setting exists. */ final public function value( $setting_key = 'default' ) { if ( isset( $this->settings[ $setting_key ] ) ) { return $this->settings[ $setting_key ]->value(); } } /** * Refresh the parameters passed to the JavaScript via JSON. * * @since 3.4.0 */ 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; } } /** * Get the data to export to the client via JSON. * * @since 4.1.0 * * @return array Array of parameters passed to the JavaScript. */ public function json() { $this->to_json(); return $this->json; } /** * 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. * * @since 3.4.0 * * @return bool False if theme doesn't support the control or user doesn't have the required permissions, otherwise true. */ 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; } /** * Get the control's content for insertion into the Customizer pane. * * @since 4.1.0 * * @return string Contents of the control. */ final public function get_content() { ob_start(); $this->maybe_render(); return trim( ob_get_clean() ); } /** * Check capabilities and render the control. * * @since 3.4.0 * @uses WP_Customize_Control::render() */ 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(); } /** * Renders the control wrapper and calls $this->render_content() for the internals. * * @since 3.4.0 */ 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>'; } /** * Get the data link attribute for a setting. * * @since 3.4.0 * @since 4.9.0 Return a `data-customize-setting-key-link` attribute if a setting is not registered for the supplied setting key. * * @param string $setting_key * @return 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. */ 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 ) . '"'; } } /** * Render the data link attribute for the control's input element. * * @since 3.4.0 * @uses WP_Customize_Control::get_link() * * @param string $setting_key */ public function link( $setting_key = 'default' ) { echo $this->get_link( $setting_key ); } /** * Render the custom attributes for the control's input element. * * @since 4.0.0 */ public function input_attrs() { foreach ( $this->input_attrs as $attr => $value ) { echo $attr . '="' . esc_attr( $value ) . '" '; } } /** * 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(). * * @since 3.4.0 */ 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 = __( '&mdash; Select &mdash;' ); $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&hellip;' ); ?>"> <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; } } /** * 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(). * * In the future, this will also print the template for the control's container * element and be override-able. * * @since 4.1.0 */ 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 } /** * 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(). * * @see WP_Customize_Control::print_template() * * @since 4.1.0 */ protected function content_template() {} } ``` | Used By | Description | | --- | --- | | [WP\_Sidebar\_Block\_Editor\_Control](wp_sidebar_block_editor_control) wp-includes/customize/class-wp-sidebar-block-editor-control.php | Core class used to implement the widgets block editor control in the customizer. | | [WP\_Customize\_Nav\_Menu\_Locations\_Control](wp_customize_nav_menu_locations_control) wp-includes/customize/class-wp-customize-nav-menu-locations-control.php | Customize Nav Menu Locations Control Class. | | [WP\_Customize\_Code\_Editor\_Control](wp_customize_code_editor_control) wp-includes/customize/class-wp-customize-code-editor-control.php | Customize Code Editor Control class. | | [WP\_Customize\_Date\_Time\_Control](wp_customize_date_time_control) wp-includes/customize/class-wp-customize-date-time-control.php | Customize Date Time Control class. | | [WP\_Customize\_Background\_Position\_Control](wp_customize_background_position_control) wp-includes/customize/class-wp-customize-background-position-control.php | Customize Background Position Control class. | | [WP\_Customize\_Nav\_Menu\_Auto\_Add\_Control](wp_customize_nav_menu_auto_add_control) wp-includes/customize/class-wp-customize-nav-menu-auto-add-control.php | Customize control to represent the auto\_add field for a given menu. | | [WP\_Customize\_New\_Menu\_Control](wp_customize_new_menu_control) wp-includes/customize/class-wp-customize-new-menu-control.php | Customize control class for new menus. | | [WP\_Customize\_Nav\_Menu\_Location\_Control](wp_customize_nav_menu_location_control) wp-includes/customize/class-wp-customize-nav-menu-location-control.php | Customize Menu Location Control Class. | | [WP\_Customize\_Nav\_Menu\_Name\_Control](wp_customize_nav_menu_name_control) wp-includes/customize/class-wp-customize-nav-menu-name-control.php | Customize control to represent the name field for a given menu. | | [WP\_Customize\_Nav\_Menu\_Control](wp_customize_nav_menu_control) wp-includes/customize/class-wp-customize-nav-menu-control.php | Customize Nav Menu Control Class. | | [WP\_Customize\_Nav\_Menu\_Item\_Control](wp_customize_nav_menu_item_control) wp-includes/customize/class-wp-customize-nav-menu-item-control.php | Customize control to represent the name field for a given menu. | | [WP\_Customize\_Theme\_Control](wp_customize_theme_control) wp-includes/customize/class-wp-customize-theme-control.php | Customize Theme Control class. | | [WP\_Customize\_Media\_Control](wp_customize_media_control) wp-includes/customize/class-wp-customize-media-control.php | Customize Media Control class. | | [WP\_Widget\_Area\_Customize\_Control](wp_widget_area_customize_control) wp-includes/customize/class-wp-widget-area-customize-control.php | Widget Area Customize Control class. | | [WP\_Widget\_Form\_Customize\_Control](wp_widget_form_customize_control) wp-includes/customize/class-wp-widget-form-customize-control.php | Widget Form Customize Control class. | | [WP\_Customize\_Color\_Control](wp_customize_color_control) wp-includes/customize/class-wp-customize-color-control.php | Customize Color Control class. | | Version | Description | | --- | --- | | [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
programming_docs
wordpress class Requests_Exception_HTTP_304 {} class Requests\_Exception\_HTTP\_304 {} ======================================= Exception for 304 Not Modified responses File: `wp-includes/Requests/Exception/HTTP/304.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/304.php/) ``` class Requests_Exception_HTTP_304 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 304; /** * Reason phrase * * @var string */ protected $reason = 'Not Modified'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_Block_Template {} class WP\_Block\_Template {} ============================ Class representing a block template. File: `wp-includes/class-wp-block-template.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-template.php/) ``` class WP_Block_Template { /** * Type: wp_template. * * @since 5.8.0 * @var string */ public $type; /** * Theme. * * @since 5.8.0 * @var string */ public $theme; /** * Template slug. * * @since 5.8.0 * @var string */ public $slug; /** * ID. * * @since 5.8.0 * @var string */ public $id; /** * Title. * * @since 5.8.0 * @var string */ public $title = ''; /** * Content. * * @since 5.8.0 * @var string */ public $content = ''; /** * Description. * * @since 5.8.0 * @var string */ public $description = ''; /** * Source of the content. `theme` and `custom` is used for now. * * @since 5.8.0 * @var string */ public $source = 'theme'; /** * Origin of the content when the content has been customized. * When customized, origin takes on the value of source and source becomes * 'custom'. * * @since 5.9.0 * @var string */ public $origin; /** * Post ID. * * @since 5.8.0 * @var int|null */ public $wp_id; /** * Template Status. * * @since 5.8.0 * @var string */ public $status; /** * Whether a template is, or is based upon, an existing template file. * * @since 5.8.0 * @var bool */ public $has_theme_file; /** * Whether a template is a custom template. * * @since 5.9.0 * * @var bool */ public $is_custom = true; /** * Author. * * A value of 0 means no author. * * @since 5.9.0 * @var int */ public $author; /** * Post types. * * @since 5.9.0 * @var array */ public $post_types; /** * Area. * * @since 5.9.0 * @var string */ public $area; } ``` | Version | Description | | --- | --- | | [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. | wordpress class Requests_Response_Headers {} class Requests\_Response\_Headers {} ==================================== Case-insensitive dictionary, suitable for HTTP headers * [flatten](requests_response_headers/flatten) β€” Flattens a value into a string * [getIterator](requests_response_headers/getiterator) β€” Get an iterator for the data * [getValues](requests_response_headers/getvalues) β€” Get all values for a given header * [offsetGet](requests_response_headers/offsetget) β€” Get the given header * [offsetSet](requests_response_headers/offsetset) β€” Set the given item File: `wp-includes/Requests/Response/Headers.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/response/headers.php/) ``` class Requests_Response_Headers extends Requests_Utility_CaseInsensitiveDictionary { /** * Get the given header * * Unlike {@see self::getValues()}, this returns a string. If there are * multiple values, it concatenates them with a comma as per RFC2616. * * Avoid using this where commas may be used unquoted in values, such as * Set-Cookie headers. * * @param string $key * @return string|null Header value */ public function offsetGet($key) { $key = strtolower($key); if (!isset($this->data[$key])) { return null; } return $this->flatten($this->data[$key]); } /** * Set the given item * * @throws Requests_Exception On attempting to use dictionary as list (`invalidset`) * * @param string $key Item name * @param string $value Item value */ public function offsetSet($key, $value) { if ($key === null) { throw new Requests_Exception('Object is a dictionary, not a list', 'invalidset'); } $key = strtolower($key); if (!isset($this->data[$key])) { $this->data[$key] = array(); } $this->data[$key][] = $value; } /** * Get all values for a given header * * @param string $key * @return array|null Header values */ public function getValues($key) { $key = strtolower($key); if (!isset($this->data[$key])) { return null; } return $this->data[$key]; } /** * Flattens a value into a string * * Converts an array into a string by imploding values with a comma, as per * RFC2616's rules for folding headers. * * @param string|array $value Value to flatten * @return string Flattened value */ public function flatten($value) { if (is_array($value)) { $value = implode(',', $value); } return $value; } /** * Get an iterator for the data * * Converts the internal * @return ArrayIterator */ public function getIterator() { return new Requests_Utility_FilteredIterator($this->data, array($this, 'flatten')); } } ``` | Uses | Description | | --- | --- | | [Requests\_Utility\_CaseInsensitiveDictionary](requests_utility_caseinsensitivedictionary) wp-includes/Requests/Utility/CaseInsensitiveDictionary.php | Case-insensitive dictionary, suitable for HTTP headers | wordpress class WP_Post_Type {} class WP\_Post\_Type {} ======================= Core class used for interacting with post types. * [register\_post\_type()](../functions/register_post_type) * [\_\_construct](wp_post_type/__construct) β€” Constructor. * [add\_hooks](wp_post_type/add_hooks) β€” Adds the future post hook action for the post type. * [add\_rewrite\_rules](wp_post_type/add_rewrite_rules) β€” Adds the necessary rewrite rules for the post type. * [add\_supports](wp_post_type/add_supports) β€” Sets the features support for the post type. * [get\_default\_labels](wp_post_type/get_default_labels) β€” Returns the default labels for post types. * [get\_rest\_controller](wp_post_type/get_rest_controller) β€” Gets the REST API controller for this post type. * [register\_meta\_boxes](wp_post_type/register_meta_boxes) β€” Registers the post type meta box if a custom callback was specified. * [register\_taxonomies](wp_post_type/register_taxonomies) β€” Registers the taxonomies for the post type. * [remove\_hooks](wp_post_type/remove_hooks) β€” Removes the future post hook action for the post type. * [remove\_rewrite\_rules](wp_post_type/remove_rewrite_rules) β€” Removes any rewrite rules, permastructs, and rules for the post type. * [remove\_supports](wp_post_type/remove_supports) β€” Removes the features support for the post type. * [reset\_default\_labels](wp_post_type/reset_default_labels) β€” Resets the cache for the default labels. * [set\_props](wp_post_type/set_props) β€” Sets post type properties. * [unregister\_meta\_boxes](wp_post_type/unregister_meta_boxes) β€” Unregisters the post type meta box if a custom callback was specified. * [unregister\_taxonomies](wp_post_type/unregister_taxonomies) β€” Removes the post type from all taxonomies. File: `wp-includes/class-wp-post-type.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-post-type.php/) ``` final class WP_Post_Type { /** * Post type key. * * @since 4.6.0 * @var string $name */ public $name; /** * Name of the post type shown in the menu. Usually plural. * * @since 4.6.0 * @var string $label */ public $label; /** * Labels object for this post type. * * If not set, post labels are inherited for non-hierarchical types * and page labels for hierarchical ones. * * @see get_post_type_labels() * * @since 4.6.0 * @var stdClass $labels */ public $labels; /** * Default labels. * * @since 6.0.0 * @var (string|null)[][] $default_labels */ protected static $default_labels = array(); /** * A short descriptive summary of what the post type is. * * Default empty. * * @since 4.6.0 * @var string $description */ public $description = ''; /** * Whether a post type is intended for use publicly either via the admin interface or by front-end users. * * While the default settings of $exclude_from_search, $publicly_queryable, $show_ui, and $show_in_nav_menus * are inherited from public, each does not rely on this relationship and controls a very specific intention. * * Default false. * * @since 4.6.0 * @var bool $public */ public $public = false; /** * Whether the post type is hierarchical (e.g. page). * * Default false. * * @since 4.6.0 * @var bool $hierarchical */ public $hierarchical = false; /** * Whether to exclude posts with this post type from front end search * results. * * Default is the opposite value of $public. * * @since 4.6.0 * @var bool $exclude_from_search */ public $exclude_from_search = null; /** * Whether queries can be performed on the front end for the post type as part of `parse_request()`. * * Endpoints would include: * * - `?post_type={post_type_key}` * - `?{post_type_key}={single_post_slug}` * - `?{post_type_query_var}={single_post_slug}` * * Default is the value of $public. * * @since 4.6.0 * @var bool $publicly_queryable */ public $publicly_queryable = null; /** * Whether to generate and allow a UI for managing this post type in the admin. * * Default is the value of $public. * * @since 4.6.0 * @var bool $show_ui */ public $show_ui = null; /** * Where to show the post type in the admin menu. * * To work, $show_ui must be true. If true, the post type is shown in its own top level menu. If false, no menu is * shown. If a string of an existing top level menu ('tools.php' or 'edit.php?post_type=page', for example), the * post type will be placed as a sub-menu of that. * * Default is the value of $show_ui. * * @since 4.6.0 * @var bool|string $show_in_menu */ public $show_in_menu = null; /** * Makes this post type available for selection in navigation menus. * * Default is the value $public. * * @since 4.6.0 * @var bool $show_in_nav_menus */ public $show_in_nav_menus = null; /** * Makes this post type available via the admin bar. * * Default is the value of $show_in_menu. * * @since 4.6.0 * @var bool $show_in_admin_bar */ public $show_in_admin_bar = null; /** * The position in the menu order the post type should appear. * * To work, $show_in_menu must be true. Default null (at the bottom). * * @since 4.6.0 * @var int $menu_position */ public $menu_position = null; /** * The URL or reference to the icon to be used for this menu. * * Pass a base64-encoded SVG using a data URI, which will be colored to match the color scheme. * This should begin with 'data:image/svg+xml;base64,'. Pass the name of a Dashicons helper class * to use a font icon, e.g. 'dashicons-chart-pie'. Pass 'none' to leave div.wp-menu-image empty * so an icon can be added via CSS. * * Defaults to use the posts icon. * * @since 4.6.0 * @var string $menu_icon */ public $menu_icon = null; /** * The string to use to build the read, edit, and delete capabilities. * * May be passed as an array to allow for alternative plurals when using * this argument as a base to construct the capabilities, e.g. * array( 'story', 'stories' ). Default 'post'. * * @since 4.6.0 * @var string $capability_type */ public $capability_type = 'post'; /** * Whether to use the internal default meta capability handling. * * Default false. * * @since 4.6.0 * @var bool $map_meta_cap */ public $map_meta_cap = false; /** * Provide a callback function that sets up the meta boxes for the edit form. * * Do `remove_meta_box()` and `add_meta_box()` calls in the callback. Default null. * * @since 4.6.0 * @var callable $register_meta_box_cb */ public $register_meta_box_cb = null; /** * An array of taxonomy identifiers that will be registered for the post type. * * Taxonomies can be registered later with `register_taxonomy()` or `register_taxonomy_for_object_type()`. * * Default empty array. * * @since 4.6.0 * @var string[] $taxonomies */ public $taxonomies = array(); /** * Whether there should be post type archives, or if a string, the archive slug to use. * * Will generate the proper rewrite rules if $rewrite is enabled. Default false. * * @since 4.6.0 * @var bool|string $has_archive */ public $has_archive = false; /** * Sets the query_var key for this post type. * * Defaults to $post_type key. If false, a post type cannot be loaded at `?{query_var}={post_slug}`. * If specified as a string, the query `?{query_var_string}={post_slug}` will be valid. * * @since 4.6.0 * @var string|bool $query_var */ public $query_var; /** * Whether to allow this post type to be exported. * * Default true. * * @since 4.6.0 * @var bool $can_export */ public $can_export = true; /** * Whether to delete posts of this type when deleting a user. * * - If true, posts of this type belonging to the user will be moved to Trash when the user is deleted. * - If false, posts of this type belonging to the user will *not* be trashed or deleted. * - If not set (the default), posts are trashed if post type supports the 'author' feature. * Otherwise posts are not trashed or deleted. * * Default null. * * @since 4.6.0 * @var bool $delete_with_user */ public $delete_with_user = null; /** * Array of blocks to use as the default initial state for an editor session. * * Each item should be an array containing block name and optional attributes. * * Default empty array. * * @link https://developer.wordpress.org/block-editor/developers/block-api/block-templates/ * * @since 5.0.0 * @var array[] $template */ public $template = array(); /** * Whether the block template should be locked if $template is set. * * - If set to 'all', the user is unable to insert new blocks, move existing blocks * and delete blocks. * - If set to 'insert', the user is able to move existing blocks but is unable to insert * new blocks and delete blocks. * * Default false. * * @link https://developer.wordpress.org/block-editor/developers/block-api/block-templates/ * * @since 5.0.0 * @var string|false $template_lock */ public $template_lock = false; /** * Whether this post type is a native or "built-in" post_type. * * Default false. * * @since 4.6.0 * @var bool $_builtin */ public $_builtin = false; /** * URL segment to use for edit link of this post type. * * Default 'post.php?post=%d'. * * @since 4.6.0 * @var string $_edit_link */ public $_edit_link = 'post.php?post=%d'; /** * Post type capabilities. * * @since 4.6.0 * @var stdClass $cap */ public $cap; /** * Triggers the handling of rewrites for this post type. * * Defaults to true, using $post_type as slug. * * @since 4.6.0 * @var array|false $rewrite */ public $rewrite; /** * The features supported by the post type. * * @since 4.6.0 * @var array|bool $supports */ public $supports; /** * Whether this post type should appear in the REST API. * * Default false. If true, standard endpoints will be registered with * respect to $rest_base and $rest_controller_class. * * @since 4.7.4 * @var bool $show_in_rest */ public $show_in_rest; /** * The base path for this post type's REST API endpoints. * * @since 4.7.4 * @var string|bool $rest_base */ public $rest_base; /** * The namespace for this post type's REST API endpoints. * * @since 5.9.0 * @var string|bool $rest_namespace */ public $rest_namespace; /** * The controller for this post type's REST API endpoints. * * Custom controllers must extend WP_REST_Controller. * * @since 4.7.4 * @var string|bool $rest_controller_class */ public $rest_controller_class; /** * The controller instance for this post type's REST API endpoints. * * Lazily computed. Should be accessed using {@see WP_Post_Type::get_rest_controller()}. * * @since 5.3.0 * @var WP_REST_Controller $rest_controller */ public $rest_controller; /** * Constructor. * * See the register_post_type() function for accepted arguments for `$args`. * * Will populate object properties from the provided arguments and assign other * default properties based on that information. * * @since 4.6.0 * * @see register_post_type() * * @param string $post_type Post type key. * @param array|string $args Optional. Array or string of arguments for registering a post type. * Default empty array. */ public function __construct( $post_type, $args = array() ) { $this->name = $post_type; $this->set_props( $args ); } /** * Sets post type properties. * * See the register_post_type() function for accepted arguments for `$args`. * * @since 4.6.0 * * @param array|string $args Array or string of arguments for registering a post type. */ public function set_props( $args ) { $args = wp_parse_args( $args ); /** * Filters the arguments for registering a post type. * * @since 4.4.0 * * @param array $args Array of arguments for registering a post type. * See the register_post_type() function for accepted arguments. * @param string $post_type Post type key. */ $args = apply_filters( 'register_post_type_args', $args, $this->name ); $post_type = $this->name; /** * Filters the arguments for registering a specific post type. * * The dynamic portion of the filter name, `$post_type`, refers to the post type key. * * Possible hook names include: * * - `register_post_post_type_args` * - `register_page_post_type_args` * * @since 6.0.0 * * @param array $args Array of arguments for registering a post type. * See the register_post_type() function for accepted arguments. * @param string $post_type Post type key. */ $args = apply_filters( "register_{$post_type}_post_type_args", $args, $this->name ); $has_edit_link = ! empty( $args['_edit_link'] ); // Args prefixed with an underscore are reserved for internal use. $defaults = array( 'labels' => array(), 'description' => '', 'public' => false, 'hierarchical' => false, 'exclude_from_search' => null, 'publicly_queryable' => null, 'show_ui' => null, 'show_in_menu' => null, 'show_in_nav_menus' => null, 'show_in_admin_bar' => null, 'menu_position' => null, 'menu_icon' => null, 'capability_type' => 'post', 'capabilities' => array(), 'map_meta_cap' => null, 'supports' => array(), 'register_meta_box_cb' => null, 'taxonomies' => array(), 'has_archive' => false, 'rewrite' => true, 'query_var' => true, 'can_export' => true, 'delete_with_user' => null, 'show_in_rest' => false, 'rest_base' => false, 'rest_namespace' => false, 'rest_controller_class' => false, 'template' => array(), 'template_lock' => false, '_builtin' => false, '_edit_link' => 'post.php?post=%d', ); $args = array_merge( $defaults, $args ); $args['name'] = $this->name; // If not set, default to the setting for 'public'. if ( null === $args['publicly_queryable'] ) { $args['publicly_queryable'] = $args['public']; } // If not set, default to the setting for 'public'. if ( null === $args['show_ui'] ) { $args['show_ui'] = $args['public']; } // 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'; } // 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 'show_in_menu'. if ( null === $args['show_in_admin_bar'] ) { $args['show_in_admin_bar'] = (bool) $args['show_in_menu']; } // 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 true if not public, false if public. if ( null === $args['exclude_from_search'] ) { $args['exclude_from_search'] = ! $args['public']; } // Back compat with quirky handling in version 3.0. #14122. if ( empty( $args['capabilities'] ) && null === $args['map_meta_cap'] && in_array( $args['capability_type'], array( 'post', 'page' ), true ) ) { $args['map_meta_cap'] = true; } // If not set, default to false. if ( null === $args['map_meta_cap'] ) { $args['map_meta_cap'] = false; } // If there's no specified edit link and no UI, remove the edit link. if ( ! $args['show_ui'] && ! $has_edit_link ) { $args['_edit_link'] = ''; } $this->cap = get_post_type_capabilities( (object) $args ); unset( $args['capabilities'] ); if ( is_array( $args['capability_type'] ) ) { $args['capability_type'] = $args['capability_type'][0]; } if ( false !== $args['query_var'] ) { if ( true === $args['query_var'] ) { $args['query_var'] = $this->name; } else { $args['query_var'] = sanitize_title_with_dashes( $args['query_var'] ); } } if ( false !== $args['rewrite'] && ( is_admin() || get_option( 'permalink_structure' ) ) ) { if ( ! is_array( $args['rewrite'] ) ) { $args['rewrite'] = array(); } if ( empty( $args['rewrite']['slug'] ) ) { $args['rewrite']['slug'] = $this->name; } if ( ! isset( $args['rewrite']['with_front'] ) ) { $args['rewrite']['with_front'] = true; } if ( ! isset( $args['rewrite']['pages'] ) ) { $args['rewrite']['pages'] = true; } if ( ! isset( $args['rewrite']['feeds'] ) || ! $args['has_archive'] ) { $args['rewrite']['feeds'] = (bool) $args['has_archive']; } if ( ! isset( $args['rewrite']['ep_mask'] ) ) { if ( isset( $args['permalink_epmask'] ) ) { $args['rewrite']['ep_mask'] = $args['permalink_epmask']; } else { $args['rewrite']['ep_mask'] = EP_PERMALINK; } } } foreach ( $args as $property_name => $property_value ) { $this->$property_name = $property_value; } $this->labels = get_post_type_labels( $this ); $this->label = $this->labels->name; } /** * Sets the features support for the post type. * * @since 4.6.0 */ public function add_supports() { if ( ! empty( $this->supports ) ) { foreach ( $this->supports as $feature => $args ) { if ( is_array( $args ) ) { add_post_type_support( $this->name, $feature, $args ); } else { add_post_type_support( $this->name, $args ); } } unset( $this->supports ); } elseif ( false !== $this->supports ) { // Add default features. add_post_type_support( $this->name, array( 'title', 'editor' ) ); } } /** * Adds the necessary rewrite rules for the post type. * * @since 4.6.0 * * @global WP_Rewrite $wp_rewrite WordPress rewrite component. * @global WP $wp Current WordPress environment instance. */ public function add_rewrite_rules() { global $wp_rewrite, $wp; if ( false !== $this->query_var && $wp && is_post_type_viewable( $this ) ) { $wp->add_query_var( $this->query_var ); } if ( false !== $this->rewrite && ( is_admin() || get_option( 'permalink_structure' ) ) ) { if ( $this->hierarchical ) { add_rewrite_tag( "%$this->name%", '(.+?)', $this->query_var ? "{$this->query_var}=" : "post_type=$this->name&pagename=" ); } else { add_rewrite_tag( "%$this->name%", '([^/]+)', $this->query_var ? "{$this->query_var}=" : "post_type=$this->name&name=" ); } if ( $this->has_archive ) { $archive_slug = true === $this->has_archive ? $this->rewrite['slug'] : $this->has_archive; if ( $this->rewrite['with_front'] ) { $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug; } else { $archive_slug = $wp_rewrite->root . $archive_slug; } add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$this->name", 'top' ); if ( $this->rewrite['feeds'] && $wp_rewrite->feeds ) { $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')'; add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$this->name" . '&feed=$matches[1]', 'top' ); add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$this->name" . '&feed=$matches[1]', 'top' ); } if ( $this->rewrite['pages'] ) { add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$this->name" . '&paged=$matches[1]', 'top' ); } } $permastruct_args = $this->rewrite; $permastruct_args['feed'] = $permastruct_args['feeds']; add_permastruct( $this->name, "{$this->rewrite['slug']}/%$this->name%", $permastruct_args ); } } /** * Registers the post type meta box if a custom callback was specified. * * @since 4.6.0 */ public function register_meta_boxes() { if ( $this->register_meta_box_cb ) { add_action( 'add_meta_boxes_' . $this->name, $this->register_meta_box_cb, 10, 1 ); } } /** * Adds the future post hook action for the post type. * * @since 4.6.0 */ public function add_hooks() { add_action( 'future_' . $this->name, '_future_post_hook', 5, 2 ); } /** * Registers the taxonomies for the post type. * * @since 4.6.0 */ public function register_taxonomies() { foreach ( $this->taxonomies as $taxonomy ) { register_taxonomy_for_object_type( $taxonomy, $this->name ); } } /** * Removes the features support for the post type. * * @since 4.6.0 * * @global array $_wp_post_type_features Post type features. */ public function remove_supports() { global $_wp_post_type_features; unset( $_wp_post_type_features[ $this->name ] ); } /** * Removes any rewrite rules, permastructs, and rules for the post type. * * @since 4.6.0 * * @global WP_Rewrite $wp_rewrite WordPress rewrite component. * @global WP $wp Current WordPress environment instance. * @global array $post_type_meta_caps Used to remove meta capabilities. */ public function remove_rewrite_rules() { global $wp, $wp_rewrite, $post_type_meta_caps; // Remove query var. if ( false !== $this->query_var ) { $wp->remove_query_var( $this->query_var ); } // Remove any rewrite rules, permastructs, and rules. if ( false !== $this->rewrite ) { remove_rewrite_tag( "%$this->name%" ); remove_permastruct( $this->name ); foreach ( $wp_rewrite->extra_rules_top as $regex => $query ) { if ( false !== strpos( $query, "index.php?post_type=$this->name" ) ) { unset( $wp_rewrite->extra_rules_top[ $regex ] ); } } } // Remove registered custom meta capabilities. foreach ( $this->cap as $cap ) { unset( $post_type_meta_caps[ $cap ] ); } } /** * Unregisters the post type meta box if a custom callback was specified. * * @since 4.6.0 */ public function unregister_meta_boxes() { if ( $this->register_meta_box_cb ) { remove_action( 'add_meta_boxes_' . $this->name, $this->register_meta_box_cb, 10 ); } } /** * Removes the post type from all taxonomies. * * @since 4.6.0 */ public function unregister_taxonomies() { foreach ( get_object_taxonomies( $this->name ) as $taxonomy ) { unregister_taxonomy_for_object_type( $taxonomy, $this->name ); } } /** * Removes the future post hook action for the post type. * * @since 4.6.0 */ public function remove_hooks() { remove_action( 'future_' . $this->name, '_future_post_hook', 5 ); } /** * Gets the REST API controller for this post type. * * Will only instantiate the controller class once per request. * * @since 5.3.0 * * @return WP_REST_Controller|null The controller instance, or null if the post type * is set not to show in rest. */ public function get_rest_controller() { if ( ! $this->show_in_rest ) { return null; } $class = $this->rest_controller_class ? $this->rest_controller_class : WP_REST_Posts_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; } /** * Returns the default labels for post types. * * @since 6.0.0 * * @return (string|null)[][] The default labels for post types. */ public static function get_default_labels() { if ( ! empty( self::$default_labels ) ) { return self::$default_labels; } self::$default_labels = array( 'name' => array( _x( 'Posts', 'post type general name' ), _x( 'Pages', 'post type general name' ) ), 'singular_name' => array( _x( 'Post', 'post type singular name' ), _x( 'Page', 'post type singular name' ) ), 'add_new' => array( _x( 'Add New', 'post' ), _x( 'Add New', 'page' ) ), 'add_new_item' => array( __( 'Add New Post' ), __( 'Add New Page' ) ), 'edit_item' => array( __( 'Edit Post' ), __( 'Edit Page' ) ), 'new_item' => array( __( 'New Post' ), __( 'New Page' ) ), 'view_item' => array( __( 'View Post' ), __( 'View Page' ) ), 'view_items' => array( __( 'View Posts' ), __( 'View Pages' ) ), 'search_items' => array( __( 'Search Posts' ), __( 'Search Pages' ) ), 'not_found' => array( __( 'No posts found.' ), __( 'No pages found.' ) ), 'not_found_in_trash' => array( __( 'No posts found in Trash.' ), __( 'No pages found in Trash.' ) ), 'parent_item_colon' => array( null, __( 'Parent Page:' ) ), 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) ), 'archives' => array( __( 'Post Archives' ), __( 'Page Archives' ) ), 'attributes' => array( __( 'Post Attributes' ), __( 'Page Attributes' ) ), 'insert_into_item' => array( __( 'Insert into post' ), __( 'Insert into page' ) ), 'uploaded_to_this_item' => array( __( 'Uploaded to this post' ), __( 'Uploaded to this page' ) ), 'featured_image' => array( _x( 'Featured image', 'post' ), _x( 'Featured image', 'page' ) ), 'set_featured_image' => array( _x( 'Set featured image', 'post' ), _x( 'Set featured image', 'page' ) ), 'remove_featured_image' => array( _x( 'Remove featured image', 'post' ), _x( 'Remove featured image', 'page' ) ), 'use_featured_image' => array( _x( 'Use as featured image', 'post' ), _x( 'Use as featured image', 'page' ) ), 'filter_items_list' => array( __( 'Filter posts list' ), __( 'Filter pages list' ) ), 'filter_by_date' => array( __( 'Filter by date' ), __( 'Filter by date' ) ), 'items_list_navigation' => array( __( 'Posts list navigation' ), __( 'Pages list navigation' ) ), 'items_list' => array( __( 'Posts list' ), __( 'Pages list' ) ), 'item_published' => array( __( 'Post published.' ), __( 'Page published.' ) ), 'item_published_privately' => array( __( 'Post published privately.' ), __( 'Page published privately.' ) ), 'item_reverted_to_draft' => array( __( 'Post reverted to draft.' ), __( 'Page reverted to draft.' ) ), 'item_scheduled' => array( __( 'Post scheduled.' ), __( 'Page scheduled.' ) ), 'item_updated' => array( __( 'Post updated.' ), __( 'Page updated.' ) ), 'item_link' => array( _x( 'Post Link', 'navigation link block title' ), _x( 'Page Link', 'navigation link block title' ), ), 'item_link_description' => array( _x( 'A link to a post.', 'navigation link block description' ), _x( 'A link to a page.', 'navigation link block description' ), ), ); return self::$default_labels; } /** * Resets the cache for the default labels. * * @since 6.0.0 */ public static function reset_default_labels() { self::$default_labels = array(); } } ``` | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
programming_docs
wordpress class IXR_Client {} class IXR\_Client {} ==================== [IXR\_Client](ixr_client) * [\_\_construct](ixr_client/__construct) β€” PHP5 constructor. * [getErrorCode](ixr_client/geterrorcode) * [getErrorMessage](ixr_client/geterrormessage) * [getResponse](ixr_client/getresponse) * [isError](ixr_client/iserror) * [IXR\_Client](ixr_client/ixr_client) β€” PHP4 constructor. * [query](ixr_client/query) File: `wp-includes/IXR/class-IXR-client.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-client.php/) ``` class IXR_Client { var $server; var $port; var $path; var $useragent; var $response; var $message = false; var $debug = false; var $timeout; var $headers = array(); // Storage place for an error message var $error = false; /** * PHP5 constructor. */ function __construct( $server, $path = false, $port = 80, $timeout = 15 ) { if (!$path) { // Assume we have been given a URL instead $bits = parse_url($server); $this->server = $bits['host']; $this->port = isset($bits['port']) ? $bits['port'] : 80; $this->path = isset($bits['path']) ? $bits['path'] : '/'; // Make absolutely sure we have a path if (!$this->path) { $this->path = '/'; } if ( ! empty( $bits['query'] ) ) { $this->path .= '?' . $bits['query']; } } else { $this->server = $server; $this->path = $path; $this->port = $port; } $this->useragent = 'The Incutio XML-RPC PHP Library'; $this->timeout = $timeout; } /** * PHP4 constructor. */ public function IXR_Client( $server, $path = false, $port = 80, $timeout = 15 ) { self::__construct( $server, $path, $port, $timeout ); } /** * @since 1.5.0 * @since 5.5.0 Formalized the existing `...$args` parameter by adding it * to the function signature. * * @return bool */ function query( ...$args ) { $method = array_shift($args); $request = new IXR_Request($method, $args); $length = $request->getLength(); $xml = $request->getXml(); $r = "\r\n"; $request = "POST {$this->path} HTTP/1.0$r"; // Merged from WP #8145 - allow custom headers $this->headers['Host'] = $this->server; $this->headers['Content-Type'] = 'text/xml'; $this->headers['User-Agent'] = $this->useragent; $this->headers['Content-Length']= $length; foreach( $this->headers as $header => $value ) { $request .= "{$header}: {$value}{$r}"; } $request .= $r; $request .= $xml; // Now send the request if ($this->debug) { echo '<pre class="ixr_request">'.htmlspecialchars($request)."\n</pre>\n\n"; } if ($this->timeout) { $fp = @fsockopen($this->server, $this->port, $errno, $errstr, $this->timeout); } else { $fp = @fsockopen($this->server, $this->port, $errno, $errstr); } if (!$fp) { $this->error = new IXR_Error(-32300, 'transport error - could not open socket'); return false; } fputs($fp, $request); $contents = ''; $debugContents = ''; $gotFirstLine = false; $gettingHeaders = true; while (!feof($fp)) { $line = fgets($fp, 4096); if (!$gotFirstLine) { // Check line for '200' if (strstr($line, '200') === false) { $this->error = new IXR_Error(-32300, 'transport error - HTTP status code was not 200'); return false; } $gotFirstLine = true; } if (trim($line) == '') { $gettingHeaders = false; } if (!$gettingHeaders) { // merged from WP #12559 - remove trim $contents .= $line; } if ($this->debug) { $debugContents .= $line; } } if ($this->debug) { echo '<pre class="ixr_response">'.htmlspecialchars($debugContents)."\n</pre>\n\n"; } // Now parse what we've got back $this->message = new IXR_Message($contents); if (!$this->message->parse()) { // XML error $this->error = new IXR_Error(-32700, 'parse error. not well formed'); return false; } // Is the message a fault? if ($this->message->messageType == 'fault') { $this->error = new IXR_Error($this->message->faultCode, $this->message->faultString); return false; } // Message must be OK return true; } function getResponse() { // methodResponses can only have one param - return that return $this->message->params[0]; } function isError() { return (is_object($this->error)); } function getErrorCode() { return $this->error->code; } function getErrorMessage() { return $this->error->message; } } ``` | Used By | Description | | --- | --- | | [IXR\_ClientMulticall](ixr_clientmulticall) wp-includes/IXR/class-IXR-clientmulticall.php | [IXR\_ClientMulticall](ixr_clientmulticall) | | [WP\_HTTP\_IXR\_Client](wp_http_ixr_client) wp-includes/class-wp-http-ixr-client.php | [WP\_HTTP\_IXR\_Client](wp_http_ixr_client) | | Version | Description | | --- | --- | | [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. | wordpress class PO {} class PO {} =========== * [add\_comment\_to\_entry](po/add_comment_to_entry) * [comment\_block](po/comment_block) β€” Prepare a text as a comment -- wraps the lines and prepends # and a special character to each line * [export](po/export) β€” Exports the whole PO file as a string * [export\_entries](po/export_entries) β€” Exports all entries to PO format * [export\_entry](po/export_entry) β€” Builds a string from the entry for inclusion in PO file * [export\_headers](po/export_headers) β€” Exports headers to a PO entry * [export\_to\_file](po/export_to_file) β€” Same as {@link export}, but writes the result to a file * [import\_from\_file](po/import_from_file) * [is\_final](po/is_final) β€” Helper function for read\_entry * [match\_begin\_and\_end\_newlines](po/match_begin_and_end_newlines) * [poify](po/poify) β€” Formats a string in PO-style * [prepend\_each\_line](po/prepend_each_line) β€” Inserts $with in the beginning of every new line of $string and returns the modified string * [read\_entry](po/read_entry) * [read\_line](po/read_line) * [set\_comment\_before\_headers](po/set_comment_before_headers) β€” Text to include as a comment before the start of the PO contents * [trim\_quotes](po/trim_quotes) * [unpoify](po/unpoify) β€” Gives back the original string from a PO-formatted string File: `wp-includes/pomo/po.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/po.php/) ``` class PO extends Gettext_Translations { public $comments_before_headers = ''; /** * Exports headers to a PO entry * * @return string msgid/msgstr PO entry for this PO file headers, doesn't contain newline at the end */ 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" ); } /** * Exports all entries to PO format * * @return string sequence of mgsgid/msgstr PO strings, doesn't containt newline at the end */ public function export_entries() { // TODO: Sorting. return implode( "\n\n", array_map( array( 'PO', 'export_entry' ), $this->entries ) ); } /** * Exports the whole PO file as a string * * @param bool $include_headers whether to include the headers in the export * @return string ready for inclusion in PO file string for headers and all the enrtries */ public function export( $include_headers = true ) { $res = ''; if ( $include_headers ) { $res .= $this->export_headers(); $res .= "\n\n"; } $res .= $this->export_entries(); return $res; } /** * Same as {@link export}, but writes the result to a file * * @param string $filename Where to write the PO string. * @param bool $include_headers Whether to include the headers in the export. * @return bool true on success, false on error */ 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 ); } /** * 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 * * @param string $text Text to include as a comment. */ public function set_comment_before_headers( $text ) { $this->comments_before_headers = $text; } /** * Formats a string in PO-style * * @param string $string the string to format * @return string the poified string */ 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; } /** * Gives back the original string from a PO-formatted string * * @param string $string PO-formatted string * @return string enascaped string */ 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; } /** * Inserts $with in the beginning of every new line of $string and * returns the modified string * * @param string $string prepend lines in this string * @param string $with prepend lines with this string */ 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; } /** * Prepare a text as a comment -- wraps the lines and prepends # * and a special character to each line * * @access private * @param string $text the comment text * @param string $char character to denote a special PO comment, * like :, default is a space */ public static function comment_block( $text, $char = ' ' ) { $text = wordwrap( $text, PO_MAX_LINE_LEN - 3 ); return PO::prepend_each_line( $text, "#$char " ); } /** * Builds a string from the entry for inclusion in PO file * * @param Translation_Entry $entry the entry to convert to po string. * @return string|false PO-style formatted string for the entry or * false if the entry is empty */ 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 ); } 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; } /** * @param string $filename * @return bool */ 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; } /** * Helper function for read_entry * * @param string $context * @return bool */ protected static function is_final( $context ) { return ( 'msgstr' === $context ) || ( 'msgstr_plural' === $context ); } /** * @param resource $f * @param int $lineno * @return null|false|array */ 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, ); } /** * @param resource $f * @param string $action * @return bool */ 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; } /** * @param Translation_Entry $entry * @param string $po_comment_line */ 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 ); } } /** * @param string $s * @return string */ 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; } } ``` | Uses | Description | | --- | --- | | [Gettext\_Translations](gettext_translations) wp-includes/pomo/translations.php | |
programming_docs
wordpress class WP_Admin_Bar {} class WP\_Admin\_Bar {} ======================= Core class used to implement the Toolbar API. [WP\_Admin\_Bar](wp_admin_bar) is WordPress’ class for generating the Toolbar that lines the top of WordPress sites when signed in. This class can be hooked and modified to add or remove options that appear in the admin bar. The Toolbar replaces the Admin Bar since WordPress [Version 3.3](https://wordpress.org/support/wordpress-version/version-3-3/ "Version 3.3"). This class is used internally by WordPress to create an object called **$wp\_admin\_bar**. Most modifications to WordPress toolbar will generally be done by modifying the $wp\_admin\_bar object that is passed through the [admin\_bar\_menu](../hooks/admin_bar_menu "Plugin API/Action Reference/admin bar menu (page does not exist)") hook. Example: ``` add_action( 'admin_bar_menu', 'modify_admin_bar' ); function modify_admin_bar( $wp_admin_bar ){ // do something with $wp_admin_bar; } ``` * [\_\_get](wp_admin_bar/__get) * [\_bind](wp_admin_bar/_bind) * [\_get\_node](wp_admin_bar/_get_node) * [\_get\_nodes](wp_admin_bar/_get_nodes) * [\_render](wp_admin_bar/_render) * [\_render\_container](wp_admin_bar/_render_container) * [\_render\_group](wp_admin_bar/_render_group) * [\_render\_item](wp_admin_bar/_render_item) * [\_set\_node](wp_admin_bar/_set_node) * [\_unset\_node](wp_admin_bar/_unset_node) * [add\_group](wp_admin_bar/add_group) β€” Adds a group to a toolbar menu node. * [add\_menu](wp_admin_bar/add_menu) β€” Adds a node (menu item) to the admin bar menu. * [add\_menus](wp_admin_bar/add_menus) β€” Adds menus to the admin bar. * [add\_node](wp_admin_bar/add_node) β€” Adds a node to the menu. * [get\_node](wp_admin_bar/get_node) β€” Gets a node. * [get\_nodes](wp_admin_bar/get_nodes) * [initialize](wp_admin_bar/initialize) β€” Initializes the admin bar. * [recursive\_render](wp_admin_bar/recursive_render) β€” Renders toolbar items recursively. β€” deprecated * [remove\_menu](wp_admin_bar/remove_menu) β€” Removes a node from the admin bar. * [remove\_node](wp_admin_bar/remove_node) β€” Remove a node. * [render](wp_admin_bar/render) File: `wp-includes/class-wp-admin-bar.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-admin-bar.php/) ``` class WP_Admin_Bar { private $nodes = array(); private $bound = false; public $user; /** * @since 3.3.0 * * @param string $name * @return string|array|void */ public function __get( $name ) { switch ( $name ) { case 'proto': return is_ssl() ? 'https://' : 'http://'; case 'menu': _deprecated_argument( 'WP_Admin_Bar', '3.3.0', 'Modify admin bar nodes with WP_Admin_Bar::get_node(), WP_Admin_Bar::add_node(), and WP_Admin_Bar::remove_node(), not the <code>menu</code> property.' ); return array(); // Sorry, folks. } } /** * Initializes the admin bar. * * @since 3.1.0 */ public function initialize() { $this->user = new stdClass; if ( is_user_logged_in() ) { /* Populate settings we need for the menu based on the current user. */ $this->user->blogs = get_blogs_of_user( get_current_user_id() ); if ( is_multisite() ) { $this->user->active_blog = get_active_blog_for_user( get_current_user_id() ); $this->user->domain = empty( $this->user->active_blog ) ? user_admin_url() : trailingslashit( get_home_url( $this->user->active_blog->blog_id ) ); $this->user->account_domain = $this->user->domain; } else { $this->user->active_blog = $this->user->blogs[ get_current_blog_id() ]; $this->user->domain = trailingslashit( home_url() ); $this->user->account_domain = $this->user->domain; } } add_action( 'wp_head', 'wp_admin_bar_header' ); add_action( 'admin_head', 'wp_admin_bar_header' ); if ( current_theme_supports( 'admin-bar' ) ) { /** * To remove the default padding styles from WordPress for the Toolbar, use the following code: * add_theme_support( 'admin-bar', array( 'callback' => '__return_false' ) ); */ $admin_bar_args = get_theme_support( 'admin-bar' ); $header_callback = $admin_bar_args[0]['callback']; } if ( empty( $header_callback ) ) { $header_callback = '_admin_bar_bump_cb'; } add_action( 'wp_head', $header_callback ); wp_enqueue_script( 'admin-bar' ); wp_enqueue_style( 'admin-bar' ); /** * Fires after WP_Admin_Bar is initialized. * * @since 3.1.0 */ do_action( 'admin_bar_init' ); } /** * Adds a node (menu item) to the admin bar menu. * * @since 3.3.0 * * @param array $node The attributes that define the node. */ public function add_menu( $node ) { $this->add_node( $node ); } /** * Removes a node from the admin bar. * * @since 3.1.0 * * @param string $id The menu slug to remove. */ public function remove_menu( $id ) { $this->remove_node( $id ); } /** * Adds a node to the menu. * * @since 3.1.0 * @since 4.5.0 Added the ability to pass 'lang' and 'dir' meta data. * * @param array $args { * Arguments for adding a node. * * @type string $id ID of the item. * @type string $title Title of the node. * @type string $parent Optional. ID of the parent node. * @type string $href Optional. Link for the item. * @type bool $group Optional. Whether or not the node is a group. Default false. * @type array $meta Meta data including the following keys: 'html', 'class', 'rel', 'lang', 'dir', * 'onclick', 'target', 'title', 'tabindex'. Default empty. * } */ public function add_node( $args ) { // Shim for old method signature: add_node( $parent_id, $menu_obj, $args ). if ( func_num_args() >= 3 && is_string( $args ) ) { $args = array_merge( array( 'parent' => $args ), func_get_arg( 2 ) ); } if ( is_object( $args ) ) { $args = get_object_vars( $args ); } // Ensure we have a valid title. if ( empty( $args['id'] ) ) { if ( empty( $args['title'] ) ) { return; } _doing_it_wrong( __METHOD__, __( 'The menu ID should not be empty.' ), '3.3.0' ); // Deprecated: Generate an ID from the title. $args['id'] = esc_attr( sanitize_title( trim( $args['title'] ) ) ); } $defaults = array( 'id' => false, 'title' => false, 'parent' => false, 'href' => false, 'group' => false, 'meta' => array(), ); // If the node already exists, keep any data that isn't provided. $maybe_defaults = $this->get_node( $args['id'] ); if ( $maybe_defaults ) { $defaults = get_object_vars( $maybe_defaults ); } // Do the same for 'meta' items. if ( ! empty( $defaults['meta'] ) && ! empty( $args['meta'] ) ) { $args['meta'] = wp_parse_args( $args['meta'], $defaults['meta'] ); } $args = wp_parse_args( $args, $defaults ); $back_compat_parents = array( 'my-account-with-avatar' => array( 'my-account', '3.3' ), 'my-blogs' => array( 'my-sites', '3.3' ), ); if ( isset( $back_compat_parents[ $args['parent'] ] ) ) { list( $new_parent, $version ) = $back_compat_parents[ $args['parent'] ]; _deprecated_argument( __METHOD__, $version, sprintf( 'Use <code>%s</code> as the parent for the <code>%s</code> admin bar node instead of <code>%s</code>.', $new_parent, $args['id'], $args['parent'] ) ); $args['parent'] = $new_parent; } $this->_set_node( $args ); } /** * @since 3.3.0 * * @param array $args */ final protected function _set_node( $args ) { $this->nodes[ $args['id'] ] = (object) $args; } /** * Gets a node. * * @since 3.3.0 * * @param string $id * @return object|void Node. */ final public function get_node( $id ) { $node = $this->_get_node( $id ); if ( $node ) { return clone $node; } } /** * @since 3.3.0 * * @param string $id * @return object|void */ final protected function _get_node( $id ) { if ( $this->bound ) { return; } if ( empty( $id ) ) { $id = 'root'; } if ( isset( $this->nodes[ $id ] ) ) { return $this->nodes[ $id ]; } } /** * @since 3.3.0 * * @return array|void */ final public function get_nodes() { $nodes = $this->_get_nodes(); if ( ! $nodes ) { return; } foreach ( $nodes as &$node ) { $node = clone $node; } return $nodes; } /** * @since 3.3.0 * * @return array|void */ final protected function _get_nodes() { if ( $this->bound ) { return; } return $this->nodes; } /** * Adds a group to a toolbar menu node. * * Groups can be used to organize toolbar items into distinct sections of a toolbar menu. * * @since 3.3.0 * * @param array $args { * Array of arguments for adding a group. * * @type string $id ID of the item. * @type string $parent Optional. ID of the parent node. Default 'root'. * @type array $meta Meta data for the group including the following keys: * 'class', 'onclick', 'target', and 'title'. * } */ final public function add_group( $args ) { $args['group'] = true; $this->add_node( $args ); } /** * Remove a node. * * @since 3.1.0 * * @param string $id The ID of the item. */ public function remove_node( $id ) { $this->_unset_node( $id ); } /** * @since 3.3.0 * * @param string $id */ final protected function _unset_node( $id ) { unset( $this->nodes[ $id ] ); } /** * @since 3.1.0 */ public function render() { $root = $this->_bind(); if ( $root ) { $this->_render( $root ); } } /** * @since 3.3.0 * * @return object|void */ final protected function _bind() { if ( $this->bound ) { return; } // Add the root node. // Clear it first, just in case. Don't mess with The Root. $this->remove_node( 'root' ); $this->add_node( array( 'id' => 'root', 'group' => false, ) ); // Normalize nodes: define internal 'children' and 'type' properties. foreach ( $this->_get_nodes() as $node ) { $node->children = array(); $node->type = ( $node->group ) ? 'group' : 'item'; unset( $node->group ); // The Root wants your orphans. No lonely items allowed. if ( ! $node->parent ) { $node->parent = 'root'; } } foreach ( $this->_get_nodes() as $node ) { if ( 'root' === $node->id ) { continue; } // Fetch the parent node. If it isn't registered, ignore the node. $parent = $this->_get_node( $node->parent ); if ( ! $parent ) { continue; } // Generate the group class (we distinguish between top level and other level groups). $group_class = ( 'root' === $node->parent ) ? 'ab-top-menu' : 'ab-submenu'; if ( 'group' === $node->type ) { if ( empty( $node->meta['class'] ) ) { $node->meta['class'] = $group_class; } else { $node->meta['class'] .= ' ' . $group_class; } } // Items in items aren't allowed. Wrap nested items in 'default' groups. if ( 'item' === $parent->type && 'item' === $node->type ) { $default_id = $parent->id . '-default'; $default = $this->_get_node( $default_id ); // The default group is added here to allow groups that are // added before standard menu items to render first. if ( ! $default ) { // Use _set_node because add_node can be overloaded. // Make sure to specify default settings for all properties. $this->_set_node( array( 'id' => $default_id, 'parent' => $parent->id, 'type' => 'group', 'children' => array(), 'meta' => array( 'class' => $group_class, ), 'title' => false, 'href' => false, ) ); $default = $this->_get_node( $default_id ); $parent->children[] = $default; } $parent = $default; // Groups in groups aren't allowed. Add a special 'container' node. // The container will invisibly wrap both groups. } elseif ( 'group' === $parent->type && 'group' === $node->type ) { $container_id = $parent->id . '-container'; $container = $this->_get_node( $container_id ); // We need to create a container for this group, life is sad. if ( ! $container ) { // Use _set_node because add_node can be overloaded. // Make sure to specify default settings for all properties. $this->_set_node( array( 'id' => $container_id, 'type' => 'container', 'children' => array( $parent ), 'parent' => false, 'title' => false, 'href' => false, 'meta' => array(), ) ); $container = $this->_get_node( $container_id ); // Link the container node if a grandparent node exists. $grandparent = $this->_get_node( $parent->parent ); if ( $grandparent ) { $container->parent = $grandparent->id; $index = array_search( $parent, $grandparent->children, true ); if ( false === $index ) { $grandparent->children[] = $container; } else { array_splice( $grandparent->children, $index, 1, array( $container ) ); } } $parent->parent = $container->id; } $parent = $container; } // Update the parent ID (it might have changed). $node->parent = $parent->id; // Add the node to the tree. $parent->children[] = $node; } $root = $this->_get_node( 'root' ); $this->bound = true; return $root; } /** * @since 3.3.0 * * @param object $root */ final protected function _render( $root ) { // Add browser classes. // We have to do this here since admin bar shows on the front end. $class = 'nojq nojs'; if ( wp_is_mobile() ) { $class .= ' mobile'; } ?> <div id="wpadminbar" class="<?php echo $class; ?>"> <?php if ( ! is_admin() && ! did_action( 'wp_body_open' ) ) { ?> <a class="screen-reader-shortcut" href="#wp-toolbar" tabindex="1"><?php _e( 'Skip to toolbar' ); ?></a> <?php } ?> <div class="quicklinks" id="wp-toolbar" role="navigation" aria-label="<?php esc_attr_e( 'Toolbar' ); ?>"> <?php foreach ( $root->children as $group ) { $this->_render_group( $group ); } ?> </div> <?php if ( is_user_logged_in() ) : ?> <a class="screen-reader-shortcut" href="<?php echo esc_url( wp_logout_url() ); ?>"><?php _e( 'Log Out' ); ?></a> <?php endif; ?> </div> <?php } /** * @since 3.3.0 * * @param object $node */ final protected function _render_container( $node ) { if ( 'container' !== $node->type || empty( $node->children ) ) { return; } echo '<div id="' . esc_attr( 'wp-admin-bar-' . $node->id ) . '" class="ab-group-container">'; foreach ( $node->children as $group ) { $this->_render_group( $group ); } echo '</div>'; } /** * @since 3.3.0 * * @param object $node */ final protected function _render_group( $node ) { if ( 'container' === $node->type ) { $this->_render_container( $node ); return; } if ( 'group' !== $node->type || empty( $node->children ) ) { return; } if ( ! empty( $node->meta['class'] ) ) { $class = ' class="' . esc_attr( trim( $node->meta['class'] ) ) . '"'; } else { $class = ''; } echo "<ul id='" . esc_attr( 'wp-admin-bar-' . $node->id ) . "'$class>"; foreach ( $node->children as $item ) { $this->_render_item( $item ); } echo '</ul>'; } /** * @since 3.3.0 * * @param object $node */ final protected function _render_item( $node ) { if ( 'item' !== $node->type ) { return; } $is_parent = ! empty( $node->children ); $has_link = ! empty( $node->href ); $is_root_top_item = 'root-default' === $node->parent; $is_top_secondary_item = 'top-secondary' === $node->parent; // Allow only numeric values, then casted to integers, and allow a tabindex value of `0` for a11y. $tabindex = ( isset( $node->meta['tabindex'] ) && is_numeric( $node->meta['tabindex'] ) ) ? (int) $node->meta['tabindex'] : ''; $aria_attributes = ( '' !== $tabindex ) ? ' tabindex="' . $tabindex . '"' : ''; $menuclass = ''; $arrow = ''; if ( $is_parent ) { $menuclass = 'menupop '; $aria_attributes .= ' aria-haspopup="true"'; } if ( ! empty( $node->meta['class'] ) ) { $menuclass .= $node->meta['class']; } // Print the arrow icon for the menu children with children. if ( ! $is_root_top_item && ! $is_top_secondary_item && $is_parent ) { $arrow = '<span class="wp-admin-bar-arrow" aria-hidden="true"></span>'; } if ( $menuclass ) { $menuclass = ' class="' . esc_attr( trim( $menuclass ) ) . '"'; } echo "<li id='" . esc_attr( 'wp-admin-bar-' . $node->id ) . "'$menuclass>"; if ( $has_link ) { $attributes = array( 'onclick', 'target', 'title', 'rel', 'lang', 'dir' ); echo "<a class='ab-item'$aria_attributes href='" . esc_url( $node->href ) . "'"; } else { $attributes = array( 'onclick', 'target', 'title', 'rel', 'lang', 'dir' ); echo '<div class="ab-item ab-empty-item"' . $aria_attributes; } foreach ( $attributes as $attribute ) { if ( empty( $node->meta[ $attribute ] ) ) { continue; } if ( 'onclick' === $attribute ) { echo " $attribute='" . esc_js( $node->meta[ $attribute ] ) . "'"; } else { echo " $attribute='" . esc_attr( $node->meta[ $attribute ] ) . "'"; } } echo ">{$arrow}{$node->title}"; if ( $has_link ) { echo '</a>'; } else { echo '</div>'; } if ( $is_parent ) { echo '<div class="ab-sub-wrapper">'; foreach ( $node->children as $group ) { $this->_render_group( $group ); } echo '</div>'; } if ( ! empty( $node->meta['html'] ) ) { echo $node->meta['html']; } echo '</li>'; } /** * Renders toolbar items recursively. * * @since 3.1.0 * @deprecated 3.3.0 Use WP_Admin_Bar::_render_item() or WP_Admin_bar::render() instead. * @see WP_Admin_Bar::_render_item() * @see WP_Admin_Bar::render() * * @param string $id Unused. * @param object $node */ public function recursive_render( $id, $node ) { _deprecated_function( __METHOD__, '3.3.0', 'WP_Admin_bar::render(), WP_Admin_Bar::_render_item()' ); $this->_render_item( $node ); } /** * Adds menus to the admin bar. * * @since 3.1.0 */ public function add_menus() { // User-related, aligned right. add_action( 'admin_bar_menu', 'wp_admin_bar_my_account_menu', 0 ); add_action( 'admin_bar_menu', 'wp_admin_bar_search_menu', 4 ); add_action( 'admin_bar_menu', 'wp_admin_bar_my_account_item', 7 ); add_action( 'admin_bar_menu', 'wp_admin_bar_recovery_mode_menu', 8 ); // Site-related. add_action( 'admin_bar_menu', 'wp_admin_bar_sidebar_toggle', 0 ); add_action( 'admin_bar_menu', 'wp_admin_bar_wp_menu', 10 ); add_action( 'admin_bar_menu', 'wp_admin_bar_my_sites_menu', 20 ); add_action( 'admin_bar_menu', 'wp_admin_bar_site_menu', 30 ); add_action( 'admin_bar_menu', 'wp_admin_bar_edit_site_menu', 40 ); add_action( 'admin_bar_menu', 'wp_admin_bar_customize_menu', 40 ); add_action( 'admin_bar_menu', 'wp_admin_bar_updates_menu', 50 ); // Content-related. if ( ! is_network_admin() && ! is_user_admin() ) { add_action( 'admin_bar_menu', 'wp_admin_bar_comments_menu', 60 ); add_action( 'admin_bar_menu', 'wp_admin_bar_new_content_menu', 70 ); } add_action( 'admin_bar_menu', 'wp_admin_bar_edit_menu', 80 ); add_action( 'admin_bar_menu', 'wp_admin_bar_add_secondary_groups', 200 ); /** * Fires after menus are added to the menu bar. * * @since 3.1.0 */ do_action( 'add_admin_bar_menus' ); } } ``` | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. | wordpress class Custom_Image_Header {} class Custom\_Image\_Header {} ============================== The custom header image class. * [\_\_construct](custom_image_header/__construct) β€” Constructor - Register administration header callback. * [admin\_page](custom_image_header/admin_page) β€” Display the page based on the current step. * [ajax\_header\_add](custom_image_header/ajax_header_add) β€” Given an attachment ID for a header image, updates its "last used" timestamp to now. * [ajax\_header\_crop](custom_image_header/ajax_header_crop) β€” Gets attachment uploaded by Media Manager, crops it, then saves it as a new object. Returns JSON-encoded object details. * [ajax\_header\_remove](custom_image_header/ajax_header_remove) β€” Given an attachment ID for a header image, unsets it as a user-uploaded header image for the active theme. * [attachment\_fields\_to\_edit](custom_image_header/attachment_fields_to_edit) β€” Unused since 3.5.0. * [create\_attachment\_object](custom_image_header/create_attachment_object) β€” Create an attachment 'object'. * [css\_includes](custom_image_header/css_includes) β€” Set up the enqueue for the CSS files * [customize\_set\_last\_used](custom_image_header/customize_set_last_used) β€” Updates the last-used postmeta on a header image attachment after saving a new header image via the Customizer. * [filter\_upload\_tabs](custom_image_header/filter_upload_tabs) β€” Unused since 3.5.0. * [finished](custom_image_header/finished) β€” Display last step of custom header image page. * [get\_default\_header\_images](custom_image_header/get_default_header_images) β€” Gets the details of default header images if defined. * [get\_header\_dimensions](custom_image_header/get_header_dimensions) β€” Calculate width and height based on what the currently selected theme supports. * [get\_previous\_crop](custom_image_header/get_previous_crop) β€” Get the ID of a previous crop from the same base image. * [get\_uploaded\_header\_images](custom_image_header/get_uploaded_header_images) β€” Gets the previously uploaded header images. * [help](custom_image_header/help) β€” Adds contextual help. * [init](custom_image_header/init) β€” Set up the hooks for the Custom Header admin page. * [insert\_attachment](custom_image_header/insert_attachment) β€” Insert an attachment and its metadata. * [js](custom_image_header/js) β€” Execute JavaScript depending on step. * [js\_1](custom_image_header/js_1) β€” Display JavaScript based on Step 1 and 3. * [js\_2](custom_image_header/js_2) β€” Display JavaScript based on Step 2. * [js\_includes](custom_image_header/js_includes) β€” Set up the enqueue for the JavaScript files. * [process\_default\_headers](custom_image_header/process_default_headers) β€” Process the default headers * [remove\_header\_image](custom_image_header/remove_header_image) β€” Remove a header image. * [reset\_header\_image](custom_image_header/reset_header_image) β€” Reset a header image to the default image for the theme. * [set\_header\_image](custom_image_header/set_header_image) β€” Choose a header image, selected from existing uploaded and default headers, or provide an array of uploaded header data (either new, or from media library). * [show\_header\_selector](custom_image_header/show_header_selector) β€” Display UI for selecting one of several default headers. * [step](custom_image_header/step) β€” Get the current step. * [step\_1](custom_image_header/step_1) β€” Display first step of custom header image page. * [step\_2](custom_image_header/step_2) β€” Display second step of custom header image page. * [step\_2\_manage\_upload](custom_image_header/step_2_manage_upload) β€” Upload the file to be cropped in the second step. * [step\_3](custom_image_header/step_3) β€” Display third step of custom header image page. * [take\_action](custom_image_header/take_action) β€” Execute custom header modification. File: `wp-admin/includes/class-custom-image-header.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-custom-image-header.php/) ``` class Custom_Image_Header { /** * Callback for administration header. * * @var callable * @since 2.1.0 */ public $admin_header_callback; /** * Callback for header div. * * @var callable * @since 3.0.0 */ public $admin_image_div_callback; /** * Holds default headers. * * @var array * @since 3.0.0 */ public $default_headers = array(); /** * Used to trigger a success message when settings updated and set to true. * * @since 3.0.0 * @var bool */ private $updated; /** * Constructor - Register administration header callback. * * @since 2.1.0 * @param callable $admin_header_callback * @param callable $admin_image_div_callback Optional custom image div output callback. */ public function __construct( $admin_header_callback, $admin_image_div_callback = '' ) { $this->admin_header_callback = $admin_header_callback; $this->admin_image_div_callback = $admin_image_div_callback; add_action( 'admin_menu', array( $this, 'init' ) ); add_action( 'customize_save_after', array( $this, 'customize_set_last_used' ) ); add_action( 'wp_ajax_custom-header-crop', array( $this, 'ajax_header_crop' ) ); add_action( 'wp_ajax_custom-header-add', array( $this, 'ajax_header_add' ) ); add_action( 'wp_ajax_custom-header-remove', array( $this, 'ajax_header_remove' ) ); } /** * Set up the hooks for the Custom Header admin page. * * @since 2.1.0 */ public function init() { $page = add_theme_page( __( 'Header' ), __( 'Header' ), 'edit_theme_options', 'custom-header', array( $this, 'admin_page' ) ); if ( ! $page ) { return; } add_action( "admin_print_scripts-{$page}", array( $this, 'js_includes' ) ); add_action( "admin_print_styles-{$page}", array( $this, 'css_includes' ) ); add_action( "admin_head-{$page}", array( $this, 'help' ) ); add_action( "admin_head-{$page}", array( $this, 'take_action' ), 50 ); add_action( "admin_head-{$page}", array( $this, 'js' ), 50 ); if ( $this->admin_header_callback ) { add_action( "admin_head-{$page}", $this->admin_header_callback, 51 ); } } /** * Adds contextual help. * * @since 3.0.0 */ public function help() { get_current_screen()->add_help_tab( array( 'id' => 'overview', 'title' => __( 'Overview' ), 'content' => '<p>' . __( 'This screen is used to customize the header section of your theme.' ) . '</p>' . '<p>' . __( 'You can choose from the theme&#8217;s default header images, or use one of your own. You can also customize how your Site Title and Tagline are displayed.' ) . '<p>', ) ); get_current_screen()->add_help_tab( array( 'id' => 'set-header-image', 'title' => __( 'Header Image' ), 'content' => '<p>' . __( 'You can set a custom image header for your site. Simply upload the image and crop it, and the new header will go live immediately. Alternatively, you can use an image that has already been uploaded to your Media Library by clicking the &#8220;Choose Image&#8221; button.' ) . '</p>' . '<p>' . __( 'Some themes come with additional header images bundled. If you see multiple images displayed, select the one you would like and click the &#8220;Save Changes&#8221; button.' ) . '</p>' . '<p>' . __( 'If your theme has more than one default header image, or you have uploaded more than one custom header image, you have the option of having WordPress display a randomly different image on each page of your site. Click the &#8220;Random&#8221; radio button next to the Uploaded Images or Default Images section to enable this feature.' ) . '</p>' . '<p>' . __( 'If you do not want a header image to be displayed on your site at all, click the &#8220;Remove Header Image&#8221; button at the bottom of the Header Image section of this page. If you want to re-enable the header image later, you just have to select one of the other image options and click &#8220;Save Changes&#8221;.' ) . '</p>', ) ); get_current_screen()->add_help_tab( array( 'id' => 'set-header-text', 'title' => __( 'Header Text' ), 'content' => '<p>' . sprintf( /* translators: %s: URL to General Settings screen. */ __( 'For most themes, the header text is your Site Title and Tagline, as defined in the <a href="%s">General Settings</a> section.' ), admin_url( 'options-general.php' ) ) . '</p>' . '<p>' . __( 'In the Header Text section of this page, you can choose whether to display this text or hide it. You can also choose a color for the text by clicking the Select Color button and either typing in a legitimate HTML hex value, e.g. &#8220;#ff0000&#8221; for red, or by choosing a color using the color picker.' ) . '</p>' . '<p>' . __( 'Do not forget to click &#8220;Save Changes&#8221; when you are done!' ) . '</p>', ) ); get_current_screen()->set_help_sidebar( '<p><strong>' . __( 'For more information:' ) . '</strong></p>' . '<p>' . __( '<a href="https://codex.wordpress.org/Appearance_Header_Screen">Documentation on Custom Header</a>' ) . '</p>' . '<p>' . __( '<a href="https://wordpress.org/support/">Support</a>' ) . '</p>' ); } /** * Get the current step. * * @since 2.6.0 * * @return int Current step. */ public function step() { if ( ! isset( $_GET['step'] ) ) { return 1; } $step = (int) $_GET['step']; if ( $step < 1 || 3 < $step || ( 2 === $step && ! wp_verify_nonce( $_REQUEST['_wpnonce-custom-header-upload'], 'custom-header-upload' ) ) || ( 3 === $step && ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'custom-header-crop-image' ) ) ) { return 1; } return $step; } /** * Set up the enqueue for the JavaScript files. * * @since 2.1.0 */ public function js_includes() { $step = $this->step(); if ( ( 1 === $step || 3 === $step ) ) { wp_enqueue_media(); wp_enqueue_script( 'custom-header' ); if ( current_theme_supports( 'custom-header', 'header-text' ) ) { wp_enqueue_script( 'wp-color-picker' ); } } elseif ( 2 === $step ) { wp_enqueue_script( 'imgareaselect' ); } } /** * Set up the enqueue for the CSS files * * @since 2.7.0 */ public function css_includes() { $step = $this->step(); if ( ( 1 === $step || 3 === $step ) && current_theme_supports( 'custom-header', 'header-text' ) ) { wp_enqueue_style( 'wp-color-picker' ); } elseif ( 2 === $step ) { wp_enqueue_style( 'imgareaselect' ); } } /** * Execute custom header modification. * * @since 2.6.0 */ public function take_action() { if ( ! current_user_can( 'edit_theme_options' ) ) { return; } if ( empty( $_POST ) ) { return; } $this->updated = true; if ( isset( $_POST['resetheader'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); $this->reset_header_image(); return; } if ( isset( $_POST['removeheader'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); $this->remove_header_image(); return; } if ( isset( $_POST['text-color'] ) && ! isset( $_POST['display-header-text'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); set_theme_mod( 'header_textcolor', 'blank' ); } elseif ( isset( $_POST['text-color'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); $_POST['text-color'] = str_replace( '#', '', $_POST['text-color'] ); $color = preg_replace( '/[^0-9a-fA-F]/', '', $_POST['text-color'] ); if ( strlen( $color ) === 6 || strlen( $color ) === 3 ) { set_theme_mod( 'header_textcolor', $color ); } elseif ( ! $color ) { set_theme_mod( 'header_textcolor', 'blank' ); } } if ( isset( $_POST['default-header'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); $this->set_header_image( $_POST['default-header'] ); return; } } /** * Process the default headers * * @since 3.0.0 * * @global array $_wp_default_headers */ public function process_default_headers() { global $_wp_default_headers; if ( ! isset( $_wp_default_headers ) ) { return; } if ( ! empty( $this->default_headers ) ) { return; } $this->default_headers = $_wp_default_headers; $template_directory_uri = get_template_directory_uri(); $stylesheet_directory_uri = get_stylesheet_directory_uri(); foreach ( array_keys( $this->default_headers ) as $header ) { $this->default_headers[ $header ]['url'] = sprintf( $this->default_headers[ $header ]['url'], $template_directory_uri, $stylesheet_directory_uri ); $this->default_headers[ $header ]['thumbnail_url'] = sprintf( $this->default_headers[ $header ]['thumbnail_url'], $template_directory_uri, $stylesheet_directory_uri ); } } /** * Display UI for selecting one of several default headers. * * Show the random image option if this theme has multiple header images. * Random image option is on by default if no header has been set. * * @since 3.0.0 * * @param string $type The header type. One of 'default' (for the Uploaded Images control) * or 'uploaded' (for the Uploaded Images control). */ public function show_header_selector( $type = 'default' ) { if ( 'default' === $type ) { $headers = $this->default_headers; } else { $headers = get_uploaded_header_images(); $type = 'uploaded'; } if ( 1 < count( $headers ) ) { echo '<div class="random-header">'; echo '<label><input name="default-header" type="radio" value="random-' . $type . '-image"' . checked( is_random_header_image( $type ), true, false ) . ' />'; _e( '<strong>Random:</strong> Show a different image on each page.' ); echo '</label>'; echo '</div>'; } echo '<div class="available-headers">'; foreach ( $headers as $header_key => $header ) { $header_thumbnail = $header['thumbnail_url']; $header_url = $header['url']; $header_alt_text = empty( $header['alt_text'] ) ? '' : $header['alt_text']; echo '<div class="default-header">'; echo '<label><input name="default-header" type="radio" value="' . esc_attr( $header_key ) . '" ' . checked( $header_url, get_theme_mod( 'header_image' ), false ) . ' />'; $width = ''; if ( ! empty( $header['attachment_id'] ) ) { $width = ' width="230"'; } echo '<img src="' . set_url_scheme( $header_thumbnail ) . '" alt="' . esc_attr( $header_alt_text ) . '"' . $width . ' /></label>'; echo '</div>'; } echo '<div class="clear"></div></div>'; } /** * Execute JavaScript depending on step. * * @since 2.1.0 */ public function js() { $step = $this->step(); if ( ( 1 === $step || 3 === $step ) && current_theme_supports( 'custom-header', 'header-text' ) ) { $this->js_1(); } elseif ( 2 === $step ) { $this->js_2(); } } /** * Display JavaScript based on Step 1 and 3. * * @since 2.6.0 */ public function js_1() { $default_color = ''; if ( current_theme_supports( 'custom-header', 'default-text-color' ) ) { $default_color = get_theme_support( 'custom-header', 'default-text-color' ); if ( $default_color && false === strpos( $default_color, '#' ) ) { $default_color = '#' . $default_color; } } ?> <script type="text/javascript"> (function($){ var default_color = '<?php echo esc_js( $default_color ); ?>', header_text_fields; function pickColor(color) { $('#name').css('color', color); $('#desc').css('color', color); $('#text-color').val(color); } function toggle_text() { var checked = $('#display-header-text').prop('checked'), text_color; header_text_fields.toggle( checked ); if ( ! checked ) return; text_color = $('#text-color'); if ( '' === text_color.val().replace('#', '') ) { text_color.val( default_color ); pickColor( default_color ); } else { pickColor( text_color.val() ); } } $( function() { var text_color = $('#text-color'); header_text_fields = $('.displaying-header-text'); text_color.wpColorPicker({ change: function( event, ui ) { pickColor( text_color.wpColorPicker('color') ); }, clear: function() { pickColor( '' ); } }); $('#display-header-text').click( toggle_text ); <?php if ( ! display_header_text() ) : ?> toggle_text(); <?php endif; ?> } ); })(jQuery); </script> <?php } /** * Display JavaScript based on Step 2. * * @since 2.6.0 */ public function js_2() { ?> <script type="text/javascript"> function onEndCrop( coords ) { jQuery( '#x1' ).val(coords.x); jQuery( '#y1' ).val(coords.y); jQuery( '#width' ).val(coords.w); jQuery( '#height' ).val(coords.h); } jQuery( function() { var xinit = <?php echo absint( get_theme_support( 'custom-header', 'width' ) ); ?>; var yinit = <?php echo absint( get_theme_support( 'custom-header', 'height' ) ); ?>; var ratio = xinit / yinit; var ximg = jQuery('img#upload').width(); var yimg = jQuery('img#upload').height(); if ( yimg < yinit || ximg < xinit ) { if ( ximg / yimg > ratio ) { yinit = yimg; xinit = yinit * ratio; } else { xinit = ximg; yinit = xinit / ratio; } } jQuery('img#upload').imgAreaSelect({ handles: true, keys: true, show: true, x1: 0, y1: 0, x2: xinit, y2: yinit, <?php if ( ! current_theme_supports( 'custom-header', 'flex-height' ) && ! current_theme_supports( 'custom-header', 'flex-width' ) ) { ?> aspectRatio: xinit + ':' + yinit, <?php } if ( ! current_theme_supports( 'custom-header', 'flex-height' ) ) { ?> maxHeight: <?php echo get_theme_support( 'custom-header', 'height' ); ?>, <?php } if ( ! current_theme_supports( 'custom-header', 'flex-width' ) ) { ?> maxWidth: <?php echo get_theme_support( 'custom-header', 'width' ); ?>, <?php } ?> onInit: function () { jQuery('#width').val(xinit); jQuery('#height').val(yinit); }, onSelectChange: function(img, c) { jQuery('#x1').val(c.x1); jQuery('#y1').val(c.y1); jQuery('#width').val(c.width); jQuery('#height').val(c.height); } }); } ); </script> <?php } /** * Display first step of custom header image page. * * @since 2.1.0 */ public function step_1() { $this->process_default_headers(); ?> <div class="wrap"> <h1><?php _e( 'Custom Header' ); ?></h1> <?php if ( current_user_can( 'customize' ) ) { ?> <div class="notice notice-info hide-if-no-customize"> <p> <?php printf( /* translators: %s: URL to header image configuration in Customizer. */ __( 'You can now manage and live-preview Custom Header in the <a href="%s">Customizer</a>.' ), admin_url( 'customize.php?autofocus[control]=header_image' ) ); ?> </p> </div> <?php } ?> <?php if ( ! empty( $this->updated ) ) { ?> <div id="message" class="updated"> <p> <?php /* translators: %s: Home URL. */ printf( __( 'Header updated. <a href="%s">Visit your site</a> to see how it looks.' ), esc_url( home_url( '/' ) ) ); ?> </p> </div> <?php } ?> <h2><?php _e( 'Header Image' ); ?></h2> <table class="form-table" role="presentation"> <tbody> <?php if ( get_custom_header() || display_header_text() ) : ?> <tr> <th scope="row"><?php _e( 'Preview' ); ?></th> <td> <?php if ( $this->admin_image_div_callback ) { call_user_func( $this->admin_image_div_callback ); } else { $custom_header = get_custom_header(); $header_image = get_header_image(); if ( $header_image ) { $header_image_style = 'background-image:url(' . esc_url( $header_image ) . ');'; } else { $header_image_style = ''; } if ( $custom_header->width ) { $header_image_style .= 'max-width:' . $custom_header->width . 'px;'; } if ( $custom_header->height ) { $header_image_style .= 'height:' . $custom_header->height . 'px;'; } ?> <div id="headimg" style="<?php echo $header_image_style; ?>"> <?php if ( display_header_text() ) { $style = ' style="color:#' . get_header_textcolor() . ';"'; } else { $style = ' style="display:none;"'; } ?> <h1><a id="name" class="displaying-header-text" <?php echo $style; ?> onclick="return false;" href="<?php bloginfo( 'url' ); ?>" tabindex="-1"><?php bloginfo( 'name' ); ?></a></h1> <div id="desc" class="displaying-header-text" <?php echo $style; ?>><?php bloginfo( 'description' ); ?></div> </div> <?php } ?> </td> </tr> <?php endif; ?> <?php if ( current_user_can( 'upload_files' ) && current_theme_supports( 'custom-header', 'uploads' ) ) : ?> <tr> <th scope="row"><?php _e( 'Select Image' ); ?></th> <td> <p><?php _e( 'You can select an image to be shown at the top of your site by uploading from your computer or choosing from your media library. After selecting an image you will be able to crop it.' ); ?><br /> <?php if ( ! current_theme_supports( 'custom-header', 'flex-height' ) && ! current_theme_supports( 'custom-header', 'flex-width' ) ) { printf( /* translators: 1: Image width in pixels, 2: Image height in pixels. */ __( 'Images of exactly <strong>%1$d &times; %2$d pixels</strong> will be used as-is.' ) . '<br />', get_theme_support( 'custom-header', 'width' ), get_theme_support( 'custom-header', 'height' ) ); } elseif ( current_theme_supports( 'custom-header', 'flex-height' ) ) { if ( ! current_theme_supports( 'custom-header', 'flex-width' ) ) { printf( /* translators: %s: Size in pixels. */ __( 'Images should be at least %s wide.' ) . ' ', sprintf( /* translators: %d: Custom header width. */ '<strong>' . __( '%d pixels' ) . '</strong>', get_theme_support( 'custom-header', 'width' ) ) ); } } elseif ( current_theme_supports( 'custom-header', 'flex-width' ) ) { if ( ! current_theme_supports( 'custom-header', 'flex-height' ) ) { printf( /* translators: %s: Size in pixels. */ __( 'Images should be at least %s tall.' ) . ' ', sprintf( /* translators: %d: Custom header height. */ '<strong>' . __( '%d pixels' ) . '</strong>', get_theme_support( 'custom-header', 'height' ) ) ); } } if ( current_theme_supports( 'custom-header', 'flex-height' ) || current_theme_supports( 'custom-header', 'flex-width' ) ) { if ( current_theme_supports( 'custom-header', 'width' ) ) { printf( /* translators: %s: Size in pixels. */ __( 'Suggested width is %s.' ) . ' ', sprintf( /* translators: %d: Custom header width. */ '<strong>' . __( '%d pixels' ) . '</strong>', get_theme_support( 'custom-header', 'width' ) ) ); } if ( current_theme_supports( 'custom-header', 'height' ) ) { printf( /* translators: %s: Size in pixels. */ __( 'Suggested height is %s.' ) . ' ', sprintf( /* translators: %d: Custom header height. */ '<strong>' . __( '%d pixels' ) . '</strong>', get_theme_support( 'custom-header', 'height' ) ) ); } } ?> </p> <form enctype="multipart/form-data" id="upload-form" class="wp-upload-form" method="post" action="<?php echo esc_url( add_query_arg( 'step', 2 ) ); ?>"> <p> <label for="upload"><?php _e( 'Choose an image from your computer:' ); ?></label><br /> <input type="file" id="upload" name="import" /> <input type="hidden" name="action" value="save" /> <?php wp_nonce_field( 'custom-header-upload', '_wpnonce-custom-header-upload' ); ?> <?php submit_button( __( 'Upload' ), '', 'submit', false ); ?> </p> <?php $modal_update_href = add_query_arg( array( 'page' => 'custom-header', 'step' => 2, '_wpnonce-custom-header-upload' => wp_create_nonce( 'custom-header-upload' ), ), admin_url( 'themes.php' ) ); ?> <p> <label for="choose-from-library-link"><?php _e( 'Or choose an image from your media library:' ); ?></label><br /> <button id="choose-from-library-link" class="button" data-update-link="<?php echo esc_url( $modal_update_href ); ?>" data-choose="<?php esc_attr_e( 'Choose a Custom Header' ); ?>" data-update="<?php esc_attr_e( 'Set as header' ); ?>"><?php _e( 'Choose Image' ); ?></button> </p> </form> </td> </tr> <?php endif; ?> </tbody> </table> <form method="post" action="<?php echo esc_url( add_query_arg( 'step', 1 ) ); ?>"> <?php submit_button( null, 'screen-reader-text', 'save-header-options', false ); ?> <table class="form-table" role="presentation"> <tbody> <?php if ( get_uploaded_header_images() ) : ?> <tr> <th scope="row"><?php _e( 'Uploaded Images' ); ?></th> <td> <p><?php _e( 'You can choose one of your previously uploaded headers, or show a random one.' ); ?></p> <?php $this->show_header_selector( 'uploaded' ); ?> </td> </tr> <?php endif; if ( ! empty( $this->default_headers ) ) : ?> <tr> <th scope="row"><?php _e( 'Default Images' ); ?></th> <td> <?php if ( current_theme_supports( 'custom-header', 'uploads' ) ) : ?> <p><?php _e( 'If you don&lsquo;t want to upload your own image, you can use one of these cool headers, or show a random one.' ); ?></p> <?php else : ?> <p><?php _e( 'You can use one of these cool headers or show a random one on each page.' ); ?></p> <?php endif; ?> <?php $this->show_header_selector( 'default' ); ?> </td> </tr> <?php endif; if ( get_header_image() ) : ?> <tr> <th scope="row"><?php _e( 'Remove Image' ); ?></th> <td> <p><?php _e( 'This will remove the header image. You will not be able to restore any customizations.' ); ?></p> <?php submit_button( __( 'Remove Header Image' ), '', 'removeheader', false ); ?> </td> </tr> <?php endif; $default_image = sprintf( get_theme_support( 'custom-header', 'default-image' ), get_template_directory_uri(), get_stylesheet_directory_uri() ); if ( $default_image && get_header_image() !== $default_image ) : ?> <tr> <th scope="row"><?php _e( 'Reset Image' ); ?></th> <td> <p><?php _e( 'This will restore the original header image. You will not be able to restore any customizations.' ); ?></p> <?php submit_button( __( 'Restore Original Header Image' ), '', 'resetheader', false ); ?> </td> </tr> <?php endif; ?> </tbody> </table> <?php if ( current_theme_supports( 'custom-header', 'header-text' ) ) : ?> <h2><?php _e( 'Header Text' ); ?></h2> <table class="form-table" role="presentation"> <tbody> <tr> <th scope="row"><?php _e( 'Header Text' ); ?></th> <td> <p> <label><input type="checkbox" name="display-header-text" id="display-header-text"<?php checked( display_header_text() ); ?> /> <?php _e( 'Show header text with your image.' ); ?></label> </p> </td> </tr> <tr class="displaying-header-text"> <th scope="row"><?php _e( 'Text Color' ); ?></th> <td> <p> <?php $default_color = ''; if ( current_theme_supports( 'custom-header', 'default-text-color' ) ) { $default_color = get_theme_support( 'custom-header', 'default-text-color' ); if ( $default_color && false === strpos( $default_color, '#' ) ) { $default_color = '#' . $default_color; } } $default_color_attr = $default_color ? ' data-default-color="' . esc_attr( $default_color ) . '"' : ''; $header_textcolor = display_header_text() ? get_header_textcolor() : get_theme_support( 'custom-header', 'default-text-color' ); if ( $header_textcolor && false === strpos( $header_textcolor, '#' ) ) { $header_textcolor = '#' . $header_textcolor; } echo '<input type="text" name="text-color" id="text-color" value="' . esc_attr( $header_textcolor ) . '"' . $default_color_attr . ' />'; if ( $default_color ) { /* translators: %s: Default text color. */ echo ' <span class="description hide-if-js">' . sprintf( _x( 'Default: %s', 'color' ), esc_html( $default_color ) ) . '</span>'; } ?> </p> </td> </tr> </tbody> </table> <?php endif; /** * Fires just before the submit button in the custom header options form. * * @since 3.1.0 */ do_action( 'custom_header_options' ); wp_nonce_field( 'custom-header-options', '_wpnonce-custom-header-options' ); ?> <?php submit_button( null, 'primary', 'save-header-options' ); ?> </form> </div> <?php } /** * Display second step of custom header image page. * * @since 2.1.0 */ public function step_2() { check_admin_referer( 'custom-header-upload', '_wpnonce-custom-header-upload' ); if ( ! current_theme_supports( 'custom-header', 'uploads' ) ) { wp_die( '<h1>' . __( 'Something went wrong.' ) . '</h1>' . '<p>' . __( 'The active theme does not support uploading a custom header image.' ) . '</p>', 403 ); } if ( empty( $_POST ) && isset( $_GET['file'] ) ) { $attachment_id = absint( $_GET['file'] ); $file = get_attached_file( $attachment_id, true ); $url = wp_get_attachment_image_src( $attachment_id, 'full' ); $url = $url[0]; } elseif ( isset( $_POST ) ) { $data = $this->step_2_manage_upload(); $attachment_id = $data['attachment_id']; $file = $data['file']; $url = $data['url']; } if ( file_exists( $file ) ) { list( $width, $height, $type, $attr ) = wp_getimagesize( $file ); } else { $data = wp_get_attachment_metadata( $attachment_id ); $height = isset( $data['height'] ) ? (int) $data['height'] : 0; $width = isset( $data['width'] ) ? (int) $data['width'] : 0; unset( $data ); } $max_width = 0; // For flex, limit size of image displayed to 1500px unless theme says otherwise. if ( current_theme_supports( 'custom-header', 'flex-width' ) ) { $max_width = 1500; } if ( current_theme_supports( 'custom-header', 'max-width' ) ) { $max_width = max( $max_width, get_theme_support( 'custom-header', 'max-width' ) ); } $max_width = max( $max_width, get_theme_support( 'custom-header', 'width' ) ); // If flexible height isn't supported and the image is the exact right size. if ( ! current_theme_supports( 'custom-header', 'flex-height' ) && ! current_theme_supports( 'custom-header', 'flex-width' ) && (int) get_theme_support( 'custom-header', 'width' ) === $width && (int) get_theme_support( 'custom-header', 'height' ) === $height ) { // Add the metadata. if ( file_exists( $file ) ) { wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) ); } $this->set_header_image( compact( 'url', 'attachment_id', 'width', 'height' ) ); /** * Fires after the header image is set or an error is returned. * * @since 2.1.0 * * @param string $file Path to the file. * @param int $attachment_id Attachment ID. */ do_action( 'wp_create_file_in_uploads', $file, $attachment_id ); // For replication. return $this->finished(); } elseif ( $width > $max_width ) { $oitar = $width / $max_width; $image = wp_crop_image( $attachment_id, 0, 0, $width, $height, $max_width, $height / $oitar, false, str_replace( wp_basename( $file ), 'midsize-' . wp_basename( $file ), $file ) ); if ( ! $image || is_wp_error( $image ) ) { wp_die( __( 'Image could not be processed. Please go back and try again.' ), __( 'Image Processing Error' ) ); } /** This filter is documented in wp-admin/includes/class-custom-image-header.php */ $image = apply_filters( 'wp_create_file_in_uploads', $image, $attachment_id ); // For replication. $url = str_replace( wp_basename( $url ), wp_basename( $image ), $url ); $width = $width / $oitar; $height = $height / $oitar; } else { $oitar = 1; } ?> <div class="wrap"> <h1><?php _e( 'Crop Header Image' ); ?></h1> <form method="post" action="<?php echo esc_url( add_query_arg( 'step', 3 ) ); ?>"> <p class="hide-if-no-js"><?php _e( 'Choose the part of the image you want to use as your header.' ); ?></p> <p class="hide-if-js"><strong><?php _e( 'You need JavaScript to choose a part of the image.' ); ?></strong></p> <div id="crop_image" style="position: relative"> <img src="<?php echo esc_url( $url ); ?>" id="upload" width="<?php echo $width; ?>" height="<?php echo $height; ?>" alt="" /> </div> <input type="hidden" name="x1" id="x1" value="0" /> <input type="hidden" name="y1" id="y1" value="0" /> <input type="hidden" name="width" id="width" value="<?php echo esc_attr( $width ); ?>" /> <input type="hidden" name="height" id="height" value="<?php echo esc_attr( $height ); ?>" /> <input type="hidden" name="attachment_id" id="attachment_id" value="<?php echo esc_attr( $attachment_id ); ?>" /> <input type="hidden" name="oitar" id="oitar" value="<?php echo esc_attr( $oitar ); ?>" /> <?php if ( empty( $_POST ) && isset( $_GET['file'] ) ) { ?> <input type="hidden" name="create-new-attachment" value="true" /> <?php } ?> <?php wp_nonce_field( 'custom-header-crop-image' ); ?> <p class="submit"> <?php submit_button( __( 'Crop and Publish' ), 'primary', 'submit', false ); ?> <?php if ( isset( $oitar ) && 1 === $oitar && ( current_theme_supports( 'custom-header', 'flex-height' ) || current_theme_supports( 'custom-header', 'flex-width' ) ) ) { submit_button( __( 'Skip Cropping, Publish Image as Is' ), '', 'skip-cropping', false ); } ?> </p> </form> </div> <?php } /** * Upload the file to be cropped in the second step. * * @since 3.4.0 */ public function step_2_manage_upload() { $overrides = array( 'test_form' => false ); $uploaded_file = $_FILES['import']; $wp_filetype = wp_check_filetype_and_ext( $uploaded_file['tmp_name'], $uploaded_file['name'] ); if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) ) { wp_die( __( 'The uploaded file is not a valid image. Please try again.' ) ); } $file = wp_handle_upload( $uploaded_file, $overrides ); if ( isset( $file['error'] ) ) { wp_die( $file['error'], __( 'Image Upload Error' ) ); } $url = $file['url']; $type = $file['type']; $file = $file['file']; $filename = wp_basename( $file ); // Construct the attachment array. $attachment = array( 'post_title' => $filename, 'post_content' => $url, 'post_mime_type' => $type, 'guid' => $url, 'context' => 'custom-header', ); // Save the data. $attachment_id = wp_insert_attachment( $attachment, $file ); return compact( 'attachment_id', 'file', 'filename', 'url', 'type' ); } /** * Display third step of custom header image page. * * @since 2.1.0 * @since 4.4.0 Switched to using wp_get_attachment_url() instead of the guid * for retrieving the header image URL. */ public function step_3() { check_admin_referer( 'custom-header-crop-image' ); if ( ! current_theme_supports( 'custom-header', 'uploads' ) ) { wp_die( '<h1>' . __( 'Something went wrong.' ) . '</h1>' . '<p>' . __( 'The active theme does not support uploading a custom header image.' ) . '</p>', 403 ); } if ( ! empty( $_POST['skip-cropping'] ) && ! current_theme_supports( 'custom-header', 'flex-height' ) && ! current_theme_supports( 'custom-header', 'flex-width' ) ) { wp_die( '<h1>' . __( 'Something went wrong.' ) . '</h1>' . '<p>' . __( 'The active theme does not support a flexible sized header image.' ) . '</p>', 403 ); } if ( $_POST['oitar'] > 1 ) { $_POST['x1'] = $_POST['x1'] * $_POST['oitar']; $_POST['y1'] = $_POST['y1'] * $_POST['oitar']; $_POST['width'] = $_POST['width'] * $_POST['oitar']; $_POST['height'] = $_POST['height'] * $_POST['oitar']; } $attachment_id = absint( $_POST['attachment_id'] ); $original = get_attached_file( $attachment_id ); $dimensions = $this->get_header_dimensions( array( 'height' => $_POST['height'], 'width' => $_POST['width'], ) ); $height = $dimensions['dst_height']; $width = $dimensions['dst_width']; if ( empty( $_POST['skip-cropping'] ) ) { $cropped = wp_crop_image( $attachment_id, (int) $_POST['x1'], (int) $_POST['y1'], (int) $_POST['width'], (int) $_POST['height'], $width, $height ); } elseif ( ! empty( $_POST['create-new-attachment'] ) ) { $cropped = _copy_image_file( $attachment_id ); } else { $cropped = get_attached_file( $attachment_id ); } if ( ! $cropped || is_wp_error( $cropped ) ) { wp_die( __( 'Image could not be processed. Please go back and try again.' ), __( 'Image Processing Error' ) ); } /** This filter is documented in wp-admin/includes/class-custom-image-header.php */ $cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication. $attachment = $this->create_attachment_object( $cropped, $attachment_id ); if ( ! empty( $_POST['create-new-attachment'] ) ) { unset( $attachment['ID'] ); } // Update the attachment. $attachment_id = $this->insert_attachment( $attachment, $cropped ); $url = wp_get_attachment_url( $attachment_id ); $this->set_header_image( compact( 'url', 'attachment_id', 'width', 'height' ) ); // Cleanup. $medium = str_replace( wp_basename( $original ), 'midsize-' . wp_basename( $original ), $original ); if ( file_exists( $medium ) ) { wp_delete_file( $medium ); } if ( empty( $_POST['create-new-attachment'] ) && empty( $_POST['skip-cropping'] ) ) { wp_delete_file( $original ); } return $this->finished(); } /** * Display last step of custom header image page. * * @since 2.1.0 */ public function finished() { $this->updated = true; $this->step_1(); } /** * Display the page based on the current step. * * @since 2.1.0 */ public function admin_page() { if ( ! current_user_can( 'edit_theme_options' ) ) { wp_die( __( 'Sorry, you are not allowed to customize headers.' ) ); } $step = $this->step(); if ( 2 === $step ) { $this->step_2(); } elseif ( 3 === $step ) { $this->step_3(); } else { $this->step_1(); } } /** * Unused since 3.5.0. * * @since 3.4.0 * * @param array $form_fields * @return array $form_fields */ public function attachment_fields_to_edit( $form_fields ) { return $form_fields; } /** * Unused since 3.5.0. * * @since 3.4.0 * * @param array $tabs * @return array $tabs */ public function filter_upload_tabs( $tabs ) { return $tabs; } /** * Choose a header image, selected from existing uploaded and default headers, * or provide an array of uploaded header data (either new, or from media library). * * @since 3.4.0 * * @param mixed $choice Which header image to select. Allows for values of 'random-default-image', * for randomly cycling among the default images; 'random-uploaded-image', for randomly cycling * among the uploaded images; the key of a default image registered for that theme; and * the key of an image uploaded for that theme (the attachment ID of the image). * Or an array of arguments: attachment_id, url, width, height. All are required. */ final public function set_header_image( $choice ) { if ( is_array( $choice ) || is_object( $choice ) ) { $choice = (array) $choice; if ( ! isset( $choice['attachment_id'] ) || ! isset( $choice['url'] ) ) { return; } $choice['url'] = sanitize_url( $choice['url'] ); $header_image_data = (object) array( 'attachment_id' => $choice['attachment_id'], 'url' => $choice['url'], 'thumbnail_url' => $choice['url'], 'height' => $choice['height'], 'width' => $choice['width'], ); update_post_meta( $choice['attachment_id'], '_wp_attachment_is_custom_header', get_stylesheet() ); set_theme_mod( 'header_image', $choice['url'] ); set_theme_mod( 'header_image_data', $header_image_data ); return; } if ( in_array( $choice, array( 'remove-header', 'random-default-image', 'random-uploaded-image' ), true ) ) { set_theme_mod( 'header_image', $choice ); remove_theme_mod( 'header_image_data' ); return; } $uploaded = get_uploaded_header_images(); if ( $uploaded && isset( $uploaded[ $choice ] ) ) { $header_image_data = $uploaded[ $choice ]; } else { $this->process_default_headers(); if ( isset( $this->default_headers[ $choice ] ) ) { $header_image_data = $this->default_headers[ $choice ]; } else { return; } } set_theme_mod( 'header_image', sanitize_url( $header_image_data['url'] ) ); set_theme_mod( 'header_image_data', $header_image_data ); } /** * Remove a header image. * * @since 3.4.0 */ final public function remove_header_image() { $this->set_header_image( 'remove-header' ); } /** * Reset a header image to the default image for the theme. * * This method does not do anything if the theme does not have a default header image. * * @since 3.4.0 */ final public function reset_header_image() { $this->process_default_headers(); $default = get_theme_support( 'custom-header', 'default-image' ); if ( ! $default ) { $this->remove_header_image(); return; } $default = sprintf( $default, get_template_directory_uri(), get_stylesheet_directory_uri() ); $default_data = array(); foreach ( $this->default_headers as $header => $details ) { if ( $details['url'] === $default ) { $default_data = $details; break; } } set_theme_mod( 'header_image', $default ); set_theme_mod( 'header_image_data', (object) $default_data ); } /** * Calculate width and height based on what the currently selected theme supports. * * @since 3.9.0 * * @param array $dimensions * @return array dst_height and dst_width of header image. */ final public function get_header_dimensions( $dimensions ) { $max_width = 0; $width = absint( $dimensions['width'] ); $height = absint( $dimensions['height'] ); $theme_height = get_theme_support( 'custom-header', 'height' ); $theme_width = get_theme_support( 'custom-header', 'width' ); $has_flex_width = current_theme_supports( 'custom-header', 'flex-width' ); $has_flex_height = current_theme_supports( 'custom-header', 'flex-height' ); $has_max_width = current_theme_supports( 'custom-header', 'max-width' ); $dst = array( 'dst_height' => null, 'dst_width' => null, ); // For flex, limit size of image displayed to 1500px unless theme says otherwise. if ( $has_flex_width ) { $max_width = 1500; } if ( $has_max_width ) { $max_width = max( $max_width, get_theme_support( 'custom-header', 'max-width' ) ); } $max_width = max( $max_width, $theme_width ); if ( $has_flex_height && ( ! $has_flex_width || $width > $max_width ) ) { $dst['dst_height'] = absint( $height * ( $max_width / $width ) ); } elseif ( $has_flex_height && $has_flex_width ) { $dst['dst_height'] = $height; } else { $dst['dst_height'] = $theme_height; } if ( $has_flex_width && ( ! $has_flex_height || $width > $max_width ) ) { $dst['dst_width'] = absint( $width * ( $max_width / $width ) ); } elseif ( $has_flex_width && $has_flex_height ) { $dst['dst_width'] = $width; } else { $dst['dst_width'] = $theme_width; } return $dst; } /** * Create an attachment 'object'. * * @since 3.9.0 * * @param string $cropped Cropped image URL. * @param int $parent_attachment_id Attachment ID of parent image. * @return array An array with attachment object data. */ final public function create_attachment_object( $cropped, $parent_attachment_id ) { $parent = get_post( $parent_attachment_id ); $parent_url = wp_get_attachment_url( $parent->ID ); $url = str_replace( wp_basename( $parent_url ), wp_basename( $cropped ), $parent_url ); $size = wp_getimagesize( $cropped ); $image_type = ( $size ) ? $size['mime'] : 'image/jpeg'; $attachment = array( 'ID' => $parent_attachment_id, 'post_title' => wp_basename( $cropped ), 'post_mime_type' => $image_type, 'guid' => $url, 'context' => 'custom-header', 'post_parent' => $parent_attachment_id, ); return $attachment; } /** * Insert an attachment and its metadata. * * @since 3.9.0 * * @param array $attachment An array with attachment object data. * @param string $cropped File path to cropped image. * @return int Attachment ID. */ final public function insert_attachment( $attachment, $cropped ) { $parent_id = isset( $attachment['post_parent'] ) ? $attachment['post_parent'] : null; unset( $attachment['post_parent'] ); $attachment_id = wp_insert_attachment( $attachment, $cropped ); $metadata = wp_generate_attachment_metadata( $attachment_id, $cropped ); // If this is a crop, save the original attachment ID as metadata. if ( $parent_id ) { $metadata['attachment_parent'] = $parent_id; } /** * Filters the header image attachment metadata. * * @since 3.9.0 * * @see wp_generate_attachment_metadata() * * @param array $metadata Attachment metadata. */ $metadata = apply_filters( 'wp_header_image_attachment_metadata', $metadata ); wp_update_attachment_metadata( $attachment_id, $metadata ); return $attachment_id; } /** * Gets attachment uploaded by Media Manager, crops it, then saves it as a * new object. Returns JSON-encoded object details. * * @since 3.9.0 */ public function ajax_header_crop() { check_ajax_referer( 'image_editor-' . $_POST['id'], 'nonce' ); if ( ! current_user_can( 'edit_theme_options' ) ) { wp_send_json_error(); } if ( ! current_theme_supports( 'custom-header', 'uploads' ) ) { wp_send_json_error(); } $crop_details = $_POST['cropDetails']; $dimensions = $this->get_header_dimensions( array( 'height' => $crop_details['height'], 'width' => $crop_details['width'], ) ); $attachment_id = absint( $_POST['id'] ); $cropped = wp_crop_image( $attachment_id, (int) $crop_details['x1'], (int) $crop_details['y1'], (int) $crop_details['width'], (int) $crop_details['height'], (int) $dimensions['dst_width'], (int) $dimensions['dst_height'] ); if ( ! $cropped || is_wp_error( $cropped ) ) { wp_send_json_error( array( 'message' => __( 'Image could not be processed. Please go back and try again.' ) ) ); } /** This filter is documented in wp-admin/includes/class-custom-image-header.php */ $cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication. $attachment = $this->create_attachment_object( $cropped, $attachment_id ); $previous = $this->get_previous_crop( $attachment ); if ( $previous ) { $attachment['ID'] = $previous; } else { unset( $attachment['ID'] ); } $new_attachment_id = $this->insert_attachment( $attachment, $cropped ); $attachment['attachment_id'] = $new_attachment_id; $attachment['url'] = wp_get_attachment_url( $new_attachment_id ); $attachment['width'] = $dimensions['dst_width']; $attachment['height'] = $dimensions['dst_height']; wp_send_json_success( $attachment ); } /** * Given an attachment ID for a header image, updates its "last used" * timestamp to now. * * Triggered when the user tries adds a new header image from the * Media Manager, even if s/he doesn't save that change. * * @since 3.9.0 */ public function ajax_header_add() { check_ajax_referer( 'header-add', 'nonce' ); if ( ! current_user_can( 'edit_theme_options' ) ) { wp_send_json_error(); } $attachment_id = absint( $_POST['attachment_id'] ); if ( $attachment_id < 1 ) { wp_send_json_error(); } $key = '_wp_attachment_custom_header_last_used_' . get_stylesheet(); update_post_meta( $attachment_id, $key, time() ); update_post_meta( $attachment_id, '_wp_attachment_is_custom_header', get_stylesheet() ); wp_send_json_success(); } /** * Given an attachment ID for a header image, unsets it as a user-uploaded * header image for the active theme. * * Triggered when the user clicks the overlay "X" button next to each image * choice in the Customizer's Header tool. * * @since 3.9.0 */ public function ajax_header_remove() { check_ajax_referer( 'header-remove', 'nonce' ); if ( ! current_user_can( 'edit_theme_options' ) ) { wp_send_json_error(); } $attachment_id = absint( $_POST['attachment_id'] ); if ( $attachment_id < 1 ) { wp_send_json_error(); } $key = '_wp_attachment_custom_header_last_used_' . get_stylesheet(); delete_post_meta( $attachment_id, $key ); delete_post_meta( $attachment_id, '_wp_attachment_is_custom_header', get_stylesheet() ); wp_send_json_success(); } /** * Updates the last-used postmeta on a header image attachment after saving a new header image via the Customizer. * * @since 3.9.0 * * @param WP_Customize_Manager $wp_customize Customize manager. */ public function customize_set_last_used( $wp_customize ) { $header_image_data_setting = $wp_customize->get_setting( 'header_image_data' ); if ( ! $header_image_data_setting ) { return; } $data = $header_image_data_setting->post_value(); if ( ! isset( $data['attachment_id'] ) ) { return; } $attachment_id = $data['attachment_id']; $key = '_wp_attachment_custom_header_last_used_' . get_stylesheet(); update_post_meta( $attachment_id, $key, time() ); } /** * Gets the details of default header images if defined. * * @since 3.9.0 * * @return array Default header images. */ public function get_default_header_images() { $this->process_default_headers(); // Get the default image if there is one. $default = get_theme_support( 'custom-header', 'default-image' ); if ( ! $default ) { // If not, easy peasy. return $this->default_headers; } $default = sprintf( $default, get_template_directory_uri(), get_stylesheet_directory_uri() ); $already_has_default = false; foreach ( $this->default_headers as $k => $h ) { if ( $h['url'] === $default ) { $already_has_default = true; break; } } if ( $already_has_default ) { return $this->default_headers; } // If the one true image isn't included in the default set, prepend it. $header_images = array(); $header_images['default'] = array( 'url' => $default, 'thumbnail_url' => $default, 'description' => 'Default', ); // The rest of the set comes after. return array_merge( $header_images, $this->default_headers ); } /** * Gets the previously uploaded header images. * * @since 3.9.0 * * @return array Uploaded header images. */ public function get_uploaded_header_images() { $header_images = get_uploaded_header_images(); $timestamp_key = '_wp_attachment_custom_header_last_used_' . get_stylesheet(); $alt_text_key = '_wp_attachment_image_alt'; foreach ( $header_images as &$header_image ) { $header_meta = get_post_meta( $header_image['attachment_id'] ); $header_image['timestamp'] = isset( $header_meta[ $timestamp_key ] ) ? $header_meta[ $timestamp_key ] : ''; $header_image['alt_text'] = isset( $header_meta[ $alt_text_key ] ) ? $header_meta[ $alt_text_key ] : ''; } return $header_images; } /** * Get the ID of a previous crop from the same base image. * * @since 4.9.0 * * @param array $attachment An array with a cropped attachment object data. * @return int|false An attachment ID if one exists. False if none. */ public function get_previous_crop( $attachment ) { $header_images = $this->get_uploaded_header_images(); // Bail early if there are no header images. if ( empty( $header_images ) ) { return false; } $previous = false; foreach ( $header_images as $image ) { if ( $image['attachment_parent'] === $attachment['post_parent'] ) { $previous = $image['attachment_id']; break; } } return $previous; } } ``` | Version | Description | | --- | --- | | [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
programming_docs
wordpress class wpdb {} class wpdb {} ============= An instantiated *<wpdb>* class can talk to any number of tables, but only to one database at a time. In the rare case you need to connect to another database, instantiate your own object from the *<wpdb>* class with your own database connection information. **Note:** Each method contained within the class is listed in the Methods section (below). In addition, each method has its own help page; this is where you’ll find detailed usage information for the method you’re interested in. Some of the methods in this class take an SQL statement as input. **All untrusted values in an SQL statement m****ust be escaped** to prevent SQL injection attacks. Some methods will escape SQL for you; others will not. Check the documentation to be sure before you use any method in this class. For more on SQL escaping in WordPress, see the section entitled Protect Queries Against SQL Injection Attacks below. WordPress provides a global object, `$wpdb`, which is an instantiation of the *<wpdb>* class. By default, `$wpdb` is instantiated to talk to the WordPress database. The recommended way to access `$wpdb` in your WordPress PHP code is to declare `$wpdb` as a global variable using the [`global` keyword](http://www.php.net/manual/en/language.variables.scope.php#language.variables.scope.global), like this: ``` <?php // 1st Method - Declaring $wpdb as global and using it to execute an SQL query statement that returns a PHP object global $wpdb; $results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT ); ``` Alternatively, if the above doesn’t suit your needs for whatever reason, use the [superglobal `$GLOBALS`](http://www.php.net/manual/en/language.variables.superglobals.php) in the following manner: ``` <?php // 2nd Method - Utilizing the $GLOBALS superglobal. Does not require global keyword ( but may not be best practice ) $results = $GLOBALS['wpdb']->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT ); ``` The `$wpdb` object can be used to read data from *any* table in the WordPress database, not just those created by WordPress itself. > For a more complete overview of SQL escaping in WordPress, see [database Data Validation](https://codex.wordpress.org/Data_Validation#Database "Data Validation"). It is a **must-read** for all WordPress code contributors and plugin authors. > > All data in SQL queries must be SQL-escaped before the SQL query is executed to prevent against SQL injection attacks. The `prepare` method performs this functionality for WordPress, which supports both a [sprintf()](http://php.net/sprintf)-like and [vsprintf()](http://php.net/vsprintf)-like syntax. Using it looks like this: ``` <?php $sql = $wpdb->prepare( 'query' , value_parameter[, value_parameter ... ] ); ``` `query` *(string)* The SQL query you wish to execute, with placeholders (see below). `value_parameter` *(int|string|array)* The value to substitute into the placeholder. Many values may be passed by simply passing more arguments in a [sprintf()](http://php.net/sprintf)-like fashion. Alternatively the second argument can be an array containing the values as in PHP’s [vsprintf()](http://php.net/vsprintf) function. Care must be taken not to allow direct user input to this parameter, which would enable array manipulation of any query with multiple placeholders.**Note:** Values cannot be SQL-escaped. The `query` parameter for `prepare` accepts [sprintf()](http://php.net/sprintf)-like placeholders: * `%s` (string) * `%d` (integer) * `%f` (float) Notes on placeholders 1. Any other `%` characters may cause parsing errors unless they are escaped. 2. All `%` characters inside SQL string literals, including LIKE wildcards, must be double-% escaped as `%%`. 3. Leave `%d`, `%f`, and `%s` unquoted in the query string. Add Meta key => value pair β€œFunny Phrases” => β€œWordPress’ database interface is like Sunday Morning: Easy.” to Post 10. ``` <?php $metakey = 'Funny Phrases'; $metavalue = "WordPress' database interface is like Sunday Morning: Easy."; $wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->postmeta ( post_id, meta_key, meta_value ) VALUES ( %d, %s, %s )", 10, $metakey, $metavalue ) ); ``` The same query using [vsprintf()](http://php.net/vsprintf)-like syntax. Note that in this example we pack the values together in an array. This can be useful when we don’t know the number of arguments we need to pass until runtime. ``` <?php $metakey = 'Funny Phrases'; $metavalue = "WordPress' database interface is like Sunday Morning: Easy."; $wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->postmeta ( post_id, meta_key, meta_value ) VALUES ( %d, %s, %s )", array( 10, $metakey, $metavalue, ) ) ); ``` In both cases, we do not need to escape the strings because we are passing them using placeholders. You can pass as many values as you like, provided each one has a corresponding placeholder in the `prepare()` method call. Each of the class’s properties and methods are listed below, and most have their own help page that you should consult for detailed usage information. This section, however, gives an overview of some of the more common tasks this class can be used to perform. The [`get_var`](wpdb/get_var) function returns a single variable from the database. Though only one variable is returned, the entire result of the query is cached for later use. Returns NULL if no result is found. ``` <?php $wpdb->get_var( 'query', column_offset, row_offset ); ?> ``` **`query`** *(string)* The query you wish to run. Setting this parameter to `null` will return the specified variable from the cached results of the previous query. **`column_offset`** *(integer)* The desired column (0 being the first). Defaults to 0. **`row_offset`** *(integer)* The desired row (0 being the first). Defaults to 0. Retrieve and display the number of users. ``` <?php $user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users" ); echo "<p>User count is {$user_count}</p>"; ?> ``` Retrieve and display the sum of a Custom Field value. ``` <?php // set the meta_key to the appropriate custom field meta key $meta_key = 'miles'; $allmiles = $wpdb->get_var( $wpdb->prepare( " SELECT sum(meta_value) FROM $wpdb->postmeta WHERE meta_key = %s ", $meta_key ) ); echo "<p>Total miles is {$allmiles}</p>"; ?> ``` To retrieve an entire row from a query, use [`get_row`](wpdb/get_row). The function can return the row as an object, an associative array, or as a numerically indexed array. If more than one row is returned by the query, only the specified row is returned by the function, but all rows are cached for later use. Returns `null` if no result is found, consider this when using the returned value in arguments, see example below. ``` <?php $wpdb->get_row('query', output_type, row_offset); ?> ``` **`query`** *(string)* The query you wish to run. **`output_type`** One of three pre-defined constants. Defaults to `OBJECT`. * `OBJECT` – result will be output as an object. * `ARRAY_A` – result will be output as an associative array. * `ARRAY_N` – result will be output as a numerically indexed array. **`row_offset`** *(integer)* The desired row (0 being the first). Defaults to 0. Get all the information about Link 10. ``` $mylink = $wpdb->get_row( "SELECT * FROM $wpdb->links WHERE link_id = 10" ); ``` The properties of the <code>$mylink</code> object are the column names of the result from the SQL query (in this example all the columns from the <code>$<wpdb>->links</code> table, but you could also query for specific columns only). ``` echo $mylink->link_id; // prints "10" ``` In contrast, using ``` $mylink = $wpdb->get_row( "SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_A ); ``` would result in an associative array: ``` echo $mylink['link_id']; // prints "10" ``` and ``` $mylink = $wpdb->get_row( "SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_N ); ``` would result in a numerically indexed array: ``` echo $mylink[1]; // prints "10" ``` If there is no record with ID 10 in the links table, `null` will be returned. The following would then be false: ``` if ( null !== $mylink ) { // do something with the link return true; } else { // no link found return false; } ``` To SELECT a column, use [`get_col`](wpdb/get_col). This method outputs a one dimensional array. If more than one column is returned by the query, only the specified column will be returned, but the entire result is cached for later use. Returns an empty array if no result is found. ``` get_col( 'query', column_offset ); ?> ``` **`query`** *(string)* the query you wish to execute. Setting this parameter to `null` will return the specified column from the cached results of the previous query. **`column_offset`** *(integer)* The desired column (0 being the first). Defaults to 0. For this example, assume the blog is devoted to information about automobiles. Each post describes a particular car (e.g. 1969 Ford Mustang), and three Custom Fields, manufacturer, model, and year, are assigned to each post. This example will display the post titles, filtered by a particular manufacturer (Ford), and sorted by model and year. The **get\_col** method is used to return an array of all the post ids meeting the criteria and sorted in the correct order. Then a `foreach` construct is used to iterate through that array of post ids, displaying the title of each post. Note that the SQL for this example was created by [Andomar](http://stackoverflow.com/questions/1690762/complicated-mysql-query/1690808#1690808). ``` <?php $meta_key1 = 'model'; $meta_key2 = 'year'; $meta_key3 = 'manufacturer'; $meta_key3_value = 'Ford'; $postids = $wpdb->get_col( $wpdb->prepare( " SELECT key3.post_id FROM $wpdb->postmeta key3 INNER JOIN $wpdb->postmeta key1 ON key1.post_id = key3.post_id AND key1.meta_key = %s INNER JOIN $wpdb->postmeta key2 ON key2.post_id = key3.post_id AND key2.meta_key = %s WHERE key3.meta_key = %s AND key3.meta_value = %s ORDER BY key1.meta_value, key2.meta_value ", $meta_key1, $meta_key2, $meta_key3, $meta_key3_value ) ); if ( $postids ) { echo "List of {$meta_key3_value}(s), sorted by {$meta_key1}, {$meta_key2}"; foreach ( $postids as $id ) { $post = get_post( intval( $id ) ); setup_postdata( $post ); ?> <p> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"> <?php the_title(); ?> </a> </p> <?php } } ?> ``` This example lists all posts that contain a particular custom field, but sorted by the value of a second custom field. ``` <?php // List all posts with custom field Color, sorted by the value of custom field Display_Order // does not exclude any 'post_type' // assumes each post has just one custom field for Color, and one for Display_Order $meta_key1 = 'Color'; $meta_key2 = 'Display_Order'; $postids = $wpdb->get_col( $wpdb->prepare( " SELECT key1.post_id FROM $wpdb->postmeta key1 INNER JOIN $wpdb->postmeta key2 ON key2.post_id = key1.post_id AND key2.meta_key = %s WHERE key1.meta_key = %s ORDER BY key2.meta_value+(0) ASC ", $meta_key2, $meta_key1 ) ); if ( $postids ) { echo "List of {$meta_key1} posts, sorted by {$meta_key2}"; foreach ( $postids as $id ) { $post = get_post( intval( $id ) ); setup_postdata( $post ); ?> <p> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"> <?php the_title(); ?> </a> </p> <?php } } ?> ``` Generic, multiple row results can be pulled from the database with [`get_results`](wpdb/get_results). The method returns the entire query result as an array. Each element of this array corresponds to one row of the query result and, like `get_row`, can be an object, an associative array, or a numbered array. If no matching rows are found, or if there is a database error, the return value will be an empty array. If your `$query` string is empty, or you pass an invalid `$output_type`, `NULL` will be returned. ``` get_results( 'query', output_type ); ``` **`query`** *(string)* The query you wish to run. **`output_type`** One of four pre-defined constants. Defaults to `OBJECT`. See [SELECT a Row](https://codex.wordpress.org/Class_Reference/wpdb#SELECT_a_Row) and its examples for more information. * **`OBJECT`** – result will be output as a numerically indexed array of row objects. * **`OBJECT_K`** – result will be output as an associative array of row objects, using first column’s values as keys (duplicates will be discarded). * **`ARRAY_A`** – result will be output as a numerically indexed array of associative arrays, using column names as keys. * **`ARRAY_N`** – result will be output as a numerically indexed array of numerically indexed arrays. Since this method uses the `$wpdb->query()` method, all the class variables are properly set. The results count for a β€˜SELECT’ query will be stored in `$wpdb->num_rows`. Get the IDs and Titles of all the Drafts by User 5 and echo the Titles. ``` $fivesdrafts = $wpdb->get_results( " SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'draft' AND post_author = 5 " ); foreach ( $fivesdrafts as $fivesdraft ) { echo $fivesdraft->post_title; } ``` Get all information on the Drafts by User 5. ``` <?php $fivesdrafts = $wpdb->get_results( " SELECT * FROM $wpdb->posts WHERE post_status = 'draft' AND post_author = 5 " ); if ( $fivesdrafts ) { foreach ( $fivesdrafts as $post ) { setup_postdata( $post ); ?> <h2> <a href="<?php the_permalink(); ?>" rel="bookmark" title="Permalink: <?php the_title(); ?>"> <?php the_title(); ?> </a> </h2> <?php } } else { ?> <h2>Not Found</h2> <?php } ?> ``` The [`insert`](wpdb/insert) method is used to insert a row into a table. ``` insert( $table, $data, $format ); ``` **`$table`** *(string)* The name of the table to insert data into. **`$data`** *(array)* Data to insert (in column => value pairs). Both `$data` columns and `$data` values should be β€œraw” (neither should be SQL escaped). **`$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`. If omitted, all values in `$data` will be treated as strings unless otherwise specified in `wpdb::$field_types`. Possible format values: `%s` as string; `%d` as integer (whole number); and `%f` as float. (See [below](https://codex.wordpress.org/Class_Reference/wpdb#Placeholders) for more information.) **Note:** After insert, the ID generated for the `AUTO_INCREMENT` column can be accessed with: ``` $wpdb->insert_id ``` This method returns `false` if the row could not be inserted. Otherwise, it returns the number of affected rows (which will always be 1). **Please note**: The value portion of the data parameter’s column=>value pairs must be scalar. If you pass an array (or object) as a value to be inserted you will generate a warning. Insert two columns in a row, the first value being a string and the second a number: ``` $wpdb->insert( 'table', array( 'column1' => 'value1', 'column2' => 123, ), array( '%s', '%d', ) ); ``` The [`replace`](wpdb/replace) method replaces a row in a table if it exists or inserts a new row in a table if the row did not already exist. ``` replace( $table, $data, $format ); ``` **`$table`** *(string)* The name of the table to replace data in. **`$data`** *(array)* Data to replace (in column => value pairs). Both `$data` columns and `$data` values should be β€œraw” (neither should be SQL escaped). **`$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`. If omitted, all values in `$data` will be treated as strings unless otherwise specified in `wpdb::$field_types`. Possible format values: `%s` as string; `%d` as integer (whole number); and `%f` as float. (See [below](https://codex.wordpress.org/Class_Reference/wpdb#Placeholders) for more information.) If the length of a string element in the `$data` array parameter is longer that the defined length in the MySql database table, the insert will fail, this method will return `false`, but $<wpdb>->last\_error will not be set to a descriptive message. You must ensure the data you wish to insert will fit in the database – do not assume the MySql will truncate the data. After replace, the ID generated for the `AUTO_INCREMENT` column can be accessed with: ``` $wpdb->insert_id ``` This method returns a count to indicate the number of rows affected. This is the sum of the rows deleted and inserted. If the count is 1 for a single-row REPLACE, a row was inserted and no rows were deleted. If the count is greater than 1, one or more old rows were deleted before the new row was inserted. It is possible for a single row to replace more than one old row if the table contains multiple unique indexes and the new row duplicates values for different old rows in different unique indexes. This method returns `false` if an existing row could not be replaced and a new row could not be inserted. Replace a row, the first value being the row id, the second a string and the third a number: ``` $wpdb->replace( 'table', array( 'indexed_id' => 1, 'column1' => 'value1', 'column2' => 123, ), array( '%d', '%s', '%d', ) ); ``` Update a row in the table. Returns `false` if errors, or the number of rows affected if successful. ([`wpdb::update`](wpdb/update)) ``` update( $table, $data, $where, $format = null, $where_format = null ); ``` **`$table`** *(string)* The name of the table to update. **`$data`** *(array)* Data to update (in `column => value` pairs). Both `$data` columns and `$data` values should be β€œraw” (neither should be SQL escaped). This means that if you are using `GET` or `POST` data you may need to use `stripslashes()` to avoid slashes ending up in the database. **`$where`** *(array)* A named array of `WHERE` clauses (in `column => value` pairs). Multiple clauses will be joined with `AND`s. Both `$where` columns and `$where` values should be β€œraw”. **`$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`. **`$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`. Possible format values: `%s` as string; `%d` as integer (whole number) and `%f` as float. (See [below](https://codex.wordpress.org/Class_Reference/wpdb#Placeholders) for more information.) If omitted, all values in `$where` will be treated as strings. This method returns the number of rows updated, or `false` if there is an error. Keep in mind that if the `$data` matches what is already in the database, no rows will be updated, so `0` will be returned. Because of this, you should probably check the return with `false === $result` Update a row, where the ID is 1, the value in the first column is a string and the value in the second column is a number: ``` $wpdb->update( 'table', array( 'column1' => 'value1', // string 'column2' => 'value2' // integer (number) ), array( 'ID' => 1 ), array( '%s', // value1 '%d' // value2 ), array( '%d' ) ); ``` **Attention:** `%d` can’t deal with comma values – if you’re *not* using full numbers, use string/`%s`. The [`delete`](wpdb/delete) method is used to delete rows from a table. The usage is very similar to `update` and `insert`. It returns the number of rows updated, or `false` on error. ``` delete( $table, $where, $where_format = null ); ``` **`$table`** (*string*) (*required*) Table name.Default: *None* **`$where`** (*array*) (*required*) A named array of `WHERE` clauses (in column -> value pairs). Multiple clauses will be joined with `AND`s. Both `$where` columns and `$where` values should be β€˜raw’. Default: *None* **`$where_format`** (*string/array*) (*optional*) An array of formats to be mapped to each of the values in `$where`. If a string, that format will be used for all of the items in `$where`. A format is one of `'%d'`, `'%f'`, `'%s'` (integer, float, string; see [below](https://codex.wordpress.org/Class_Reference/wpdb#Placeholders) for more information). If omitted, all values in `$where` will be treated as strings unless otherwise specified in `wpdb::$field_types`. Default: `null` ``` // Default usage. $wpdb->delete( 'table', array( 'ID' => 1 ) ); // Using where formatting. $wpdb->delete( 'table', array( 'ID' => 1 ), array( '%d' ) ); ``` The `query` method allows you to execute any SQL query on the WordPress database. It is best used when there is a need for specific, custom, or otherwise complex SQL queries. For more basic queries, such as selecting information from a table, see the other `wpdb` methods above such as `get_results, get_var, get_row or get_col`. ``` query('query'); ``` **`query`** *(string)* The SQL query you wish to execute. This method returns an integer value indicating the number of rows affected/selected for SELECT, INSERT, DELETE, UPDATE, etc. For CREATE, ALTER, TRUNCATE and DROP SQL statements, (which affect whole tables instead of specific rows) this method returns `TRUE` on success. If a MySQL error is encountered, the method will return `FALSE`. Note that since both 0 and `FALSE` may be returned for row queries, you should be careful when checking the return value. Use the identity operator (`===`) to check for errors (e.g., `false === $result`), and whether any rows were affected (e.g., `0 === $result`). Delete the β€˜gargle’ meta key and value from Post 13. (We’ll add the β€˜prepare’ method to make sure we’re not dealing with an illegal operation or any illegal characters): ``` $wpdb->query( $wpdb->prepare( " DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s ", 13, 'gargle' ) ); ``` Set the parent of Page 15 to Page 7. ``` $wpdb->query( $wpdb->prepare( " UPDATE $wpdb->posts SET post_parent = %d WHERE ID = %d AND post_status = %s ", 7, 15, 'static' ) ); ``` You can turn error echoing on and off with the show\_errors and hide\_errors, respectively. ``` <?php $wpdb->show_errors(); ?> <?php $wpdb->hide_errors(); ?> ``` You can also print the error (if any) generated by the most recent query with print\_error. ``` <?php $wpdb->print_error(); ?> ``` Note: If you are running WordPress Multisite, you must define the DIEONDBERROR constant for database errors to display like so: ``` <?php define( 'DIEONDBERROR', true ); ?> ``` You can retrieve information about the columns of the most recent query result with get\_col\_info. This can be useful when a function has returned an OBJECT whose properties you don’t know. The function will output the desired information from the specified column, or an array with information on all columns from the query result if no column is specified. ``` <?php $wpdb->get_col_info('type', offset); ?> ``` **type** (string) What information you wish to retrieve. May take on any of the following values (list taken from the ezSQL docs). Defaults to name. * name – column name. Default. * table – name of the table the column belongs to * max\_length – maximum length of the column * not\_null – 1 if the column cannot be NULL * primary\_key – 1 if the column is a primary key * unique\_key – 1 if the column is a unique key * multiple\_key – 1 if the column is a non-unique key * numeric – 1 if the column is numeric * blob – 1 if the column is a BLOB * type – the type of the column * unsigned – 1 if the column is unsigned * zerofill – 1 if the column is zero-filled **offset** (integer) Specify the column from which to retrieve information (with 0 being the first column). Defaults to -1. * -1 – Retrieve information from all columns. Output as array. Default. * Non-negative integer – Retrieve information from specified column (0 being the first). You can clear the SQL result cache with flush. ``` <?php $wpdb->flush(); ?> ``` This clears $<wpdb>->last\_result, $<wpdb>->last\_query, and $<wpdb>->col\_info. The tables that WordPress creates by default can be found [here](https://codex.wordpress.org/Database_Description). * $base\_prefix β€” The original prefix as defined in wp-config.php. For multi-site: Use if you want to get the prefix without the blog number appended. * $col\_info β€” The column information for the most recent query results. See Getting Column Information. * $insert\_id β€” ID generated for an AUTO\_INCREMENT column by the most recent INSERT query. * $last\_error β€” The most recent error text generated by MySQL. * $last\_query β€” The most recent query to have been executed. * $last\_result β€” The most recent query results. * $num\_queries β€” The number of queries that have been executed. * $num\_rows β€” The number of rows returned by the last query. * $prefix β€” The assigned WordPress table prefix for the site. * $queries β€” You may save all of the queries run on the database and their stop times by setting the SAVEQUERIES constant to TRUE (this constant defaults to FALSE). If SAVEQUERIES is TRUE, your queries will be stored in this variable as an array. * $show\_errors β€” Whether or not Error echoing is turned on. Defaults to TRUE. If you are using Multi-Site, you also have access to the following: * $blogid β€” The id of the current site (blog). * $siteid β€” The id of the current network (formerly β€œsite”). WordPress currently only supports one network per multi-site install, but that could change in future. See the following for more information: WordPress: difference between site\_id and blog\_id? http://stackoverflow.com/a/4189358/1924128 – Another good answer to the same question. The [WordPress database tables](https://codex.wordpress.org/Database_Description) are easily referenced in the *<wpdb>* class. * $comments β€” The Comments table. * $commentmeta β€” The table contains additional comment information. * $links β€” The table of Links. * $options β€” The Options table. * $posts β€” The table of Posts. * $postmeta β€” The Meta Content (a.k.a. Custom Fields) table. * $term\_taxonomy β€” The term\_taxonomy table describes the various taxonomies (classes of terms). Categories, Link Categories, and Tags are taxonomies. * $term\_relationships β€” The term relationships table contains link between the term and the object that uses that term, meaning this file point to each Category used for each Post. * $termmeta β€” The termmeta table contains the term meta values. * $terms β€” The terms table contains the β€˜description’ of Categories, Link Categories, Tags. * $users β€” The table of Users. * $usermeta β€” The usermeta table contains additional user information, such as nicknames, descriptions and permissions. These tables are used only in multisite installations. * $blogs β€” The Blogs table contains a list of the separate blogs (sites) that have been set up within the network(s). * $blog\_versions β€” The Blog Versions table. * $blogmeta β€” The Blogmeta table is used to store data associated with a particulate blog in multisite context. See more info in this blog post. * $registration\_log β€” The Registration Log table. * $signups β€” The Signups table. * $site β€” The Site table contains a list of the networks (previously known as β€œsites” in WPMU) that are set up in the installation (usually there is only one site listed in this table). * $sitecategories β€” The Site Categories table. * $sitemeta β€” The Network Options (Site Meta) table contains any options that are applicable to the entire multisite installation. For more information about the tables WordPress creates and uses, look [here](https://codex.wordpress.org/Database_Description). * [\_\_construct](wpdb/__construct) β€” Connects to the database server and selects a database. * [\_\_get](wpdb/__get) β€” Makes private properties readable for backward compatibility. * [\_\_isset](wpdb/__isset) β€” Makes private properties check-able for backward compatibility. * [\_\_set](wpdb/__set) β€” Makes private properties settable for backward compatibility. * [\_\_unset](wpdb/__unset) β€” Makes private properties un-settable for backward compatibility. * [\_do\_query](wpdb/_do_query) β€” Internal function to perform the mysql\_query() call. * [\_escape](wpdb/_escape) β€” Escapes data. Works on arrays. * [\_insert\_replace\_helper](wpdb/_insert_replace_helper) β€” Helper function for insert and replace. * [\_real\_escape](wpdb/_real_escape) β€” Real escape, using mysqli\_real\_escape\_string() or mysql\_real\_escape\_string(). * [\_weak\_escape](wpdb/_weak_escape) β€” Do not use, deprecated. β€” deprecated * [add\_placeholder\_escape](wpdb/add_placeholder_escape) β€” Adds a placeholder escape string, to escape anything that resembles a printf() placeholder. * [bail](wpdb/bail) β€” Wraps errors in a nice header and footer and dies. * [check\_ascii](wpdb/check_ascii) β€” Checks if a string is ASCII. * [check\_connection](wpdb/check_connection) β€” Checks that the connection to the database is still up. If not, try to reconnect. * [check\_database\_version](wpdb/check_database_version) β€” Determines whether MySQL database is at least the required minimum version. * [check\_safe\_collation](wpdb/check_safe_collation) β€” Checks if the query is accessing a collation considered safe on the current version of MySQL. * [close](wpdb/close) β€” Closes the current database connection. * [db\_connect](wpdb/db_connect) β€” Connects to and selects database. * [db\_server\_info](wpdb/db_server_info) β€” Retrieves full database server information. * [db\_version](wpdb/db_version) β€” Retrieves the database server version. * [delete](wpdb/delete) β€” Deletes a row in the table. * [determine\_charset](wpdb/determine_charset) β€” Determines the best charset and collation to use given a charset and collation. * [esc\_like](wpdb/esc_like) β€” First half of escaping for `LIKE` special characters `%` and `\_` before preparing for SQL. * [escape](wpdb/escape) β€” Do not use, deprecated. β€” deprecated * [escape\_by\_ref](wpdb/escape_by_ref) β€” Escapes content by reference for insertion into the database, for security. * [flush](wpdb/flush) β€” Kills cached query results. * [get\_blog\_prefix](wpdb/get_blog_prefix) β€” Gets blog prefix. * [get\_caller](wpdb/get_caller) β€” Retrieves a comma-separated list of the names of the functions that called wpdb. * [get\_charset\_collate](wpdb/get_charset_collate) β€” Retrieves the database character collate. * [get\_col](wpdb/get_col) β€” Retrieves one column from the database. * [get\_col\_charset](wpdb/get_col_charset) β€” Retrieves the character set for the given column. * [get\_col\_info](wpdb/get_col_info) β€” Retrieves column metadata from the last query. * [get\_col\_length](wpdb/get_col_length) β€” Retrieves the maximum string length allowed in a given column. * [get\_results](wpdb/get_results) β€” Retrieves an entire SQL result set from the database (i.e., many rows). * [get\_row](wpdb/get_row) β€” Retrieves one row from the database. * [get\_table\_charset](wpdb/get_table_charset) β€” Retrieves the character set for the given table. * [get\_table\_from\_query](wpdb/get_table_from_query) β€” Finds the first table name referenced in a query. * [get\_var](wpdb/get_var) β€” Retrieves one variable from the database. * [has\_cap](wpdb/has_cap) β€” Determines whether the database or WPDB supports a particular feature. * [hide\_errors](wpdb/hide_errors) β€” Disables showing of database errors. * [init\_charset](wpdb/init_charset) β€” Sets $this->charset and $this->collate. * [insert](wpdb/insert) β€” Inserts a row into the table. * [load\_col\_info](wpdb/load_col_info) β€” Loads the column metadata from the last query. * [log\_query](wpdb/log_query) β€” Logs query data. * [parse\_db\_host](wpdb/parse_db_host) β€” Parses the DB\_HOST setting to interpret it for mysqli\_real\_connect(). * [placeholder\_escape](wpdb/placeholder_escape) β€” Generates and returns a placeholder escape string for use in queries returned by ::prepare(). * [prepare](wpdb/prepare) β€” Prepares a SQL query for safe execution. * [print\_error](wpdb/print_error) β€” Prints SQL/DB error. * [process\_field\_charsets](wpdb/process_field_charsets) β€” Adds field charsets to field/value/format arrays generated by wpdb::process\_field\_formats(). * [process\_field\_formats](wpdb/process_field_formats) β€” Prepares arrays of value/format pairs as passed to wpdb CRUD methods. * [process\_field\_lengths](wpdb/process_field_lengths) β€” For string fields, records the maximum string length that field can safely save. * [process\_fields](wpdb/process_fields) β€” Processes arrays of field/value pairs and field formats. * [query](wpdb/query) β€” Performs a database query, using current database connection. * [remove\_placeholder\_escape](wpdb/remove_placeholder_escape) β€” Removes the placeholder escape strings from a query. * [replace](wpdb/replace) β€” Replaces a row in the table. * [select](wpdb/select) β€” Selects a database using the current or provided database connection. * [set\_blog\_id](wpdb/set_blog_id) β€” Sets blog ID. * [set\_charset](wpdb/set_charset) β€” Sets the connection's character set. * [set\_prefix](wpdb/set_prefix) β€” Sets the table prefix for the WordPress tables. * [set\_sql\_mode](wpdb/set_sql_mode) β€” Changes the current SQL mode, and ensures its WordPress compatibility. * [show\_errors](wpdb/show_errors) β€” Enables showing of database errors. * [strip\_invalid\_text](wpdb/strip_invalid_text) β€” Strips any invalid characters based on value/charset pairs. * [strip\_invalid\_text\_for\_column](wpdb/strip_invalid_text_for_column) β€” Strips any invalid characters from the string for a given table and column. * [strip\_invalid\_text\_from\_query](wpdb/strip_invalid_text_from_query) β€” Strips any invalid characters from the query. * [supports\_collation](wpdb/supports_collation) β€” Determines whether the database supports collation. β€” deprecated * [suppress\_errors](wpdb/suppress_errors) β€” Enables or disables suppressing of database errors. * [tables](wpdb/tables) β€” Returns an array of WordPress tables. * [timer\_start](wpdb/timer_start) β€” Starts the timer, for debugging purposes. * [timer\_stop](wpdb/timer_stop) β€” Stops the debugging timer. * [update](wpdb/update) β€” Updates a row in the table. File: `wp-includes/class-wpdb.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wpdb.php/) ``` class wpdb { /** * Whether to show SQL/DB errors. * * Default is to show errors if both WP_DEBUG and WP_DEBUG_DISPLAY evaluate to true. * * @since 0.71 * * @var bool */ public $show_errors = false; /** * Whether to suppress errors during the DB bootstrapping. Default false. * * @since 2.5.0 * * @var bool */ public $suppress_errors = false; /** * The error encountered during the last query. * * @since 2.5.0 * * @var string */ public $last_error = ''; /** * The number of queries made. * * @since 1.2.0 * * @var int */ public $num_queries = 0; /** * Count of rows returned by the last query. * * @since 0.71 * * @var int */ public $num_rows = 0; /** * Count of rows affected by the last query. * * @since 0.71 * * @var int */ public $rows_affected = 0; /** * The ID generated for an AUTO_INCREMENT column by the last query (usually INSERT). * * @since 0.71 * * @var int */ public $insert_id = 0; /** * The last query made. * * @since 0.71 * * @var string */ public $last_query; /** * Results of the last query. * * @since 0.71 * * @var stdClass[]|null */ public $last_result; /** * Database query result. * * Possible values: * * - For successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries: * - `mysqli_result` instance when the `mysqli` driver is in use * - `resource` when the older `mysql` driver is in use * - `true` for other query types that were successful * - `null` if a query is yet to be made or if the result has since been flushed * - `false` if the query returned an error * * @since 0.71 * * @var mysqli_result|resource|bool|null */ protected $result; /** * Cached column info, for sanity checking data before inserting. * * @since 4.2.0 * * @var array */ protected $col_meta = array(); /** * Calculated character sets keyed by table name. * * @since 4.2.0 * * @var string[] */ protected $table_charset = array(); /** * Whether text fields in the current query need to be sanity checked. * * @since 4.2.0 * * @var bool */ protected $check_current_query = true; /** * Flag to ensure we don't run into recursion problems when checking the collation. * * @since 4.2.0 * * @see wpdb::check_safe_collation() * @var bool */ private $checking_collation = false; /** * Saved info on the table column. * * @since 0.71 * * @var array */ protected $col_info; /** * Log of queries that were executed, for debugging purposes. * * @since 1.5.0 * @since 2.5.0 The third element in each query log was added to record the calling functions. * @since 5.1.0 The fourth element in each query log was added to record the start time. * @since 5.3.0 The fifth element in each query log was added to record custom data. * * @var array[] { * Array of arrays containing information about queries that were executed. * * @type array ...$0 { * Data for each query. * * @type string $0 The query's SQL. * @type float $1 Total time spent on the query, in seconds. * @type string $2 Comma-separated list of the calling functions. * @type float $3 Unix timestamp of the time at the start of the query. * @type array $4 Custom query data. * } * } */ public $queries; /** * The number of times to retry reconnecting before dying. Default 5. * * @since 3.9.0 * * @see wpdb::check_connection() * @var int */ protected $reconnect_retries = 5; /** * WordPress table prefix. * * You can set this to have multiple WordPress installations in a single database. * The second reason is for possible security precautions. * * @since 2.5.0 * * @var string */ public $prefix = ''; /** * WordPress base table prefix. * * @since 3.0.0 * * @var string */ public $base_prefix; /** * Whether the database queries are ready to start executing. * * @since 2.3.2 * * @var bool */ public $ready = false; /** * Blog ID. * * @since 3.0.0 * * @var int */ public $blogid = 0; /** * Site ID. * * @since 3.0.0 * * @var int */ public $siteid = 0; /** * List of WordPress per-site tables. * * @since 2.5.0 * * @see wpdb::tables() * @var string[] */ public $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta', 'terms', 'term_taxonomy', 'term_relationships', 'termmeta', 'commentmeta', ); /** * List of deprecated WordPress tables. * * 'categories', 'post2cat', and 'link2cat' were deprecated in 2.3.0, db version 5539. * * @since 2.9.0 * * @see wpdb::tables() * @var string[] */ public $old_tables = array( 'categories', 'post2cat', 'link2cat' ); /** * List of WordPress global tables. * * @since 3.0.0 * * @see wpdb::tables() * @var string[] */ public $global_tables = array( 'users', 'usermeta' ); /** * List of Multisite global tables. * * @since 3.0.0 * * @see wpdb::tables() * @var string[] */ public $ms_global_tables = array( 'blogs', 'blogmeta', 'signups', 'site', 'sitemeta', 'registration_log', ); /** * List of deprecated WordPress Multisite global tables. * * @since 6.1.0 * * @see wpdb::tables() * @var string[] */ public $old_ms_global_tables = array( 'sitecategories' ); /** * WordPress Comments table. * * @since 1.5.0 * * @var string */ public $comments; /** * WordPress Comment Metadata table. * * @since 2.9.0 * * @var string */ public $commentmeta; /** * WordPress Links table. * * @since 1.5.0 * * @var string */ public $links; /** * WordPress Options table. * * @since 1.5.0 * * @var string */ public $options; /** * WordPress Post Metadata table. * * @since 1.5.0 * * @var string */ public $postmeta; /** * WordPress Posts table. * * @since 1.5.0 * * @var string */ public $posts; /** * WordPress Terms table. * * @since 2.3.0 * * @var string */ public $terms; /** * WordPress Term Relationships table. * * @since 2.3.0 * * @var string */ public $term_relationships; /** * WordPress Term Taxonomy table. * * @since 2.3.0 * * @var string */ public $term_taxonomy; /** * WordPress Term Meta table. * * @since 4.4.0 * * @var string */ public $termmeta; // // Global and Multisite tables // /** * WordPress User Metadata table. * * @since 2.3.0 * * @var string */ public $usermeta; /** * WordPress Users table. * * @since 1.5.0 * * @var string */ public $users; /** * Multisite Blogs table. * * @since 3.0.0 * * @var string */ public $blogs; /** * Multisite Blog Metadata table. * * @since 5.1.0 * * @var string */ public $blogmeta; /** * Multisite Registration Log table. * * @since 3.0.0 * * @var string */ public $registration_log; /** * Multisite Signups table. * * @since 3.0.0 * * @var string */ public $signups; /** * Multisite Sites table. * * @since 3.0.0 * * @var string */ public $site; /** * Multisite Sitewide Terms table. * * @since 3.0.0 * * @var string */ public $sitecategories; /** * Multisite Site Metadata table. * * @since 3.0.0 * * @var string */ public $sitemeta; /** * Format specifiers for DB columns. * * Columns not listed here default to %s. Initialized during WP load. * Keys are column names, values are format types: 'ID' => '%d'. * * @since 2.8.0 * * @see wpdb::prepare() * @see wpdb::insert() * @see wpdb::update() * @see wpdb::delete() * @see wp_set_wpdb_vars() * @var array */ public $field_types = array(); /** * Database table columns charset. * * @since 2.2.0 * * @var string */ public $charset; /** * Database table columns collate. * * @since 2.2.0 * * @var string */ public $collate; /** * Database Username. * * @since 2.9.0 * * @var string */ protected $dbuser; /** * Database Password. * * @since 3.1.0 * * @var string */ protected $dbpassword; /** * Database Name. * * @since 3.1.0 * * @var string */ protected $dbname; /** * Database Host. * * @since 3.1.0 * * @var string */ protected $dbhost; /** * Database handle. * * Possible values: * * - `mysqli` instance when the `mysqli` driver is in use * - `resource` when the older `mysql` driver is in use * - `null` if the connection is yet to be made or has been closed * - `false` if the connection has failed * * @since 0.71 * * @var mysqli|resource|false|null */ protected $dbh; /** * A textual description of the last query/get_row/get_var call. * * @since 3.0.0 * * @var string */ public $func_call; /** * Whether MySQL is used as the database engine. * * Set in wpdb::db_connect() to true, by default. This is used when checking * against the required MySQL version for WordPress. Normally, a replacement * database drop-in (db.php) will skip these checks, but setting this to true * will force the checks to occur. * * @since 3.3.0 * * @var bool */ public $is_mysql = null; /** * A list of incompatible SQL modes. * * @since 3.9.0 * * @var string[] */ protected $incompatible_modes = array( 'NO_ZERO_DATE', 'ONLY_FULL_GROUP_BY', 'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES', 'TRADITIONAL', 'ANSI', ); /** * Whether to use mysqli over mysql. Default false. * * @since 3.9.0 * * @var bool */ private $use_mysqli = false; /** * Whether we've managed to successfully connect at some point. * * @since 3.9.0 * * @var bool */ private $has_connected = false; /** * Time when the last query was performed. * * Only set when `SAVEQUERIES` is defined and truthy. * * @since 1.5.0 * * @var float */ public $time_start = null; /** * The last SQL error that was encountered. * * @since 2.5.0 * * @var WP_Error|string */ public $error = null; /** * Connects to the database server and selects a database. * * Does the actual setting up * of the class properties and connection to the database. * * @since 2.0.8 * * @link https://core.trac.wordpress.org/ticket/3354 * * @param string $dbuser Database user. * @param string $dbpassword Database password. * @param string $dbname Database name. * @param string $dbhost Database host. */ 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(); } /** * Makes private properties readable for backward compatibility. * * @since 3.5.0 * * @param string $name The private member to get, and optionally process. * @return mixed The private member. */ public function __get( $name ) { if ( 'col_info' === $name ) { $this->load_col_info(); } return $this->$name; } /** * Makes private properties settable for backward compatibility. * * @since 3.5.0 * * @param string $name The private member to set. * @param mixed $value The value to set. */ 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; } /** * Makes private properties check-able for backward compatibility. * * @since 3.5.0 * * @param string $name The private member to check. * @return bool If the member is set or not. */ public function __isset( $name ) { return isset( $this->$name ); } /** * Makes private properties un-settable for backward compatibility. * * @since 3.5.0 * * @param string $name The private member to unset */ public function __unset( $name ) { unset( $this->$name ); } /** * Sets $this->charset and $this->collate. * * @since 3.1.0 */ 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']; } /** * Determines the best charset and collation to use given a charset and collation. * * For example, when able, utf8mb4 should be used instead of utf8. * * @since 4.6.0 * * @param string $charset The character set to check. * @param string $collate The collation to check. * @return array { * The most appropriate character set and collation to use. * * @type string $charset Character set. * @type string $collate Collation. * } */ 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' ); } /** * Sets the connection's character set. * * @since 3.1.0 * * @param mysqli|resource $dbh The connection returned by `mysqli_connect()` or `mysql_connect()`. * @param string $charset Optional. The character set. Default null. * @param string $collate Optional. The collation. Default null. */ 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 ); } } } } /** * 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. * * @since 3.9.0 * * @param array $modes Optional. A list of SQL modes to set. Default empty array. */ 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 ); } } /** * Sets the table prefix for the WordPress tables. * * @since 2.5.0 * * @param string $prefix Alphanumeric name for the new prefix. * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, * should be updated or not. Default true. * @return string|WP_Error Old prefix or WP_Error on error. */ 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; } /** * Sets blog ID. * * @since 3.0.0 * * @param int $blog_id * @param int $network_id Optional. * @return int Previous blog ID. */ 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; } /** * Gets blog prefix. * * @since 3.0.0 * * @param int $blog_id Optional. * @return string Blog prefix. */ 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; } } /** * 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. * * @since 3.0.0 * @since 6.1.0 `old` now includes deprecated multisite global tables only on multisite. * * @uses wpdb::$tables * @uses wpdb::$old_tables * @uses wpdb::$global_tables * @uses wpdb::$ms_global_tables * @uses wpdb::$old_ms_global_tables * * @param string $scope Optional. Possible values include 'all', 'global', 'ms_global', 'blog', * or 'old' tables. Default 'all'. * @param bool $prefix Optional. Whether to include table prefixes. If blog prefix is requested, * then the custom users and usermeta tables will be mapped. Default true. * @param int $blog_id Optional. The blog_id to prefix. Used only when prefix is requested. * Defaults to `wpdb::$blogid`. * @return string[] Table names. When a prefix is requested, the key is the unprefixed table name. */ 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; } /** * 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. * * @since 0.71 * * @param string $db Database name. * @param mysqli|resource $dbh Optional database connection. */ 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' ); } } } /** * Do not use, deprecated. * * Use esc_sql() or wpdb::prepare() instead. * * @since 2.8.0 * @deprecated 3.6.0 Use wpdb::prepare() * @see wpdb::prepare() * @see esc_sql() * * @param string $string * @return string */ 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 ); } /** * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string(). * * @since 2.8.0 * * @see mysqli_real_escape_string() * @see mysql_real_escape_string() * * @param string $string String to escape. * @return string Escaped string. */ 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 ); } /** * Escapes data. Works on arrays. * * @since 2.8.0 * * @uses wpdb::_real_escape() * * @param string|array $data Data to escape. * @return string|array Escaped data, in the same type as supplied. */ 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; } /** * Do not use, deprecated. * * Use esc_sql() or wpdb::prepare() instead. * * @since 0.71 * @deprecated 3.6.0 Use wpdb::prepare() * @see wpdb::prepare() * @see esc_sql() * * @param string|array $data Data to escape. * @return string|array Escaped data, in the same type as supplied. */ 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; } /** * Escapes content by reference for insertion into the database, for security. * * @uses wpdb::_real_escape() * * @since 2.3.0 * * @param string $string String to escape. */ public function escape_by_ref( &$string ) { if ( ! is_float( $string ) ) { $string = $this->_real_escape( $string ); } } /** * 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(). * * 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' * ); * * @since 2.3.0 * @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`. * * @link https://www.php.net/sprintf Description of syntax. * * @param string $query Query statement with sprintf()-like placeholders. * @param array|mixed $args The array of variables to substitute into the query's placeholders * if being called with an array of arguments, or the first variable * to substitute into the query's placeholders if being called with * individual arguments. * @param mixed ...$args Further variables to substitute into the query's placeholders * if being called with individual arguments. * @return string|void Sanitized query string, if there is a query to prepare. */ 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 ); } /** * First half of escaping for `LIKE` special characters `%` and `_` before preparing for SQL. * * Use this only before wpdb::prepare() or 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 ) ); * * @since 4.0.0 * * @param string $text The raw text to be escaped. The input typed by the user * should have no extra or deleted slashes. * @return string Text in the form of a LIKE phrase. The output is not SQL safe. * Call wpdb::prepare() or wpdb::_real_escape() next. */ public function esc_like( $text ) { return addcslashes( $text, '_%\\' ); } /** * Prints SQL/DB error. * * @since 0.71 * * @global array $EZSQL_ERROR Stores error information of query and error string. * * @param string $str The error to display. * @return void|false Void if the showing of errors is enabled, false if disabled. */ 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 ); } } /** * Enables showing of database errors. * * This function should be used only to enable showing of errors. * wpdb::hide_errors() should be used instead for hiding errors. * * @since 0.71 * * @see wpdb::hide_errors() * * @param bool $show Optional. Whether to show errors. Default true. * @return bool Whether showing of errors was previously active. */ public function show_errors( $show = true ) { $errors = $this->show_errors; $this->show_errors = $show; return $errors; } /** * Disables showing of database errors. * * By default database errors are not shown. * * @since 0.71 * * @see wpdb::show_errors() * * @return bool Whether showing of errors was previously active. */ public function hide_errors() { $show = $this->show_errors; $this->show_errors = false; return $show; } /** * Enables or disables suppressing of database errors. * * By default database errors are suppressed. * * @since 2.5.0 * * @see wpdb::hide_errors() * * @param bool $suppress Optional. Whether to suppress errors. Default true. * @return bool Whether suppressing of errors was previously active. */ public function suppress_errors( $suppress = true ) { $errors = $this->suppress_errors; $this->suppress_errors = (bool) $suppress; return $errors; } /** * Kills cached query results. * * @since 0.71 */ 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 ); } } /** * Connects to and selects database. * * If `$allow_bail` is false, the lack of database connection will need to be handled manually. * * @since 3.0.0 * @since 3.9.0 $allow_bail parameter added. * * @param bool $allow_bail Optional. Allows the function to bail. Default true. * @return bool True with a successful connection, false on failure. */ 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&#8217;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; } /** * 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. * * @since 4.9.0 * * @param string $host The DB_HOST setting to parse. * @return 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. * * @type string $0 Host name. * @type string|null $1 Port. * @type string|null $2 Socket. * @type bool $3 Whether it is an IPv6 address. * } */ 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 ); } /** * 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 {@see '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. * * @since 3.9.0 * * @param bool $allow_bail Optional. Allows the function to bail. Default true. * @return bool|void True if the connection is up. */ 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&#8217;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(); } /** * Performs a database query, using current database connection. * * More information can be found on the documentation page. * * @since 0.71 * * @link https://developer.wordpress.org/reference/classes/wpdb/ * * @param string $query Database query. * @return int|bool Boolean true for CREATE, ALTER, TRUNCATE and DROP queries. Number of rows * affected/selected for all other queries. Boolean false on error. */ 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; } /** * Internal function to perform the mysql_query() call. * * @since 3.9.0 * * @see wpdb::query() * * @param string $query The query to run. */ 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() ); } } /** * Logs query data. * * @since 5.3.0 * * @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. * @param array $query_data Custom query data. */ 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, ); } /** * Generates and returns a placeholder escape string for use in queries returned by ::prepare(). * * @since 4.8.3 * * @return string String to escape placeholders. */ 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; } /** * Adds a placeholder escape string, to escape anything that resembles a printf() placeholder. * * @since 4.8.3 * * @param string $query The query to escape. * @return string The query with the placeholder escape string inserted where necessary. */ 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 ); } /** * Removes the placeholder escape strings from a query. * * @since 4.8.3 * * @param string $query The query from which the placeholder will be removed. * @return string The query with the placeholder removed. */ public function remove_placeholder_escape( $query ) { return str_replace( $this->placeholder_escape(), '%', $query ); } /** * 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' ) ) * * @since 2.5.0 * * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * * @param string $table Table name. * @param array $data 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. * @param array|string $format 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. * @return int|false The number of rows inserted, or false on error. */ public function insert( $table, $data, $format = null ) { return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' ); } /** * 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' ) ) * * @since 3.0.0 * * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * * @param string $table Table name. * @param array $data 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. * @param array|string $format 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. * @return int|false The number of rows affected, or false on error. */ public function replace( $table, $data, $format = null ) { return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' ); } /** * Helper function for insert and replace. * * Runs an insert or replace query based on $type argument. * * @since 3.0.0 * * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * * @param string $table Table name. * @param array $data 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. * @param array|string $format 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. * @param string $type Optional. Type of operation. Possible values include 'INSERT' or 'REPLACE'. * Default 'INSERT'. * @return int|false The number of rows affected, or false on error. */ 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 ) ); } /** * 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' ) ) * * @since 2.5.0 * * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * * @param string $table Table name. * @param array $data 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. * @param array $where 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. * @param array|string $format 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. * @param array|string $where_format 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. * @return int|false The number of rows updated, or false on error. */ 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 ) ); } /** * Deletes a row in the table. * * Examples: * * wpdb::delete( 'table', array( 'ID' => 1 ) ) * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) ) * * @since 3.4.0 * * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * * @param string $table Table name. * @param array $where 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. * @param array|string $where_format 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. * @return int|false The number of rows deleted, or false on error. */ 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 ) ); } /** * Processes arrays of field/value pairs and field formats. * * This is a helper method for 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. * * @since 4.2.0 * * @param string $table Table name. * @param array $data Field/value pair. * @param mixed $format Format for each field. * @return array|false An array of fields that contain paired value and formats. * False for invalid values. */ 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; } /** * Prepares arrays of value/format pairs as passed to wpdb CRUD methods. * * @since 4.2.0 * * @param array $data Array of fields to values. * @param mixed $format Formats to be mapped to the values in $data. * @return array Array, keyed by field names with values being an array * of 'value' and 'format' keys. */ 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; } /** * Adds field charsets to field/value/format arrays generated by wpdb::process_field_formats(). * * @since 4.2.0 * * @param array $data As it comes from the wpdb::process_field_formats() method. * @param string $table Table name. * @return array|false The same array as $data with additional 'charset' keys. * False on failure. */ 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; } /** * For string fields, records the maximum string length that field can safely save. * * @since 4.2.1 * * @param array $data As it comes from the wpdb::process_field_charsets() method. * @param string $table Table name. * @return 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. */ 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; } /** * 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. * * @since 0.71 * * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query. * @param int $x Optional. Column of value to return. Indexed from 0. * @param int $y Optional. Row of value to return. Indexed from 0. * @return string|null Database query result (as string), or null on failure. */ 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; } /** * Retrieves one row from the database. * * Executes a SQL query and returns the row from the SQL result. * * @since 0.71 * * @param string|null $query SQL query. * @param string $output 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. * @param int $y Optional. Row to return. Indexed from 0. * @return array|object|null|void Database query result in format specified by $output or null on failure. */ 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' ); } } /** * 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. * * @since 0.71 * * @param string|null $query Optional. SQL query. Defaults to previous query. * @param int $x Optional. Column to return. Indexed from 0. * @return array Database query result. Array indexed from 0 by SQL result row number. */ 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; } /** * Retrieves an entire SQL result set from the database (i.e., many rows). * * Executes a SQL query and returns the entire SQL result. * * @since 0.71 * * @param string $query SQL query. * @param string $output 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. * @return array|object|null Database query results. */ 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; } /** * Retrieves the character set for the given table. * * @since 4.2.0 * * @param string $table Table name. * @return string|WP_Error Table character set, WP_Error object if it couldn't be found. */ 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; } /** * Retrieves the character set for the given column. * * @since 4.2.0 * * @param string $table Table name. * @param string $column Column name. * @return string|false|WP_Error Column character set as a string. False if the column has * no character set. WP_Error object if there was an error. */ 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; } /** * Retrieves the maximum string length allowed in a given column. * * The length may either be specified as a byte length or a character length. * * @since 4.2.1 * * @param string $table Table name. * @param string $column Column name. * @return array|false|WP_Error { * Array of column length information, false if the column has no length (for * example, numeric column), WP_Error object if there was an error. * * @type int $length The column length. * @type string $type One of 'byte' or 'char'. */ 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; } } /** * 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. * * @since 4.2.0 * * @param string $string String to check. * @return bool True if ASCII, false if not. */ 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; } /** * Checks if the query is accessing a collation considered safe on the current version of MySQL. * * @since 4.2.0 * * @param string $query The query to check. * @return bool True if the collation is safe, false if it isn't. */ 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; } /** * Strips any invalid characters based on value/charset pairs. * * @since 4.2.0 * * @param array $data 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. * @return array|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 object is returned. */ 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; } /** * Strips any invalid characters from the query. * * @since 4.2.0 * * @param string $query Query to convert. * @return string|WP_Error The converted query, or a WP_Error object if the conversion fails. */ 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']; } /** * Strips any invalid characters from the string for a given table and column. * * @since 4.2.0 * * @param string $table Table name. * @param string $column Column name. * @param string $value The text to check. * @return string|WP_Error The converted string, or a WP_Error object if the conversion fails. */ 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']; } /** * Finds the first table name referenced in a query. * * @since 4.2.0 * * @param string $query The query to search. * @return string|false The table name found, or false if a table couldn't be found. */ 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; } /** * Loads the column metadata from the last query. * * @since 3.5.0 */ 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 ); } } } /** * Retrieves column metadata from the last query. * * @since 0.71 * * @param string $info_type Optional. Possible values include 'name', 'table', 'def', 'max_length', * 'not_null', 'primary_key', 'multiple_key', 'unique_key', 'numeric', * 'blob', 'type', 'unsigned', 'zerofill'. Default 'name'. * @param int $col_offset 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. * @return mixed Column results. */ 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}; } } } /** * Starts the timer, for debugging purposes. * * @since 1.5.0 * * @return true */ public function timer_start() { $this->time_start = microtime( true ); return true; } /** * Stops the debugging timer. * * @since 1.5.0 * * @return float Total time spent on the query, in seconds. */ public function timer_stop() { return ( microtime( true ) - $this->time_start ); } /** * Wraps errors in a nice header and footer and dies. * * Will not die if wpdb::$show_errors is false. * * @since 1.5.0 * * @param string $message The error message. * @param string $error_code Optional. A computer-readable string to identify the error. * Default '500'. * @return void|false Void if the showing of errors is enabled, false if disabled. */ 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; } } /** * Closes the current database connection. * * @since 4.5.0 * * @return bool True if the connection was successfully closed, * false if it wasn't, or if the connection doesn't exist. */ 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; } /** * Determines whether MySQL database is at least the required minimum version. * * @since 2.5.0 * * @global string $wp_version The WordPress version string. * @global string $required_mysql_version The required MySQL version string. * @return void|WP_Error */ 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 ) ); } } /** * Determines whether the database supports collation. * * Called when WordPress is generating the table scheme. * * Use `wpdb::has_cap( 'collation' )`. * * @since 2.5.0 * @deprecated 3.5.0 Use wpdb::has_cap() * * @return bool True if collation is supported, false if not. */ public function supports_collation() { _deprecated_function( __FUNCTION__, '3.5.0', 'wpdb::has_cap( \'collation\' )' ); return $this->has_cap( 'collation' ); } /** * Retrieves the database character collate. * * @since 3.5.0 * * @return string The database character collate. */ 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; } /** * 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. * * @since 2.7.0 * @since 4.1.0 Added support for the 'utf8mb4' feature. * @since 4.6.0 Added support for the 'utf8mb4_520' feature. * * @see wpdb::db_version() * * @param string $db_cap The feature to check for. Accepts 'collation', 'group_concat', * 'subqueries', 'set_charset', 'utf8mb4', or 'utf8mb4_520'. * @return bool True when the database feature is supported, false otherwise. */ 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; } /** * Retrieves a comma-separated list of the names of the functions that called wpdb. * * @since 2.5.0 * * @return string Comma-separated list of the calling functions. */ public function get_caller() { return wp_debug_backtrace_summary( __CLASS__ ); } /** * Retrieves the database server version. * * @since 2.7.0 * * @return string|null Version number on success, null on failure. */ public function db_version() { return preg_replace( '/[^0-9.].*/', '', $this->db_server_info() ); } /** * Retrieves full database server information. * * @since 5.5.0 * * @return string|false Server info on success, false on failure. */ 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; } } ```
programming_docs
wordpress class WP_Site_Query {} class WP\_Site\_Query {} ======================== Core class used for querying sites. * [WP\_Site\_Query::\_\_construct()](wp_site_query/__construct): for accepted arguments. * [\_\_construct](wp_site_query/__construct) β€” Sets up the site query, based on the query vars passed. * [get\_search\_sql](wp_site_query/get_search_sql) β€” Used internally to generate an SQL string for searching across multiple columns. * [get\_site\_ids](wp_site_query/get_site_ids) β€” Used internally to get a list of site IDs matching the query vars. * [get\_sites](wp_site_query/get_sites) β€” Retrieves a list of sites matching the query vars. * [parse\_order](wp_site_query/parse_order) β€” Parses an 'order' query variable and cast it to 'ASC' or 'DESC' as necessary. * [parse\_orderby](wp_site_query/parse_orderby) β€” Parses and sanitizes 'orderby' keys passed to the site query. * [parse\_query](wp_site_query/parse_query) β€” Parses arguments passed to the site query with default query parameters. * [query](wp_site_query/query) β€” Sets up the WordPress query for retrieving sites. * [set\_found\_sites](wp_site_query/set_found_sites) β€” Populates found\_sites and max\_num\_pages properties for the current query if the limit clause was used. File: `wp-includes/class-wp-site-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site-query.php/) ``` class WP_Site_Query { /** * SQL for database query. * * @since 4.6.0 * @var string */ public $request; /** * SQL query clauses. * * @since 4.6.0 * @var array */ protected $sql_clauses = array( 'select' => '', 'from' => '', 'where' => array(), 'groupby' => '', 'orderby' => '', 'limits' => '', ); /** * Metadata query container. * * @since 5.1.0 * @var WP_Meta_Query */ public $meta_query = false; /** * Metadata query clauses. * * @since 5.1.0 * @var array */ protected $meta_query_clauses; /** * Date query container. * * @since 4.6.0 * @var WP_Date_Query A date query instance. */ public $date_query = false; /** * Query vars set by the user. * * @since 4.6.0 * @var array */ public $query_vars; /** * Default values for query vars. * * @since 4.6.0 * @var array */ public $query_var_defaults; /** * List of sites located by the query. * * @since 4.6.0 * @var array */ public $sites; /** * The amount of found sites for the current query. * * @since 4.6.0 * @var int */ public $found_sites = 0; /** * The number of pages. * * @since 4.6.0 * @var int */ public $max_num_pages = 0; /** * Sets up the site query, based on the query vars passed. * * @since 4.6.0 * @since 4.8.0 Introduced the 'lang_id', 'lang__in', and 'lang__not_in' parameters. * @since 5.1.0 Introduced the 'update_site_meta_cache', 'meta_query', 'meta_key', * 'meta_compare_key', 'meta_value', 'meta_type', and 'meta_compare' parameters. * @since 5.3.0 Introduced the 'meta_type_key' parameter. * * @param string|array $query { * Optional. Array or query string of site query parameters. Default empty. * * @type int[] $site__in Array of site IDs to include. Default empty. * @type int[] $site__not_in Array of site IDs to exclude. Default empty. * @type bool $count Whether to return a site count (true) or array of site objects. * Default false. * @type array $date_query Date query clauses to limit sites by. See WP_Date_Query. * Default null. * @type string $fields Site fields to return. Accepts 'ids' (returns an array of site IDs) * or empty (returns an array of complete site objects). Default empty. * @type int $ID A site ID to only return that site. Default empty. * @type int $number Maximum number of sites to retrieve. Default 100. * @type int $offset Number of sites to offset the query. Used to build LIMIT clause. * Default 0. * @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query. Default true. * @type string|array $orderby Site status or array of statuses. Accepts: * - 'id' * - 'domain' * - 'path' * - 'network_id' * - 'last_updated' * - 'registered' * - 'domain_length' * - 'path_length' * - 'site__in' * - 'network__in' * - 'deleted' * - 'mature' * - 'spam' * - 'archived' * - 'public' * - false, an empty array, or 'none' to disable `ORDER BY` clause. * Default 'id'. * @type string $order How to order retrieved sites. Accepts 'ASC', 'DESC'. Default 'ASC'. * @type int $network_id Limit results to those affiliated with a given network ID. If 0, * include all networks. Default 0. * @type int[] $network__in Array of network IDs to include affiliated sites for. Default empty. * @type int[] $network__not_in Array of network IDs to exclude affiliated sites for. Default empty. * @type string $domain Limit results to those affiliated with a given domain. Default empty. * @type string[] $domain__in Array of domains to include affiliated sites for. Default empty. * @type string[] $domain__not_in Array of domains to exclude affiliated sites for. Default empty. * @type string $path Limit results to those affiliated with a given path. Default empty. * @type string[] $path__in Array of paths to include affiliated sites for. Default empty. * @type string[] $path__not_in Array of paths to exclude affiliated sites for. Default empty. * @type int $public Limit results to public sites. Accepts '1' or '0'. Default empty. * @type int $archived Limit results to archived sites. Accepts '1' or '0'. Default empty. * @type int $mature Limit results to mature sites. Accepts '1' or '0'. Default empty. * @type int $spam Limit results to spam sites. Accepts '1' or '0'. Default empty. * @type int $deleted Limit results to deleted sites. Accepts '1' or '0'. Default empty. * @type int $lang_id Limit results to a language ID. Default empty. * @type string[] $lang__in Array of language IDs to include affiliated sites for. Default empty. * @type string[] $lang__not_in Array of language IDs to exclude affiliated sites for. Default empty. * @type string $search Search term(s) to retrieve matching sites for. Default empty. * @type string[] $search_columns Array of column names to be searched. Accepts 'domain' and 'path'. * Default empty array. * @type bool $update_site_cache Whether to prime the cache for found sites. Default true. * @type bool $update_site_meta_cache Whether to prime the metadata cache for found sites. Default true. * @type string|string[] $meta_key Meta key or keys to filter by. * @type string|string[] $meta_value Meta value or values to filter by. * @type string $meta_compare MySQL operator used for comparing the meta value. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_compare_key MySQL operator used for comparing the meta key. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_type MySQL data type that the meta_value column will be CAST to for comparisons. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_type_key MySQL data type that the meta_key column will be CAST to for comparisons. * See WP_Meta_Query::__construct() for accepted values and default value. * @type array $meta_query An associative array of WP_Meta_Query arguments. * See WP_Meta_Query::__construct() for accepted values. * } */ public function __construct( $query = '' ) { $this->query_var_defaults = array( 'fields' => '', 'ID' => '', 'site__in' => '', 'site__not_in' => '', 'number' => 100, 'offset' => '', 'no_found_rows' => true, 'orderby' => 'id', 'order' => 'ASC', 'network_id' => 0, 'network__in' => '', 'network__not_in' => '', 'domain' => '', 'domain__in' => '', 'domain__not_in' => '', 'path' => '', 'path__in' => '', 'path__not_in' => '', 'public' => null, 'archived' => null, 'mature' => null, 'spam' => null, 'deleted' => null, 'lang_id' => null, 'lang__in' => '', 'lang__not_in' => '', 'search' => '', 'search_columns' => array(), 'count' => false, 'date_query' => null, // See WP_Date_Query. 'update_site_cache' => true, 'update_site_meta_cache' => true, 'meta_query' => '', 'meta_key' => '', 'meta_value' => '', 'meta_type' => '', 'meta_compare' => '', ); if ( ! empty( $query ) ) { $this->query( $query ); } } /** * Parses arguments passed to the site query with default query parameters. * * @since 4.6.0 * * @see WP_Site_Query::__construct() * * @param string|array $query Array or string of WP_Site_Query arguments. See WP_Site_Query::__construct(). */ public function parse_query( $query = '' ) { if ( empty( $query ) ) { $query = $this->query_vars; } $this->query_vars = wp_parse_args( $query, $this->query_var_defaults ); /** * Fires after the site query vars have been parsed. * * @since 4.6.0 * * @param WP_Site_Query $query The WP_Site_Query instance (passed by reference). */ do_action_ref_array( 'parse_site_query', array( &$this ) ); } /** * Sets up the WordPress query for retrieving sites. * * @since 4.6.0 * * @param string|array $query Array or URL query string of parameters. * @return array|int List of WP_Site objects, a list of site IDs when 'fields' is set to 'ids', * or the number of sites when 'count' is passed as a query var. */ public function query( $query ) { $this->query_vars = wp_parse_args( $query ); return $this->get_sites(); } /** * Retrieves a list of sites matching the query vars. * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @return array|int List of WP_Site objects, a list of site IDs when 'fields' is set to 'ids', * or the number of sites when 'count' is passed as a query var. */ public function get_sites() { global $wpdb; $this->parse_query(); // Parse meta query. $this->meta_query = new WP_Meta_Query(); $this->meta_query->parse_query_vars( $this->query_vars ); /** * Fires before sites are retrieved. * * @since 4.6.0 * * @param WP_Site_Query $query Current instance of WP_Site_Query (passed by reference). */ do_action_ref_array( 'pre_get_sites', array( &$this ) ); // Reparse query vars, in case they were modified in a 'pre_get_sites' callback. $this->meta_query->parse_query_vars( $this->query_vars ); if ( ! empty( $this->meta_query->queries ) ) { $this->meta_query_clauses = $this->meta_query->get_sql( 'blog', $wpdb->blogs, 'blog_id', $this ); } $site_data = null; /** * Filters the site data before the get_sites query takes place. * * Return a non-null value to bypass WordPress' default site queries. * * The expected return type from this filter depends on the value passed * in the request query vars: * - When `$this->query_vars['count']` is set, the filter should return * the site count as an integer. * - When `'ids' === $this->query_vars['fields']`, the filter should return * an array of site IDs. * - Otherwise the filter should return an array of WP_Site objects. * * Note that if the filter returns an array of site data, it will be assigned * to the `sites` property of the current WP_Site_Query instance. * * Filtering functions that require pagination information are encouraged to set * the `found_sites` and `max_num_pages` properties of the WP_Site_Query object, * passed to the filter by reference. If WP_Site_Query does not perform a database * query, it will not have enough information to generate these values itself. * * @since 5.2.0 * @since 5.6.0 The returned array of site data is assigned to the `sites` property * of the current WP_Site_Query instance. * * @param array|int|null $site_data Return an array of site data to short-circuit WP's site query, * the site count as an integer if `$this->query_vars['count']` is set, * or null to run the normal queries. * @param WP_Site_Query $query The WP_Site_Query instance, passed by reference. */ $site_data = apply_filters_ref_array( 'sites_pre_query', array( $site_data, &$this ) ); if ( null !== $site_data ) { if ( is_array( $site_data ) && ! $this->query_vars['count'] ) { $this->sites = $site_data; } return $site_data; } // $args can include anything. Only use the args defined in the query_var_defaults to compute the key. $_args = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ); // Ignore the $fields, $update_site_cache, $update_site_meta_cache argument as the queried result will be the same regardless. unset( $_args['fields'], $_args['update_site_cache'], $_args['update_site_meta_cache'] ); $key = md5( serialize( $_args ) ); $last_changed = wp_cache_get_last_changed( 'sites' ); $cache_key = "get_sites:$key:$last_changed"; $cache_value = wp_cache_get( $cache_key, 'sites' ); if ( false === $cache_value ) { $site_ids = $this->get_site_ids(); if ( $site_ids ) { $this->set_found_sites(); } $cache_value = array( 'site_ids' => $site_ids, 'found_sites' => $this->found_sites, ); wp_cache_add( $cache_key, $cache_value, 'sites' ); } else { $site_ids = $cache_value['site_ids']; $this->found_sites = $cache_value['found_sites']; } if ( $this->found_sites && $this->query_vars['number'] ) { $this->max_num_pages = ceil( $this->found_sites / $this->query_vars['number'] ); } // If querying for a count only, there's nothing more to do. if ( $this->query_vars['count'] ) { // $site_ids is actually a count in this case. return (int) $site_ids; } $site_ids = array_map( 'intval', $site_ids ); if ( 'ids' === $this->query_vars['fields'] ) { $this->sites = $site_ids; return $this->sites; } // Prime site network caches. if ( $this->query_vars['update_site_cache'] ) { _prime_site_caches( $site_ids, $this->query_vars['update_site_meta_cache'] ); } // Fetch full site objects from the primed cache. $_sites = array(); foreach ( $site_ids as $site_id ) { $_site = get_site( $site_id ); if ( $_site ) { $_sites[] = $_site; } } /** * Filters the site query results. * * @since 4.6.0 * * @param WP_Site[] $_sites An array of WP_Site objects. * @param WP_Site_Query $query Current instance of WP_Site_Query (passed by reference). */ $_sites = apply_filters_ref_array( 'the_sites', array( $_sites, &$this ) ); // Convert to WP_Site instances. $this->sites = array_map( 'get_site', $_sites ); return $this->sites; } /** * Used internally to get a list of site IDs matching the query vars. * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @return int|array A single count of site IDs if a count query. An array of site IDs if a full query. */ protected function get_site_ids() { global $wpdb; $order = $this->parse_order( $this->query_vars['order'] ); // Disable ORDER BY with 'none', an empty array, or boolean false. if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) { $orderby = ''; } elseif ( ! empty( $this->query_vars['orderby'] ) ) { $ordersby = is_array( $this->query_vars['orderby'] ) ? $this->query_vars['orderby'] : preg_split( '/[,\s]/', $this->query_vars['orderby'] ); $orderby_array = array(); foreach ( $ordersby as $_key => $_value ) { if ( ! $_value ) { continue; } if ( is_int( $_key ) ) { $_orderby = $_value; $_order = $order; } else { $_orderby = $_key; $_order = $_value; } $parsed = $this->parse_orderby( $_orderby ); if ( ! $parsed ) { continue; } if ( 'site__in' === $_orderby || 'network__in' === $_orderby ) { $orderby_array[] = $parsed; continue; } $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order ); } $orderby = implode( ', ', $orderby_array ); } else { $orderby = "{$wpdb->blogs}.blog_id $order"; } $number = absint( $this->query_vars['number'] ); $offset = absint( $this->query_vars['offset'] ); $limits = ''; if ( ! empty( $number ) ) { if ( $offset ) { $limits = 'LIMIT ' . $offset . ',' . $number; } else { $limits = 'LIMIT ' . $number; } } if ( $this->query_vars['count'] ) { $fields = 'COUNT(*)'; } else { $fields = "{$wpdb->blogs}.blog_id"; } // Parse site IDs for an IN clause. $site_id = absint( $this->query_vars['ID'] ); if ( ! empty( $site_id ) ) { $this->sql_clauses['where']['ID'] = $wpdb->prepare( "{$wpdb->blogs}.blog_id = %d", $site_id ); } // Parse site IDs for an IN clause. if ( ! empty( $this->query_vars['site__in'] ) ) { $this->sql_clauses['where']['site__in'] = "{$wpdb->blogs}.blog_id IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__in'] ) ) . ' )'; } // Parse site IDs for a NOT IN clause. if ( ! empty( $this->query_vars['site__not_in'] ) ) { $this->sql_clauses['where']['site__not_in'] = "{$wpdb->blogs}.blog_id NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['site__not_in'] ) ) . ' )'; } $network_id = absint( $this->query_vars['network_id'] ); if ( ! empty( $network_id ) ) { $this->sql_clauses['where']['network_id'] = $wpdb->prepare( 'site_id = %d', $network_id ); } // Parse site network IDs for an IN clause. if ( ! empty( $this->query_vars['network__in'] ) ) { $this->sql_clauses['where']['network__in'] = 'site_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['network__in'] ) ) . ' )'; } // Parse site network IDs for a NOT IN clause. if ( ! empty( $this->query_vars['network__not_in'] ) ) { $this->sql_clauses['where']['network__not_in'] = 'site_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['network__not_in'] ) ) . ' )'; } if ( ! empty( $this->query_vars['domain'] ) ) { $this->sql_clauses['where']['domain'] = $wpdb->prepare( 'domain = %s', $this->query_vars['domain'] ); } // Parse site domain for an IN clause. if ( is_array( $this->query_vars['domain__in'] ) ) { $this->sql_clauses['where']['domain__in'] = "domain IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__in'] ) ) . "' )"; } // Parse site domain for a NOT IN clause. if ( is_array( $this->query_vars['domain__not_in'] ) ) { $this->sql_clauses['where']['domain__not_in'] = "domain NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__not_in'] ) ) . "' )"; } if ( ! empty( $this->query_vars['path'] ) ) { $this->sql_clauses['where']['path'] = $wpdb->prepare( 'path = %s', $this->query_vars['path'] ); } // Parse site path for an IN clause. if ( is_array( $this->query_vars['path__in'] ) ) { $this->sql_clauses['where']['path__in'] = "path IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__in'] ) ) . "' )"; } // Parse site path for a NOT IN clause. if ( is_array( $this->query_vars['path__not_in'] ) ) { $this->sql_clauses['where']['path__not_in'] = "path NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__not_in'] ) ) . "' )"; } if ( is_numeric( $this->query_vars['archived'] ) ) { $archived = absint( $this->query_vars['archived'] ); $this->sql_clauses['where']['archived'] = $wpdb->prepare( 'archived = %s ', absint( $archived ) ); } if ( is_numeric( $this->query_vars['mature'] ) ) { $mature = absint( $this->query_vars['mature'] ); $this->sql_clauses['where']['mature'] = $wpdb->prepare( 'mature = %d ', $mature ); } if ( is_numeric( $this->query_vars['spam'] ) ) { $spam = absint( $this->query_vars['spam'] ); $this->sql_clauses['where']['spam'] = $wpdb->prepare( 'spam = %d ', $spam ); } if ( is_numeric( $this->query_vars['deleted'] ) ) { $deleted = absint( $this->query_vars['deleted'] ); $this->sql_clauses['where']['deleted'] = $wpdb->prepare( 'deleted = %d ', $deleted ); } if ( is_numeric( $this->query_vars['public'] ) ) { $public = absint( $this->query_vars['public'] ); $this->sql_clauses['where']['public'] = $wpdb->prepare( 'public = %d ', $public ); } if ( is_numeric( $this->query_vars['lang_id'] ) ) { $lang_id = absint( $this->query_vars['lang_id'] ); $this->sql_clauses['where']['lang_id'] = $wpdb->prepare( 'lang_id = %d ', $lang_id ); } // Parse site language IDs for an IN clause. if ( ! empty( $this->query_vars['lang__in'] ) ) { $this->sql_clauses['where']['lang__in'] = 'lang_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['lang__in'] ) ) . ' )'; } // Parse site language IDs for a NOT IN clause. if ( ! empty( $this->query_vars['lang__not_in'] ) ) { $this->sql_clauses['where']['lang__not_in'] = 'lang_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['lang__not_in'] ) ) . ' )'; } // Falsey search strings are ignored. if ( strlen( $this->query_vars['search'] ) ) { $search_columns = array(); if ( $this->query_vars['search_columns'] ) { $search_columns = array_intersect( $this->query_vars['search_columns'], array( 'domain', 'path' ) ); } if ( ! $search_columns ) { $search_columns = array( 'domain', 'path' ); } /** * Filters the columns to search in a WP_Site_Query search. * * The default columns include 'domain' and 'path. * * @since 4.6.0 * * @param string[] $search_columns Array of column names to be searched. * @param string $search Text being searched. * @param WP_Site_Query $query The current WP_Site_Query instance. */ $search_columns = apply_filters( 'site_search_columns', $search_columns, $this->query_vars['search'], $this ); $this->sql_clauses['where']['search'] = $this->get_search_sql( $this->query_vars['search'], $search_columns ); } $date_query = $this->query_vars['date_query']; if ( ! empty( $date_query ) && is_array( $date_query ) ) { $this->date_query = new WP_Date_Query( $date_query, 'registered' ); // Strip leading 'AND'. $this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $this->date_query->get_sql() ); } $join = ''; $groupby = ''; if ( ! empty( $this->meta_query_clauses ) ) { $join .= $this->meta_query_clauses['join']; // Strip leading 'AND'. $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] ); if ( ! $this->query_vars['count'] ) { $groupby = "{$wpdb->blogs}.blog_id"; } } $where = implode( ' AND ', $this->sql_clauses['where'] ); $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' ); /** * Filters the site query clauses. * * @since 4.6.0 * * @param string[] $clauses An associative array of site query clauses. * @param WP_Site_Query $query Current instance of WP_Site_Query (passed by reference). */ $clauses = apply_filters_ref_array( 'sites_clauses', array( compact( $pieces ), &$this ) ); $fields = isset( $clauses['fields'] ) ? $clauses['fields'] : ''; $join = isset( $clauses['join'] ) ? $clauses['join'] : ''; $where = isset( $clauses['where'] ) ? $clauses['where'] : ''; $orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : ''; $limits = isset( $clauses['limits'] ) ? $clauses['limits'] : ''; $groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : ''; if ( $where ) { $where = 'WHERE ' . $where; } if ( $groupby ) { $groupby = 'GROUP BY ' . $groupby; } if ( $orderby ) { $orderby = "ORDER BY $orderby"; } $found_rows = ''; if ( ! $this->query_vars['no_found_rows'] ) { $found_rows = 'SQL_CALC_FOUND_ROWS'; } $this->sql_clauses['select'] = "SELECT $found_rows $fields"; $this->sql_clauses['from'] = "FROM $wpdb->blogs $join"; $this->sql_clauses['groupby'] = $groupby; $this->sql_clauses['orderby'] = $orderby; $this->sql_clauses['limits'] = $limits; $this->request = " {$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']} "; if ( $this->query_vars['count'] ) { return (int) $wpdb->get_var( $this->request ); } $site_ids = $wpdb->get_col( $this->request ); return array_map( 'intval', $site_ids ); } /** * Populates found_sites and max_num_pages properties for the current query * if the limit clause was used. * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. */ private function set_found_sites() { global $wpdb; if ( $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) { /** * Filters the query used to retrieve found site count. * * @since 4.6.0 * * @param string $found_sites_query SQL query. Default 'SELECT FOUND_ROWS()'. * @param WP_Site_Query $site_query The `WP_Site_Query` instance. */ $found_sites_query = apply_filters( 'found_sites_query', 'SELECT FOUND_ROWS()', $this ); $this->found_sites = (int) $wpdb->get_var( $found_sites_query ); } } /** * Used internally to generate an SQL string for searching across multiple columns. * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $search Search string. * @param string[] $columns Array of columns to search. * @return string Search SQL. */ protected function get_search_sql( $search, $columns ) { global $wpdb; if ( false !== strpos( $search, '*' ) ) { $like = '%' . implode( '%', array_map( array( $wpdb, 'esc_like' ), explode( '*', $search ) ) ) . '%'; } else { $like = '%' . $wpdb->esc_like( $search ) . '%'; } $searches = array(); foreach ( $columns as $column ) { $searches[] = $wpdb->prepare( "$column LIKE %s", $like ); } return '(' . implode( ' OR ', $searches ) . ')'; } /** * Parses and sanitizes 'orderby' keys passed to the site query. * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $orderby Alias for the field to order by. * @return string|false Value to used in the ORDER clause. False otherwise. */ protected function parse_orderby( $orderby ) { global $wpdb; $parsed = false; switch ( $orderby ) { case 'site__in': $site__in = implode( ',', array_map( 'absint', $this->query_vars['site__in'] ) ); $parsed = "FIELD( {$wpdb->blogs}.blog_id, $site__in )"; break; case 'network__in': $network__in = implode( ',', array_map( 'absint', $this->query_vars['network__in'] ) ); $parsed = "FIELD( {$wpdb->blogs}.site_id, $network__in )"; break; case 'domain': case 'last_updated': case 'path': case 'registered': case 'deleted': case 'spam': case 'mature': case 'archived': case 'public': $parsed = $orderby; break; case 'network_id': $parsed = 'site_id'; break; case 'domain_length': $parsed = 'CHAR_LENGTH(domain)'; break; case 'path_length': $parsed = 'CHAR_LENGTH(path)'; break; case 'id': $parsed = "{$wpdb->blogs}.blog_id"; break; } if ( ! empty( $parsed ) || empty( $this->meta_query_clauses ) ) { return $parsed; } $meta_clauses = $this->meta_query->get_clauses(); if ( empty( $meta_clauses ) ) { return $parsed; } $primary_meta_query = reset( $meta_clauses ); if ( ! empty( $primary_meta_query['key'] ) && $primary_meta_query['key'] === $orderby ) { $orderby = 'meta_value'; } switch ( $orderby ) { case 'meta_value': if ( ! empty( $primary_meta_query['type'] ) ) { $parsed = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})"; } else { $parsed = "{$primary_meta_query['alias']}.meta_value"; } break; case 'meta_value_num': $parsed = "{$primary_meta_query['alias']}.meta_value+0"; break; default: if ( isset( $meta_clauses[ $orderby ] ) ) { $meta_clause = $meta_clauses[ $orderby ]; $parsed = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})"; } } return $parsed; } /** * Parses an 'order' query variable and cast it to 'ASC' or 'DESC' as necessary. * * @since 4.6.0 * * @param string $order The 'order' query variable. * @return string The sanitized 'order' query variable. */ protected function parse_order( $order ) { if ( ! is_string( $order ) || empty( $order ) ) { return 'ASC'; } if ( 'ASC' === strtoupper( $order ) ) { return 'ASC'; } else { return 'DESC'; } } } ``` | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
programming_docs
wordpress class WP_Widget_Recent_Comments {} class WP\_Widget\_Recent\_Comments {} ===================================== Core class used to implement a Recent Comments widget. * [WP\_Widget](wp_widget) * [\_\_construct](wp_widget_recent_comments/__construct) β€” Sets up a new Recent Comments widget instance. * [flush\_widget\_cache](wp_widget_recent_comments/flush_widget_cache) β€” Flushes the Recent Comments widget cache. β€” deprecated * [form](wp_widget_recent_comments/form) β€” Outputs the settings form for the Recent Comments widget. * [recent\_comments\_style](wp_widget_recent_comments/recent_comments_style) β€” Outputs the default styles for the Recent Comments widget. * [update](wp_widget_recent_comments/update) β€” Handles updating settings for the current Recent Comments widget instance. * [widget](wp_widget_recent_comments/widget) β€” Outputs the content for the current Recent Comments widget instance. File: `wp-includes/widgets/class-wp-widget-recent-comments.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-recent-comments.php/) ``` class WP_Widget_Recent_Comments extends WP_Widget { /** * Sets up a new Recent Comments widget instance. * * @since 2.8.0 */ public function __construct() { $widget_ops = array( 'classname' => 'widget_recent_comments', 'description' => __( 'Your site&#8217;s most recent comments.' ), 'customize_selective_refresh' => true, 'show_instance_in_rest' => true, ); parent::__construct( 'recent-comments', __( 'Recent Comments' ), $widget_ops ); $this->alt_option_name = 'widget_recent_comments'; if ( is_active_widget( false, false, $this->id_base ) || is_customize_preview() ) { add_action( 'wp_head', array( $this, 'recent_comments_style' ) ); } } /** * Outputs the default styles for the Recent Comments widget. * * @since 2.8.0 */ public function recent_comments_style() { /** * Filters the Recent Comments default widget styles. * * @since 3.1.0 * * @param bool $active Whether the widget is active. Default true. * @param string $id_base The widget ID. */ if ( ! current_theme_supports( 'widgets' ) // Temp hack #14876. || ! apply_filters( 'show_recent_comments_widget_style', true, $this->id_base ) ) { return; } $type_attr = current_theme_supports( 'html5', 'style' ) ? '' : ' type="text/css"'; printf( '<style%s>.recentcomments a{display:inline !important;padding:0 !important;margin:0 !important;}</style>', $type_attr ); } /** * Outputs the content for the current Recent Comments widget instance. * * @since 2.8.0 * @since 5.4.0 Creates a unique HTML ID for the `<ul>` element * if more than one instance is displayed on the page. * * @param array $args Display arguments including 'before_title', 'after_title', * 'before_widget', and 'after_widget'. * @param array $instance Settings for the current Recent Comments widget instance. */ public function widget( $args, $instance ) { static $first_instance = true; if ( ! isset( $args['widget_id'] ) ) { $args['widget_id'] = $this->id; } $output = ''; $default_title = __( 'Recent Comments' ); $title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : $default_title; /** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */ $title = apply_filters( 'widget_title', $title, $instance, $this->id_base ); $number = ( ! empty( $instance['number'] ) ) ? absint( $instance['number'] ) : 5; if ( ! $number ) { $number = 5; } $comments = get_comments( /** * Filters the arguments for the Recent Comments widget. * * @since 3.4.0 * @since 4.9.0 Added the `$instance` parameter. * * @see WP_Comment_Query::query() for information on accepted arguments. * * @param array $comment_args An array of arguments used to retrieve the recent comments. * @param array $instance Array of settings for the current widget. */ apply_filters( 'widget_comments_args', array( 'number' => $number, 'status' => 'approve', 'post_status' => 'publish', ), $instance ) ); $output .= $args['before_widget']; if ( $title ) { $output .= $args['before_title'] . $title . $args['after_title']; } $recent_comments_id = ( $first_instance ) ? 'recentcomments' : "recentcomments-{$this->number}"; $first_instance = false; $format = current_theme_supports( 'html5', 'navigation-widgets' ) ? 'html5' : 'xhtml'; /** This filter is documented in wp-includes/widgets/class-wp-nav-menu-widget.php */ $format = apply_filters( 'navigation_widgets_format', $format ); if ( 'html5' === $format ) { // The title may be filtered: Strip out HTML and make sure the aria-label is never empty. $title = trim( strip_tags( $title ) ); $aria_label = $title ? $title : $default_title; $output .= '<nav aria-label="' . esc_attr( $aria_label ) . '">'; } $output .= '<ul id="' . esc_attr( $recent_comments_id ) . '">'; if ( is_array( $comments ) && $comments ) { // Prime cache for associated posts. (Prime post term cache if we need it for permalinks.) $post_ids = array_unique( wp_list_pluck( $comments, 'comment_post_ID' ) ); _prime_post_caches( $post_ids, strpos( get_option( 'permalink_structure' ), '%category%' ), false ); foreach ( (array) $comments as $comment ) { $output .= '<li class="recentcomments">'; $output .= sprintf( /* translators: Comments widget. 1: Comment author, 2: Post link. */ _x( '%1$s on %2$s', 'widgets' ), '<span class="comment-author-link">' . get_comment_author_link( $comment ) . '</span>', '<a href="' . esc_url( get_comment_link( $comment ) ) . '">' . get_the_title( $comment->comment_post_ID ) . '</a>' ); $output .= '</li>'; } } $output .= '</ul>'; if ( 'html5' === $format ) { $output .= '</nav>'; } $output .= $args['after_widget']; echo $output; } /** * Handles updating settings for the current Recent Comments widget instance. * * @since 2.8.0 * * @param array $new_instance New settings for this instance as input by the user via * WP_Widget::form(). * @param array $old_instance Old settings for this instance. * @return array Updated settings to save. */ public function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = sanitize_text_field( $new_instance['title'] ); $instance['number'] = absint( $new_instance['number'] ); return $instance; } /** * Outputs the settings form for the Recent Comments widget. * * @since 2.8.0 * * @param array $instance Current settings. */ public function form( $instance ) { $title = isset( $instance['title'] ) ? $instance['title'] : ''; $number = isset( $instance['number'] ) ? absint( $instance['number'] ) : 5; ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /> </p> <p> <label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of comments to show:' ); ?></label> <input class="tiny-text" id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" type="number" step="1" min="1" value="<?php echo $number; ?>" size="3" /> </p> <?php } /** * Flushes the Recent Comments widget cache. * * @since 2.8.0 * * @deprecated 4.4.0 Fragment caching was removed in favor of split queries. */ public function flush_widget_cache() { _deprecated_function( __METHOD__, '4.4.0' ); } } ``` | Uses | Description | | --- | --- | | [WP\_Widget](wp_widget) wp-includes/class-wp-widget.php | Core base class extended to register widgets. | | Version | Description | | --- | --- | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. | wordpress class WP_Customize_Widgets {} class WP\_Customize\_Widgets {} =============================== Customize Widgets class. Implements widget management in the Customizer. * [WP\_Customize\_Manager](wp_customize_manager) [WP\_Customize\_Widgets](wp_customize_widgets) is WordPress’ class for implementing widget management via the [Theme Customization API](https://developer.wordpress.org/themes/customize-api/ "Theme Customization API") for WordPress 3.9 and newer. This live preview and management of widgets via the Customizer serves as a secondary option to the traditional widget management workflow already in place. WordPress instantiates the class via [WP\_Customize\_Manager](wp_customize_manager "Class Reference/WP Customize Manager") and works by adding a new Customizer section for each of the active sidebars visible in the Customizer preview. * [\_\_construct](wp_customize_widgets/__construct) β€” Initial loader. * [\_sort\_name\_callback](wp_customize_widgets/_sort_name_callback) β€” Naturally orders available widgets by name. * [call\_widget\_update](wp_customize_widgets/call_widget_update) β€” Finds and invokes the widget update and control callbacks. * [capture\_filter\_pre\_get\_option](wp_customize_widgets/capture_filter_pre_get_option) β€” Pre-filters captured option values before retrieving. * [capture\_filter\_pre\_update\_option](wp_customize_widgets/capture_filter_pre_update_option) β€” Pre-filters captured option values before updating. * [count\_captured\_options](wp_customize_widgets/count_captured_options) β€” Retrieves the number of captured widget option updates. * [customize\_controls\_init](wp_customize_widgets/customize_controls_init) β€” Ensures all widgets get loaded into the Customizer. * [customize\_dynamic\_partial\_args](wp_customize_widgets/customize_dynamic_partial_args) β€” Filters arguments for dynamic widget partials. * [customize\_preview\_enqueue](wp_customize_widgets/customize_preview_enqueue) β€” Enqueues scripts for the Customizer preview. * [customize\_preview\_init](wp_customize_widgets/customize_preview_init) β€” Adds hooks for the Customizer preview. * [customize\_register](wp_customize_widgets/customize_register) β€” Registers Customizer settings and controls for all sidebars and widgets. * [end\_dynamic\_sidebar](wp_customize_widgets/end_dynamic_sidebar) β€” Finishes keeping track of the current sidebar being rendered. * [enqueue\_scripts](wp_customize_widgets/enqueue_scripts) β€” Enqueues scripts and styles for Customizer panel and export data to JavaScript. * [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, * [filter\_customize\_dynamic\_setting\_args](wp_customize_widgets/filter_customize_dynamic_setting_args) β€” Determines the arguments for a dynamically-created setting. * [filter\_customize\_value\_old\_sidebars\_widgets\_data](wp_customize_widgets/filter_customize_value_old_sidebars_widgets_data) β€” Filters old\_sidebars\_widgets\_data Customizer setting. * [filter\_dynamic\_sidebar\_params](wp_customize_widgets/filter_dynamic_sidebar_params) β€” Inject selective refresh data attributes into widget container elements. * [filter\_option\_sidebars\_widgets\_for\_theme\_switch](wp_customize_widgets/filter_option_sidebars_widgets_for_theme_switch) β€” Filters sidebars\_widgets option for theme switch. * [filter\_sidebars\_widgets\_for\_rendering\_widget](wp_customize_widgets/filter_sidebars_widgets_for_rendering_widget) β€” Filters sidebars\_widgets to ensure the currently-rendered widget is the only widget in the current sidebar. * [filter\_wp\_kses\_allowed\_data\_attributes](wp_customize_widgets/filter_wp_kses_allowed_data_attributes) β€” Ensures the HTML data-\* attributes for selective refresh are allowed by kses. * [get\_available\_widgets](wp_customize_widgets/get_available_widgets) β€” Builds up an index of all available widgets for use in Backbone models. * [get\_captured\_option](wp_customize_widgets/get_captured_option) β€” Retrieves the option that was captured from being saved. * [get\_captured\_options](wp_customize_widgets/get_captured_options) β€” Retrieves captured widget option updates. * [get\_instance\_hash\_key](wp_customize_widgets/get_instance_hash_key) β€” Retrieves MAC for a serialized widget instance string. * [get\_post\_value](wp_customize_widgets/get_post_value) β€” Retrieves an unslashed post value or return a default. * [get\_selective\_refreshable\_widgets](wp_customize_widgets/get_selective_refreshable_widgets) β€” List whether each registered widget can be use selective refresh. * [get\_setting\_args](wp_customize_widgets/get_setting_args) β€” Retrieves common arguments to supply when constructing a Customizer setting. * [get\_setting\_id](wp_customize_widgets/get_setting_id) β€” Converts a widget\_id into its corresponding Customizer setting ID (option name). * [get\_setting\_type](wp_customize_widgets/get_setting_type) β€” Retrieves the widget setting type given a setting ID. * [get\_widget\_control](wp_customize_widgets/get_widget_control) β€” Retrieves the widget control markup. * [get\_widget\_control\_parts](wp_customize_widgets/get_widget_control_parts) β€” Retrieves the widget control markup parts. * [is\_option\_capture\_ignored](wp_customize_widgets/is_option_capture_ignored) β€” Determines whether the captured option update should be ignored. * [is\_panel\_active](wp_customize_widgets/is_panel_active) β€” Determines whether the widgets panel is active, based on whether there are sidebars registered. * [is\_sidebar\_rendered](wp_customize_widgets/is_sidebar_rendered) β€” Determines if a sidebar is rendered on the page. * [is\_wide\_widget](wp_customize_widgets/is_wide_widget) β€” Determines whether the widget is considered "wide". * [is\_widget\_rendered](wp_customize_widgets/is_widget_rendered) β€” Determine if a widget is rendered on the page. * [is\_widget\_selective\_refreshable](wp_customize_widgets/is_widget_selective_refreshable) β€” Determines if a widget supports selective refresh. * [output\_widget\_control\_templates](wp_customize_widgets/output_widget_control_templates) β€” Renders the widget form control templates into the DOM. * [override\_sidebars\_widgets\_for\_theme\_switch](wp_customize_widgets/override_sidebars_widgets_for_theme_switch) β€” Override sidebars\_widgets for theme switch. * [parse\_widget\_id](wp_customize_widgets/parse_widget_id) β€” Converts a widget ID into its id\_base and number components. * [parse\_widget\_setting\_id](wp_customize_widgets/parse_widget_setting_id) β€” Converts a widget setting ID (option path) to its id\_base and number components. * [prepreview\_added\_sidebars\_widgets](wp_customize_widgets/prepreview_added_sidebars_widgets) β€” {@internal Missing Summary} β€” deprecated * [prepreview\_added\_widget\_instance](wp_customize_widgets/prepreview_added_widget_instance) β€” {@internal Missing Summary} β€” deprecated * [preview\_sidebars\_widgets](wp_customize_widgets/preview_sidebars_widgets) β€” When previewing, ensures the proper previewing widgets are used. * [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. * [print\_preview\_css](wp_customize_widgets/print_preview_css) β€” Inserts default style for highlighted widget at early point so theme stylesheet can override. * [print\_scripts](wp_customize_widgets/print_scripts) β€” Calls admin\_print\_scripts-widgets.php and admin\_print\_scripts hooks to allow custom scripts from plugins. * [print\_styles](wp_customize_widgets/print_styles) β€” Calls admin\_print\_styles-widgets.php and admin\_print\_styles hooks to allow custom styles from plugins. * [refresh\_nonces](wp_customize_widgets/refresh_nonces) β€” Refreshes the nonce for widget updates. * [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. * [remove\_prepreview\_filters](wp_customize_widgets/remove_prepreview_filters) β€” {@internal Missing Summary} β€” deprecated * [render\_widget\_partial](wp_customize_widgets/render_widget_partial) β€” Renders a specific widget using the supplied sidebar arguments. * [sanitize\_sidebar\_widgets](wp_customize_widgets/sanitize_sidebar_widgets) β€” Ensures sidebar widget arrays only ever contain widget IDS. * [sanitize\_sidebar\_widgets\_js\_instance](wp_customize_widgets/sanitize_sidebar_widgets_js_instance) β€” Strips out widget IDs for widgets which are no longer registered. * [sanitize\_widget\_instance](wp_customize_widgets/sanitize_widget_instance) β€” Sanitizes a widget instance. * [sanitize\_widget\_js\_instance](wp_customize_widgets/sanitize_widget_js_instance) β€” Converts a widget instance into JSON-representable format. * [schedule\_customize\_register](wp_customize_widgets/schedule_customize_register) β€” Ensures widgets are available for all types of previews. * [selective\_refresh\_init](wp_customize_widgets/selective_refresh_init) β€” Adds hooks for selective refresh. * [setup\_widget\_addition\_previews](wp_customize_widgets/setup_widget_addition_previews) β€” {@internal Missing Summary} β€” deprecated * [should\_load\_block\_editor\_scripts\_and\_styles](wp_customize_widgets/should_load_block_editor_scripts_and_styles) β€” Tells the script loader to load the scripts and styles of custom blocks if the widgets block editor is enabled. * [start\_capturing\_option\_updates](wp_customize_widgets/start_capturing_option_updates) β€” Begins keeping track of changes to widget options, caching new values. * [start\_dynamic\_sidebar](wp_customize_widgets/start_dynamic_sidebar) β€” Begins keeping track of the current sidebar being rendered. * [stop\_capturing\_option\_updates](wp_customize_widgets/stop_capturing_option_updates) β€” Undoes any changes to the options since options capture began. * [tally\_rendered\_widgets](wp_customize_widgets/tally_rendered_widgets) β€” Tracks the widgets that were rendered. * [tally\_sidebars\_via\_dynamic\_sidebar\_calls](wp_customize_widgets/tally_sidebars_via_dynamic_sidebar_calls) β€” Tallies the sidebars rendered via dynamic\_sidebar(). * [tally\_sidebars\_via\_is\_active\_sidebar\_calls](wp_customize_widgets/tally_sidebars_via_is_active_sidebar_calls) β€” Tallies the sidebars rendered via is\_active\_sidebar(). * [wp\_ajax\_update\_widget](wp_customize_widgets/wp_ajax_update_widget) β€” Updates widget settings asynchronously. File: `wp-includes/class-wp-customize-widgets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-widgets.php/) ``` final class WP_Customize_Widgets { /** * WP_Customize_Manager instance. * * @since 3.9.0 * @var WP_Customize_Manager */ public $manager; /** * All id_bases for widgets defined in core. * * @since 3.9.0 * @var array */ protected $core_widget_id_bases = array( 'archives', 'calendar', 'categories', 'custom_html', 'links', 'media_audio', 'media_image', 'media_video', 'meta', 'nav_menu', 'pages', 'recent-comments', 'recent-posts', 'rss', 'search', 'tag_cloud', 'text', ); /** * @since 3.9.0 * @var array */ protected $rendered_sidebars = array(); /** * @since 3.9.0 * @var array */ protected $rendered_widgets = array(); /** * @since 3.9.0 * @var array */ protected $old_sidebars_widgets = array(); /** * Mapping of widget ID base to whether it supports selective refresh. * * @since 4.5.0 * @var array */ protected $selective_refreshable_widgets; /** * Mapping of setting type to setting ID pattern. * * @since 4.2.0 * @var array */ protected $setting_id_patterns = array( 'widget_instance' => '/^widget_(?P<id_base>.+?)(?:\[(?P<widget_number>\d+)\])?$/', 'sidebar_widgets' => '/^sidebars_widgets\[(?P<sidebar_id>.+?)\]$/', ); /** * Initial loader. * * @since 3.9.0 * * @param WP_Customize_Manager $manager Customizer bootstrap instance. */ 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' ) ); } /** * 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. * * @since 4.5.0 * * @global WP_Widget_Factory $wp_widget_factory * * @return array Mapping of id_base to support. If theme doesn't support * selective refresh, an empty array is returned. */ 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; } /** * Determines if a widget supports selective refresh. * * @since 4.5.0 * * @param string $id_base Widget ID Base. * @return bool Whether the widget can be selective refreshed. */ public function is_widget_selective_refreshable( $id_base ) { $selective_refreshable_widgets = $this->get_selective_refreshable_widgets(); return ! empty( $selective_refreshable_widgets[ $id_base ] ); } /** * Retrieves the widget setting type given a setting ID. * * @since 4.2.0 * * @param string $setting_id Setting ID. * @return string|void Setting type. */ 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; } } } /** * Inspects the incoming customized data for any widget settings, and dynamically adds * them up-front so widgets will be initialized properly. * * @since 4.2.0 */ 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(); } } } /** * Determines the arguments for a dynamically-created setting. * * @since 4.2.0 * * @param false|array $args The arguments to the WP_Customize_Setting constructor. * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`. * @return array|false Setting arguments, false otherwise. */ 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; } /** * Retrieves an unslashed post value or return a default. * * @since 3.9.0 * * @param string $name Post value. * @param mixed $default_value Default post value. * @return mixed Unslashed post value or default value. */ protected function get_post_value( $name, $default_value = null ) { if ( ! isset( $_POST[ $name ] ) ) { return $default_value; } return wp_unslash( $_POST[ $name ] ); } /** * 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. * * @since 3.9.0 * * @global array $sidebars_widgets * @global array $_wp_sidebars_widgets */ 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'] ); } /** * 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(). * The value for old_sidebars_widgets_data gets set in the old theme's sidebars_widgets * theme_mod. * * @since 3.9.0 * * @see WP_Customize_Widgets::handle_theme_switch() * * @param array $old_sidebars_widgets * @return array */ public function filter_customize_value_old_sidebars_widgets_data( $old_sidebars_widgets ) { return $this->old_sidebars_widgets; } /** * Filters sidebars_widgets option for theme switch. * * When switching themes, the 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. * * @since 3.9.0 * * @see WP_Customize_Widgets::handle_theme_switch() * @global array $sidebars_widgets * * @param array $sidebars_widgets * @return array */ public function filter_option_sidebars_widgets_for_theme_switch( $sidebars_widgets ) { $sidebars_widgets = $GLOBALS['sidebars_widgets']; $sidebars_widgets['array_version'] = 3; return $sidebars_widgets; } /** * Ensures all widgets get loaded into the Customizer. * * Note: these actions are also fired in wp_ajax_update_widget(). * * @since 3.9.0 */ 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' ); } /** * Ensures widgets are available for all types of previews. * * When in preview, hook to {@see 'customize_register'} for settings after WordPress is loaded * so that all filters have been initialized (e.g. Widget Visibility). * * @since 3.9.0 */ public function schedule_customize_register() { if ( is_admin() ) { $this->customize_register(); } else { add_action( 'wp', array( $this, 'customize_register' ) ); } } /** * Registers Customizer settings and controls for all sidebars and widgets. * * @since 3.9.0 * * @global array $wp_registered_widgets * @global array $wp_registered_widget_controls * @global array $wp_registered_sidebars */ 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(); } } } /** * Determines whether the widgets panel is active, based on whether there are sidebars registered. * * @since 4.4.0 * * @see WP_Customize_Panel::$active_callback * * @global array $wp_registered_sidebars * @return bool Active. */ public function is_panel_active() { global $wp_registered_sidebars; return ! empty( $wp_registered_sidebars ); } /** * Converts a widget_id into its corresponding Customizer setting ID (option name). * * @since 3.9.0 * * @param string $widget_id Widget ID. * @return string Maybe-parsed widget ID. */ 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; } /** * 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 {@see 'is_wide_widget_in_customizer'} filter. * * @since 3.9.0 * * @global array $wp_registered_widget_controls * * @param string $widget_id Widget ID. * @return bool Whether or not the widget is a "wide" widget. */ 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 ); } /** * Converts a widget ID into its id_base and number components. * * @since 3.9.0 * * @param string $widget_id Widget ID. * @return array Array containing a widget's id_base and number components. */ 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; } /** * Converts a widget setting ID (option path) to its id_base and number components. * * @since 3.9.0 * * @param string $setting_id Widget setting ID. * @return array|WP_Error Array containing a widget's id_base and number components, * or a WP_Error object. */ 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' ); } /** * Calls admin_print_styles-widgets.php and admin_print_styles hooks to * allow custom styles from plugins. * * @since 3.9.0 */ 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' ); } /** * Calls admin_print_scripts-widgets.php and admin_print_scripts hooks to * allow custom scripts from plugins. * * @since 3.9.0 */ 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' ); } /** * Enqueues scripts and styles for Customizer panel and export data to JavaScript. * * @since 3.9.0 * * @global WP_Scripts $wp_scripts * @global array $wp_registered_sidebars * @global array $wp_registered_widgets */ 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&hellip;' ), __( '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' ); } } /** * Renders the widget form control templates into the DOM. * * @since 3.9.0 */ 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: &#9656; is the unicode right-pointing triangle. %s: Section title in the Customizer. */ printf( __( 'Customizing &#9656; %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&hellip;' ); ?>" 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 } /** * Calls admin_print_footer_scripts and admin_print_scripts hooks to * allow custom scripts from plugins. * * @since 3.9.0 */ 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 } /** * Retrieves common arguments to supply when constructing a Customizer setting. * * @since 3.9.0 * * @param string $id Widget setting ID. * @param array $overrides Array of setting overrides. * @return array Possibly modified setting arguments. */ 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 ); } /** * Ensures sidebar widget arrays only ever contain widget IDS. * * Used as the 'sanitize_callback' for each $sidebars_widgets setting. * * @since 3.9.0 * * @param string[] $widget_ids Array of widget IDs. * @return string[] Array of sanitized widget IDs. */ 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; } /** * Builds up an index of all available widgets for use in Backbone models. * * @since 3.9.0 * * @global array $wp_registered_widgets * @global array $wp_registered_widget_controls * * @see wp_list_widgets() * * @return array List of available widgets. */ 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; } /** * Naturally orders available widgets by name. * * @since 3.9.0 * * @param array $widget_a The first widget to compare. * @param array $widget_b The second widget to compare. * @return int Reorder position for the current widget comparison. */ protected function _sort_name_callback( $widget_a, $widget_b ) { return strnatcasecmp( $widget_a['name'], $widget_b['name'] ); } /** * Retrieves the widget control markup. * * @since 3.9.0 * * @param array $args Widget control arguments. * @return string Widget control form HTML markup. */ 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; } /** * Retrieves the widget control markup parts. * * @since 4.4.0 * * @param array $args Widget control arguments. * @return array { * @type string $control Markup for widget control wrapping form. * @type string $content The contents of the widget form itself. * } */ 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' ); } /** * Adds hooks for the Customizer preview. * * @since 3.9.0 */ 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 ); } /** * Refreshes the nonce for widget updates. * * @since 4.2.0 * * @param array $nonces Array of nonces. * @return array Array of nonces. */ public function refresh_nonces( $nonces ) { $nonces['update-widget'] = wp_create_nonce( 'update-widget' ); return $nonces; } /** * Tells the script loader to load the scripts and styles of custom blocks * if the widgets block editor is enabled. * * @since 5.8.0 * * @param bool $is_block_editor_screen Current decision about loading block assets. * @return bool Filtered decision about loading block assets. */ 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; } /** * When previewing, ensures the proper previewing widgets are used. * * Because wp_get_sidebars_widgets() gets called early at {@see 'init' } (via * 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. * * @since 3.9.0 * * @param array $sidebars_widgets List of widgets for the current sidebar. * @return array */ public function preview_sidebars_widgets( $sidebars_widgets ) { $sidebars_widgets = get_option( 'sidebars_widgets', array() ); unset( $sidebars_widgets['array_version'] ); return $sidebars_widgets; } /** * Enqueues scripts for the Customizer preview. * * @since 3.9.0 */ public function customize_preview_enqueue() { wp_enqueue_script( 'customize-preview-widgets' ); } /** * Inserts default style for highlighted widget at early point so theme * stylesheet can override. * * @since 3.9.0 */ 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 } /** * Communicates the sidebars that appeared on the page at the very end of the page, * and at the very end of the wp_footer, * * @since 3.9.0 * * @global array $wp_registered_sidebars * @global array $wp_registered_widgets */ 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 } /** * Tracks the widgets that were rendered. * * @since 3.9.0 * * @param array $widget Rendered widget to tally. */ public function tally_rendered_widgets( $widget ) { $this->rendered_widgets[ $widget['id'] ] = true; } /** * Determine if a widget is rendered on the page. * * @since 4.0.0 * * @param string $widget_id Widget ID to check. * @return bool Whether the widget is rendered. */ public function is_widget_rendered( $widget_id ) { return ! empty( $this->rendered_widgets[ $widget_id ] ); } /** * Determines if a sidebar is rendered on the page. * * @since 4.0.0 * * @param string $sidebar_id Sidebar ID to check. * @return bool Whether the sidebar is rendered. */ public function is_sidebar_rendered( $sidebar_id ) { return ! empty( $this->rendered_sidebars[ $sidebar_id ] ); } /** * Tallies the sidebars rendered via is_active_sidebar(). * * Keep track of the times that 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. * * @since 3.9.0 * * @param bool $is_active Whether the sidebar is active. * @param string $sidebar_id Sidebar ID. * @return bool Whether the sidebar is active. */ 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; } /** * Tallies the sidebars rendered via dynamic_sidebar(). * * Keep track of the times that 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. * * @since 3.9.0 * * @param bool $has_widgets Whether the current sidebar has widgets. * @param string $sidebar_id Sidebar ID. * @return bool Whether the current sidebar has widgets. */ 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; } /** * 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. * * @since 3.9.0 * * @param string $serialized_instance Widget instance. * @return string MAC for serialized widget instance. */ protected function get_instance_hash_key( $serialized_instance ) { return wp_hash( $serialized_instance ); } /** * 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*. * * @since 3.9.0 * @since 5.8.0 Added the `$id_base` parameter. * * @global WP_Widget_Factory $wp_widget_factory * * @param array $value Widget instance to sanitize. * @param string $id_base Optional. Base of the ID of the widget being sanitized. Default null. * @return array|void Sanitized widget instance. */ 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; } /** * Converts a widget instance into JSON-representable format. * * @since 3.9.0 * @since 5.8.0 Added the `$id_base` parameter. * * @global WP_Widget_Factory $wp_widget_factory * * @param array $value Widget instance to convert to JSON. * @param string $id_base Optional. Base of the ID of the widget being sanitized. Default null. * @return array JSON-converted widget instance. */ 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; } /** * 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. * * @since 3.9.0 * * @global array $wp_registered_widgets * * @param array $widget_ids List of widget IDs. * @return array Parsed list of widget IDs. */ 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; } /** * Finds and invokes the widget update and control callbacks. * * Requires that `$_POST` be populated with the instance data. * * @since 3.9.0 * * @global array $wp_registered_widget_updates * @global array $wp_registered_widget_controls * * @param string $widget_id Widget ID. * @return array|WP_Error Array containing the updated widget information. * A WP_Error object, otherwise. */ 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' ); } /** * 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(). * * @since 3.9.0 * * @see wp_ajax_save_widget() */ 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' ) ); } /* * Selective Refresh Methods */ /** * Filters arguments for dynamic widget partials. * * @since 4.5.0 * * @param array|false $partial_args Partial arguments. * @param string $partial_id Partial ID. * @return array (Maybe) modified partial arguments. */ 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; } /** * Adds hooks for selective refresh. * * @since 4.5.0 */ 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' ) ); } /** * Inject selective refresh data attributes into widget container elements. * * @since 4.5.0 * * @param array $params { * Dynamic sidebar params. * * @type array $args Sidebar args. * @type array $widget_args Widget args. * } * @see WP_Customize_Nav_Menus::filter_wp_nav_menu_args() * * @return array Params. */ 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; } /** * List of the tag names seen for before_widget strings. * * This is used in the {@see 'filter_wp_kses_allowed_html'} filter to ensure that the * data-* attributes can be allowed. * * @since 4.5.0 * @var array */ protected $before_widget_tags_seen = 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() when printed. * * @since 4.5.0 * * @param array $allowed_html Allowed HTML. * @return array (Maybe) modified allowed HTML. */ 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; } /** * Keep track of the number of times that dynamic_sidebar() was called for a given sidebar index. * * This helps facilitate the uncommon scenario where a single sidebar is rendered multiple times on a template. * * @since 4.5.0 * @var array */ protected $sidebar_instance_count = array(); /** * The current request's sidebar_instance_number context. * * @since 4.5.0 * @var int|null */ protected $context_sidebar_instance_number; /** * Current sidebar ID being rendered. * * @since 4.5.0 * @var array */ protected $current_dynamic_sidebar_id_stack = array(); /** * Begins keeping track of the current sidebar being rendered. * * Insert marker before widgets are rendered in a dynamic sidebar. * * @since 4.5.0 * * @param int|string $index Index, name, or ID of the dynamic sidebar. */ 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 ] ); } } /** * Finishes keeping track of the current sidebar being rendered. * * Inserts a marker after widgets are rendered in a dynamic sidebar. * * @since 4.5.0 * * @param int|string $index Index, name, or ID of the dynamic sidebar. */ 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 ] ); } } /** * Current sidebar being rendered. * * @since 4.5.0 * @var string|null */ protected $rendering_widget_id; /** * Current widget being rendered. * * @since 4.5.0 * @var string|null */ protected $rendering_sidebar_id; /** * Filters sidebars_widgets to ensure the currently-rendered widget is the only widget in the current sidebar. * * @since 4.5.0 * * @param array $sidebars_widgets Sidebars widgets. * @return array Filtered sidebars widgets. */ public function filter_sidebars_widgets_for_rendering_widget( $sidebars_widgets ) { $sidebars_widgets[ $this->rendering_sidebar_id ] = array( $this->rendering_widget_id ); return $sidebars_widgets; } /** * Renders a specific widget using the supplied sidebar arguments. * * @since 4.5.0 * * @see dynamic_sidebar() * * @param WP_Customize_Partial $partial Partial. * @param array $context { * Sidebar args supplied as container context. * * @type string $sidebar_id ID for sidebar for widget to render into. * @type int $sidebar_instance_number Disambiguating instance number. * } * @return string|false */ 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; } // // Option Update Capturing. // /** * List of captured widget option updates. * * @since 3.9.0 * @var array $_captured_options Values updated while option capture is happening. */ protected $_captured_options = array(); /** * Whether option capture is currently happening. * * @since 3.9.0 * @var bool $_is_current Whether option capture is currently happening or not. */ protected $_is_capturing_option_updates = false; /** * Determines whether the captured option update should be ignored. * * @since 3.9.0 * * @param string $option_name Option name. * @return bool Whether the option capture is ignored. */ protected function is_option_capture_ignored( $option_name ) { return ( 0 === strpos( $option_name, '_transient_' ) ); } /** * Retrieves captured widget option updates. * * @since 3.9.0 * * @return array Array of captured options. */ protected function get_captured_options() { return $this->_captured_options; } /** * Retrieves the option that was captured from being saved. * * @since 4.2.0 * * @param string $option_name Option name. * @param mixed $default_value Optional. Default value to return if the option does not exist. Default false. * @return mixed Value set for the option. */ 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; } /** * Retrieves the number of captured widget option updates. * * @since 3.9.0 * * @return int Number of updated options. */ protected function count_captured_options() { return count( $this->_captured_options ); } /** * Begins keeping track of changes to widget options, caching new values. * * @since 3.9.0 */ 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 ); } /** * Pre-filters captured option values before updating. * * @since 3.9.0 * * @param mixed $new_value The new option value. * @param string $option_name Name of the option. * @param mixed $old_value The old option value. * @return mixed Filtered option value. */ 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; } /** * Pre-filters captured option values before retrieving. * * @since 3.9.0 * * @param mixed $value Value to return instead of the option value. * @return mixed Filtered option value. */ 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; } /** * Undoes any changes to the options since options capture began. * * @since 3.9.0 */ 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; } /** * {@internal Missing Summary} * * See the {@see 'customize_dynamic_setting_args'} filter. * * @since 3.9.0 * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter. */ public function setup_widget_addition_previews() { _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' ); } /** * {@internal Missing Summary} * * See the {@see 'customize_dynamic_setting_args'} filter. * * @since 3.9.0 * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter. */ public function prepreview_added_sidebars_widgets() { _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' ); } /** * {@internal Missing Summary} * * See the {@see 'customize_dynamic_setting_args'} filter. * * @since 3.9.0 * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter. */ public function prepreview_added_widget_instance() { _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' ); } /** * {@internal Missing Summary} * * See the {@see 'customize_dynamic_setting_args'} filter. * * @since 3.9.0 * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter. */ public function remove_prepreview_filters() { _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' ); } } ``` | Version | Description | | --- | --- | | [3.9.0](https://developer.wordpress.org/reference/since/3.9.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Menu_Locations_Controller {} class WP\_REST\_Menu\_Locations\_Controller {} ============================================== Core class used to access menu locations via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_menu_locations_controller/__construct) β€” Menu Locations Constructor. * [get\_collection\_params](wp_rest_menu_locations_controller/get_collection_params) β€” Retrieves the query params for collections. * [get\_item](wp_rest_menu_locations_controller/get_item) β€” Retrieves a specific menu location. * [get\_item\_permissions\_check](wp_rest_menu_locations_controller/get_item_permissions_check) β€” Checks if a given request has access to read a menu location. * [get\_item\_schema](wp_rest_menu_locations_controller/get_item_schema) β€” Retrieves the menu location's schema, conforming to JSON Schema. * [get\_items](wp_rest_menu_locations_controller/get_items) β€” Retrieves all menu locations, depending on user context. * [get\_items\_permissions\_check](wp_rest_menu_locations_controller/get_items_permissions_check) β€” Checks whether a given request has permission to read menu locations. * [prepare\_item\_for\_response](wp_rest_menu_locations_controller/prepare_item_for_response) β€” Prepares a menu location object for serialization. * [prepare\_links](wp_rest_menu_locations_controller/prepare_links) β€” Prepares links for the request. * [register\_routes](wp_rest_menu_locations_controller/register_routes) β€” Registers the routes for the objects of the controller. File: `wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php/) ``` class WP_REST_Menu_Locations_Controller extends WP_REST_Controller { /** * Menu Locations Constructor. * * @since 5.9.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'menu-locations'; } /** * Registers the routes for the objects of the controller. * * @since 5.9.0 * * @see register_rest_route() */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => $this->get_collection_params(), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<location>[\w-]+)', array( 'args' => array( 'location' => array( 'description' => __( 'An alphanumeric identifier for the menu location.' ), 'type' => 'string', ), ), array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'permission_callback' => array( $this, 'get_item_permissions_check' ), 'args' => array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks whether a given request has permission to read menu locations. * * @since 5.9.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_Error|bool True if the request has read access, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { if ( ! current_user_can( 'edit_theme_options' ) ) { return new WP_Error( 'rest_cannot_view', __( 'Sorry, you are not allowed to view menu locations.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Retrieves all menu locations, depending on user context. * * @since 5.9.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { $data = array(); foreach ( get_registered_nav_menus() as $name => $description ) { $location = new stdClass(); $location->name = $name; $location->description = $description; $location = $this->prepare_item_for_response( $location, $request ); $data[ $name ] = $this->prepare_response_for_collection( $location ); } return rest_ensure_response( $data ); } /** * Checks if a given request has access to read a menu location. * * @since 5.9.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_Error|bool True if the request has read access for the item, WP_Error object otherwise. */ public function get_item_permissions_check( $request ) { if ( ! current_user_can( 'edit_theme_options' ) ) { return new WP_Error( 'rest_cannot_view', __( 'Sorry, you are not allowed to view menu locations.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Retrieves a specific menu location. * * @since 5.9.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { $registered_menus = get_registered_nav_menus(); if ( ! array_key_exists( $request['location'], $registered_menus ) ) { return new WP_Error( 'rest_menu_location_invalid', __( 'Invalid menu location.' ), array( 'status' => 404 ) ); } $location = new stdClass(); $location->name = $request['location']; $location->description = $registered_menus[ $location->name ]; $data = $this->prepare_item_for_response( $location, $request ); return rest_ensure_response( $data ); } /** * Prepares a menu location object for serialization. * * @since 5.9.0 * * @param stdClass $item Post status data. * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response Menu location data. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $location = $item; $locations = get_nav_menu_locations(); $menu = isset( $locations[ $location->name ] ) ? $locations[ $location->name ] : 0; $fields = $this->get_fields_for_response( $request ); $data = array(); if ( rest_is_field_included( 'name', $fields ) ) { $data['name'] = $location->name; } if ( rest_is_field_included( 'description', $fields ) ) { $data['description'] = $location->description; } if ( rest_is_field_included( 'menu', $fields ) ) { $data['menu'] = (int) $menu; } $context = ! empty( $request['context'] ) ? $request['context'] : 'view'; $data = $this->add_additional_fields_to_object( $data, $request ); $data = $this->filter_response_by_context( $data, $context ); $response = rest_ensure_response( $data ); if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { $response->add_links( $this->prepare_links( $location ) ); } /** * Filters menu location data returned from the REST API. * * @since 5.9.0 * * @param WP_REST_Response $response The response object. * @param object $location The original location object. * @param WP_REST_Request $request Request used to generate the response. */ return apply_filters( 'rest_prepare_menu_location', $response, $location, $request ); } /** * Prepares links for the request. * * @since 5.9.0 * * @param stdClass $location Menu location. * @return array Links for the given menu location. */ protected function prepare_links( $location ) { $base = sprintf( '%s/%s', $this->namespace, $this->rest_base ); // Entity meta. $links = array( 'self' => array( 'href' => rest_url( trailingslashit( $base ) . $location->name ), ), 'collection' => array( 'href' => rest_url( $base ), ), ); $locations = get_nav_menu_locations(); $menu = isset( $locations[ $location->name ] ) ? $locations[ $location->name ] : 0; if ( $menu ) { $path = rest_get_route_for_term( $menu ); if ( $path ) { $url = rest_url( $path ); $links['https://api.w.org/menu'][] = array( 'href' => $url, 'embeddable' => true, ); } } return $links; } /** * Retrieves the menu location's schema, conforming to JSON Schema. * * @since 5.9.0 * * @return array Item schema data. */ public function get_item_schema() { if ( $this->schema ) { return $this->add_additional_fields_schema( $this->schema ); } $this->schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'menu-location', 'type' => 'object', 'properties' => array( 'name' => array( 'description' => __( 'The name of the menu location.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'description' => array( 'description' => __( 'The description of the menu location.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'menu' => array( 'description' => __( 'The ID of the assigned menu.' ), 'type' => 'integer', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), ), ); return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the query params for collections. * * @since 5.9.0 * * @return array Collection parameters. */ public function get_collection_params() { return array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. | wordpress class Plugin_Upgrader_Skin {} class Plugin\_Upgrader\_Skin {} =============================== Plugin Upgrader Skin for WordPress Plugin Upgrades. * [WP\_Upgrader\_Skin](wp_upgrader_skin) * [\_\_construct](plugin_upgrader_skin/__construct) β€” Constructor. * [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/) ``` class Plugin_Upgrader_Skin extends WP_Upgrader_Skin { /** * Holds the plugin slug in the Plugin Directory. * * @since 2.8.0 * * @var string */ public $plugin = ''; /** * Whether the plugin is active. * * @since 2.8.0 * * @var bool */ public $plugin_active = false; /** * Whether the plugin is active for the entire network. * * @since 2.8.0 * * @var bool */ public $plugin_network_active = false; /** * Constructor. * * Sets up the plugin upgrader skin. * * @since 2.8.0 * * @param array $args Optional. The plugin upgrader skin arguments to * override default options. Default empty array. */ 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 ); } /** * Action to perform following a single plugin update. * * @since 2.8.0 */ 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&amp;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 ) ); } } } ``` | Uses | Description | | --- | --- | | [WP\_Upgrader\_Skin](wp_upgrader_skin) wp-admin/includes/class-wp-upgrader-skin.php | Generic Skin for the WordPress Upgrader classes. This skin is designed to be extended for specific purposes. | | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php. | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. | wordpress class WP_Comment_Query {} class WP\_Comment\_Query {} =========================== Core class used for querying comments. * [WP\_Comment\_Query::\_\_construct()](wp_comment_query/__construct): for accepted arguments. When you create an instance of this class passing an array of arguments to its constructor, the class will automatically run the query method and return an instance of `WP_Comment_Query`. See [\_\_construct()](wp_comment_query/__construct) method for all accepted arguments and [get\_comments()](../functions/get_comments) method to all possible return values. ``` <?php $args = array( // args here ); // The Query $comments_query = new WP_Comment_Query( $args ); $comments = $comments_query->comments; // Comment Loop if ( $comments ) { foreach ( $comments as $comment ) { echo $comment->comment_content; } } else { echo 'No comments found.'; } ?> ``` * [\_\_call](wp_comment_query/__call) β€” Make private/protected methods readable for backward compatibility. * [\_\_construct](wp_comment_query/__construct) β€” Constructor. * [fill\_descendants](wp_comment_query/fill_descendants) β€” Fetch descendants for located comments. * [get\_comment\_ids](wp_comment_query/get_comment_ids) β€” Used internally to get a list of comment IDs matching the query vars. * [get\_comments](wp_comment_query/get_comments) β€” Get a list of comments matching the query vars. * [get\_search\_sql](wp_comment_query/get_search_sql) β€” Used internally to generate an SQL string for searching across multiple columns. * [parse\_order](wp_comment_query/parse_order) β€” Parse an 'order' query variable and cast it to ASC or DESC as necessary. * [parse\_orderby](wp_comment_query/parse_orderby) β€” Parse and sanitize 'orderby' keys passed to the comment query. * [parse\_query](wp_comment_query/parse_query) β€” Parse arguments passed to the comment query with default query parameters. * [query](wp_comment_query/query) β€” Sets up the WordPress query for retrieving comments. * [set\_found\_comments](wp_comment_query/set_found_comments) β€” Populates found\_comments and max\_num\_pages properties for the current query if the limit clause was used. File: `wp-includes/class-wp-comment-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment-query.php/) ``` class WP_Comment_Query { /** * SQL for database query. * * @since 4.0.1 * @var string */ public $request; /** * Metadata query container * * @since 3.5.0 * @var WP_Meta_Query A meta query instance. */ public $meta_query = false; /** * Metadata query clauses. * * @since 4.4.0 * @var array */ protected $meta_query_clauses; /** * SQL query clauses. * * @since 4.4.0 * @var array */ protected $sql_clauses = array( 'select' => '', 'from' => '', 'where' => array(), 'groupby' => '', 'orderby' => '', 'limits' => '', ); /** * SQL WHERE clause. * * Stored after the {@see 'comments_clauses'} filter is run on the compiled WHERE sub-clauses. * * @since 4.4.2 * @var string */ protected $filtered_where_clause; /** * Date query container * * @since 3.7.0 * @var WP_Date_Query A date query instance. */ public $date_query = false; /** * Query vars set by the user. * * @since 3.1.0 * @var array */ public $query_vars; /** * Default values for query vars. * * @since 4.2.0 * @var array */ public $query_var_defaults; /** * List of comments located by the query. * * @since 4.0.0 * @var int[]|WP_Comment[] */ public $comments; /** * The amount of found comments for the current query. * * @since 4.4.0 * @var int */ public $found_comments = 0; /** * The number of pages. * * @since 4.4.0 * @var int */ public $max_num_pages = 0; /** * Make private/protected methods readable for backward compatibility. * * @since 4.0.0 * * @param string $name Method to call. * @param array $arguments Arguments to pass when calling. * @return mixed|false Return value of the callback, false otherwise. */ public function __call( $name, $arguments ) { if ( 'get_search_sql' === $name ) { return $this->get_search_sql( ...$arguments ); } return false; } /** * Constructor. * * Sets up the comment query, based on the query vars passed. * * @since 4.2.0 * @since 4.4.0 `$parent__in` and `$parent__not_in` were added. * @since 4.4.0 Order by `comment__in` was added. `$update_comment_meta_cache`, `$no_found_rows`, * `$hierarchical`, and `$update_comment_post_cache` were added. * @since 4.5.0 Introduced the `$author_url` argument. * @since 4.6.0 Introduced the `$cache_domain` argument. * @since 4.9.0 Introduced the `$paged` argument. * @since 5.1.0 Introduced the `$meta_compare_key` argument. * @since 5.3.0 Introduced the `$meta_type_key` argument. * * @param string|array $query { * Optional. Array or query string of comment query parameters. Default empty. * * @type string $author_email Comment author email address. Default empty. * @type string $author_url Comment author URL. Default empty. * @type int[] $author__in Array of author IDs to include comments for. Default empty. * @type int[] $author__not_in Array of author IDs to exclude comments for. Default empty. * @type int[] $comment__in Array of comment IDs to include. Default empty. * @type int[] $comment__not_in Array of comment IDs to exclude. Default empty. * @type bool $count Whether to return a comment count (true) or array of * comment objects (false). Default false. * @type array $date_query Date query clauses to limit comments by. See WP_Date_Query. * Default null. * @type string $fields Comment fields to return. Accepts 'ids' for comment IDs * only or empty for all fields. Default empty. * @type array $include_unapproved Array of IDs or email addresses of users whose unapproved * comments will be returned by the query regardless of * `$status`. Default empty. * @type int $karma Karma score to retrieve matching comments for. * Default empty. * @type string|string[] $meta_key Meta key or keys to filter by. * @type string|string[] $meta_value Meta value or values to filter by. * @type string $meta_compare MySQL operator used for comparing the meta value. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_compare_key MySQL operator used for comparing the meta key. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_type MySQL data type that the meta_value column will be CAST to for comparisons. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_type_key MySQL data type that the meta_key column will be CAST to for comparisons. * See WP_Meta_Query::__construct() for accepted values and default value. * @type array $meta_query An associative array of WP_Meta_Query arguments. * See WP_Meta_Query::__construct() for accepted values. * @type int $number Maximum number of comments to retrieve. * Default empty (no limit). * @type int $paged When used with `$number`, defines the page of results to return. * When used with `$offset`, `$offset` takes precedence. Default 1. * @type int $offset Number of comments to offset the query. Used to build * LIMIT clause. Default 0. * @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query. * Default: true. * @type string|array $orderby Comment 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'. * @type string $order How to order retrieved comments. Accepts 'ASC', 'DESC'. * Default: 'DESC'. * @type int $parent Parent ID of comment to retrieve children of. * Default empty. * @type int[] $parent__in Array of parent IDs of comments to retrieve children for. * Default empty. * @type int[] $parent__not_in Array of parent IDs of comments *not* to retrieve * children for. Default empty. * @type int[] $post_author__in Array of author IDs to retrieve comments for. * Default empty. * @type int[] $post_author__not_in Array of author IDs *not* to retrieve comments for. * Default empty. * @type int $post_id Limit results to those affiliated with a given post ID. * Default 0. * @type int[] $post__in Array of post IDs to include affiliated comments for. * Default empty. * @type int[] $post__not_in Array of post IDs to exclude affiliated comments for. * Default empty. * @type int $post_author Post author ID to limit results by. Default empty. * @type string|string[] $post_status Post status or array of post statuses to retrieve * affiliated comments for. Pass 'any' to match any value. * Default empty. * @type string|string[] $post_type Post type or array of post types to retrieve affiliated * comments for. Pass 'any' to match any value. Default empty. * @type string $post_name Post name to retrieve affiliated comments for. * Default empty. * @type int $post_parent Post parent ID to retrieve affiliated comments for. * Default empty. * @type string $search Search term(s) to retrieve matching comments for. * Default empty. * @type string|array $status Comment 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[] $type Include comments of a given type, or array of types. * Accepts 'comment', 'pings' (includes 'pingback' and * 'trackback'), or any custom type string. Default empty. * @type string[] $type__in Include comments from a given array of comment types. * Default empty. * @type string[] $type__not_in Exclude comments from a given array of comment types. * Default empty. * @type int $user_id Include comments for a specific user ID. Default empty. * @type bool|string $hierarchical Whether 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. * @type string $cache_domain Unique cache key to be produced when this query is stored in * an object cache. Default is 'core'. * @type bool $update_comment_meta_cache Whether to prime the metadata cache for found comments. * Default true. * @type bool $update_comment_post_cache Whether to prime the cache for comment posts. * Default false. * } */ public function __construct( $query = '' ) { $this->query_var_defaults = array( 'author_email' => '', 'author_url' => '', 'author__in' => '', 'author__not_in' => '', 'include_unapproved' => '', 'fields' => '', 'ID' => '', 'comment__in' => '', 'comment__not_in' => '', 'karma' => '', 'number' => '', 'offset' => '', 'no_found_rows' => true, 'orderby' => '', 'order' => 'DESC', 'paged' => 1, 'parent' => '', 'parent__in' => '', 'parent__not_in' => '', 'post_author__in' => '', 'post_author__not_in' => '', 'post_ID' => '', 'post_id' => 0, 'post__in' => '', 'post__not_in' => '', 'post_author' => '', 'post_name' => '', 'post_parent' => '', 'post_status' => '', 'post_type' => '', 'status' => 'all', 'type' => '', 'type__in' => '', 'type__not_in' => '', 'user_id' => '', 'search' => '', 'count' => false, 'meta_key' => '', 'meta_value' => '', 'meta_query' => '', 'date_query' => null, // See WP_Date_Query. 'hierarchical' => false, 'cache_domain' => 'core', 'update_comment_meta_cache' => true, 'update_comment_post_cache' => false, ); if ( ! empty( $query ) ) { $this->query( $query ); } } /** * Parse arguments passed to the comment query with default query parameters. * * @since 4.2.0 Extracted from WP_Comment_Query::query(). * * @param string|array $query WP_Comment_Query arguments. See WP_Comment_Query::__construct() */ public function parse_query( $query = '' ) { if ( empty( $query ) ) { $query = $this->query_vars; } $this->query_vars = wp_parse_args( $query, $this->query_var_defaults ); /** * Fires after the comment query vars have been parsed. * * @since 4.2.0 * * @param WP_Comment_Query $query The WP_Comment_Query instance (passed by reference). */ do_action_ref_array( 'parse_comment_query', array( &$this ) ); } /** * Sets up the WordPress query for retrieving comments. * * @since 3.1.0 * @since 4.1.0 Introduced 'comment__in', 'comment__not_in', 'post_author__in', * 'post_author__not_in', 'author__in', 'author__not_in', 'post__in', * 'post__not_in', 'include_unapproved', 'type__in', and 'type__not_in' * arguments to $query_vars. * @since 4.2.0 Moved parsing to WP_Comment_Query::parse_query(). * * @param string|array $query Array or URL query string of parameters. * @return array|int List of comments, or number of comments when 'count' is passed as a query var. */ public function query( $query ) { $this->query_vars = wp_parse_args( $query ); return $this->get_comments(); } /** * Get a list of comments matching the query vars. * * @since 4.2.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @return int|int[]|WP_Comment[] List of comments or number of found comments if `$count` argument is true. */ public function get_comments() { global $wpdb; $this->parse_query(); // Parse meta query. $this->meta_query = new WP_Meta_Query(); $this->meta_query->parse_query_vars( $this->query_vars ); /** * Fires before comments are retrieved. * * @since 3.1.0 * * @param WP_Comment_Query $query Current instance of WP_Comment_Query (passed by reference). */ do_action_ref_array( 'pre_get_comments', array( &$this ) ); // Reparse query vars, in case they were modified in a 'pre_get_comments' callback. $this->meta_query->parse_query_vars( $this->query_vars ); if ( ! empty( $this->meta_query->queries ) ) { $this->meta_query_clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this ); } $comment_data = null; /** * Filters the comments data before the query takes place. * * Return a non-null value to bypass WordPress' default comment queries. * * The expected return type from this filter depends on the value passed * in the request query vars: * - When `$this->query_vars['count']` is set, the filter should return * the comment count as an integer. * - When `'ids' === $this->query_vars['fields']`, the filter should return * an array of comment IDs. * - Otherwise the filter should return an array of WP_Comment objects. * * Note that if the filter returns an array of comment data, it will be assigned * to the `comments` property of the current WP_Comment_Query instance. * * Filtering functions that require pagination information are encouraged to set * the `found_comments` and `max_num_pages` properties of the WP_Comment_Query object, * passed to the filter by reference. If WP_Comment_Query does not perform a database * query, it will not have enough information to generate these values itself. * * @since 5.3.0 * @since 5.6.0 The returned array of comment data is assigned to the `comments` property * of the current WP_Comment_Query instance. * * @param array|int|null $comment_data Return an array of comment data to short-circuit WP's comment query, * the comment count as an integer if `$this->query_vars['count']` is set, * or null to allow WP to run its normal queries. * @param WP_Comment_Query $query The WP_Comment_Query instance, passed by reference. */ $comment_data = apply_filters_ref_array( 'comments_pre_query', array( $comment_data, &$this ) ); if ( null !== $comment_data ) { if ( is_array( $comment_data ) && ! $this->query_vars['count'] ) { $this->comments = $comment_data; } return $comment_data; } /* * Only use the args defined in the query_var_defaults to compute the key, * but ignore 'fields', 'update_comment_meta_cache', 'update_comment_post_cache' which does not affect query results. */ $_args = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ); unset( $_args['fields'], $_args['update_comment_meta_cache'], $_args['update_comment_post_cache'] ); $key = md5( serialize( $_args ) ); $last_changed = wp_cache_get_last_changed( 'comment' ); $cache_key = "get_comments:$key:$last_changed"; $cache_value = wp_cache_get( $cache_key, 'comment' ); if ( false === $cache_value ) { $comment_ids = $this->get_comment_ids(); if ( $comment_ids ) { $this->set_found_comments(); } $cache_value = array( 'comment_ids' => $comment_ids, 'found_comments' => $this->found_comments, ); wp_cache_add( $cache_key, $cache_value, 'comment' ); } else { $comment_ids = $cache_value['comment_ids']; $this->found_comments = $cache_value['found_comments']; } if ( $this->found_comments && $this->query_vars['number'] ) { $this->max_num_pages = ceil( $this->found_comments / $this->query_vars['number'] ); } // If querying for a count only, there's nothing more to do. if ( $this->query_vars['count'] ) { // $comment_ids is actually a count in this case. return (int) $comment_ids; } $comment_ids = array_map( 'intval', $comment_ids ); if ( 'ids' === $this->query_vars['fields'] ) { $this->comments = $comment_ids; return $this->comments; } _prime_comment_caches( $comment_ids, $this->query_vars['update_comment_meta_cache'] ); // Fetch full comment objects from the primed cache. $_comments = array(); foreach ( $comment_ids as $comment_id ) { $_comment = get_comment( $comment_id ); if ( $_comment ) { $_comments[] = $_comment; } } // Prime comment post caches. if ( $this->query_vars['update_comment_post_cache'] ) { $comment_post_ids = array(); foreach ( $_comments as $_comment ) { $comment_post_ids[] = $_comment->comment_post_ID; } _prime_post_caches( $comment_post_ids, false, false ); } /** * Filters the comment query results. * * @since 3.1.0 * * @param WP_Comment[] $_comments An array of comments. * @param WP_Comment_Query $query Current instance of WP_Comment_Query (passed by reference). */ $_comments = apply_filters_ref_array( 'the_comments', array( $_comments, &$this ) ); // Convert to WP_Comment instances. $comments = array_map( 'get_comment', $_comments ); if ( $this->query_vars['hierarchical'] ) { $comments = $this->fill_descendants( $comments ); } $this->comments = $comments; return $this->comments; } /** * Used internally to get a list of comment IDs matching the query vars. * * @since 4.4.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @return int|array A single count of comment IDs if a count query. An array of comment IDs if a full query. */ protected function get_comment_ids() { global $wpdb; // Assemble clauses related to 'comment_approved'. $approved_clauses = array(); // 'status' accepts an array or a comma-separated string. $status_clauses = array(); $statuses = wp_parse_list( $this->query_vars['status'] ); // Empty 'status' should be interpreted as 'all'. if ( empty( $statuses ) ) { $statuses = array( 'all' ); } // 'any' overrides other statuses. if ( ! in_array( 'any', $statuses, true ) ) { foreach ( $statuses as $status ) { switch ( $status ) { case 'hold': $status_clauses[] = "comment_approved = '0'"; break; case 'approve': $status_clauses[] = "comment_approved = '1'"; break; case 'all': case '': $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )"; break; default: $status_clauses[] = $wpdb->prepare( 'comment_approved = %s', $status ); break; } } if ( ! empty( $status_clauses ) ) { $approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )'; } } // User IDs or emails whose unapproved comments are included, regardless of $status. if ( ! empty( $this->query_vars['include_unapproved'] ) ) { $include_unapproved = wp_parse_list( $this->query_vars['include_unapproved'] ); $unapproved_ids = array(); $unapproved_emails = array(); foreach ( $include_unapproved as $unapproved_identifier ) { // Numeric values are assumed to be user IDs. if ( is_numeric( $unapproved_identifier ) ) { $approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier ); } else { // Otherwise we match against email addresses. if ( ! empty( $_GET['unapproved'] ) && ! empty( $_GET['moderation-hash'] ) ) { // Only include requested comment. $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' AND {$wpdb->comments}.comment_ID = %d )", $unapproved_identifier, (int) $_GET['unapproved'] ); } else { // Include all of the author's unapproved comments. $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier ); } } } } // Collapse comment_approved clauses into a single OR-separated clause. if ( ! empty( $approved_clauses ) ) { if ( 1 === count( $approved_clauses ) ) { $this->sql_clauses['where']['approved'] = $approved_clauses[0]; } else { $this->sql_clauses['where']['approved'] = '( ' . implode( ' OR ', $approved_clauses ) . ' )'; } } $order = ( 'ASC' === strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC'; // Disable ORDER BY with 'none', an empty array, or boolean false. if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) { $orderby = ''; } elseif ( ! empty( $this->query_vars['orderby'] ) ) { $ordersby = is_array( $this->query_vars['orderby'] ) ? $this->query_vars['orderby'] : preg_split( '/[,\s]/', $this->query_vars['orderby'] ); $orderby_array = array(); $found_orderby_comment_id = false; foreach ( $ordersby as $_key => $_value ) { if ( ! $_value ) { continue; } if ( is_int( $_key ) ) { $_orderby = $_value; $_order = $order; } else { $_orderby = $_key; $_order = $_value; } if ( ! $found_orderby_comment_id && in_array( $_orderby, array( 'comment_ID', 'comment__in' ), true ) ) { $found_orderby_comment_id = true; } $parsed = $this->parse_orderby( $_orderby ); if ( ! $parsed ) { continue; } if ( 'comment__in' === $_orderby ) { $orderby_array[] = $parsed; continue; } $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order ); } // If no valid clauses were found, order by comment_date_gmt. if ( empty( $orderby_array ) ) { $orderby_array[] = "$wpdb->comments.comment_date_gmt $order"; } // To ensure determinate sorting, always include a comment_ID clause. if ( ! $found_orderby_comment_id ) { $comment_id_order = ''; // Inherit order from comment_date or comment_date_gmt, if available. foreach ( $orderby_array as $orderby_clause ) { if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) { $comment_id_order = $match[1]; break; } } // If no date-related order is available, use the date from the first available clause. if ( ! $comment_id_order ) { foreach ( $orderby_array as $orderby_clause ) { if ( false !== strpos( 'ASC', $orderby_clause ) ) { $comment_id_order = 'ASC'; } else { $comment_id_order = 'DESC'; } break; } } // Default to DESC. if ( ! $comment_id_order ) { $comment_id_order = 'DESC'; } $orderby_array[] = "$wpdb->comments.comment_ID $comment_id_order"; } $orderby = implode( ', ', $orderby_array ); } else { $orderby = "$wpdb->comments.comment_date_gmt $order"; } $number = absint( $this->query_vars['number'] ); $offset = absint( $this->query_vars['offset'] ); $paged = absint( $this->query_vars['paged'] ); $limits = ''; if ( ! empty( $number ) ) { if ( $offset ) { $limits = 'LIMIT ' . $offset . ',' . $number; } else { $limits = 'LIMIT ' . ( $number * ( $paged - 1 ) ) . ',' . $number; } } if ( $this->query_vars['count'] ) { $fields = 'COUNT(*)'; } else { $fields = "$wpdb->comments.comment_ID"; } $post_id = absint( $this->query_vars['post_id'] ); if ( ! empty( $post_id ) ) { $this->sql_clauses['where']['post_id'] = $wpdb->prepare( 'comment_post_ID = %d', $post_id ); } // Parse comment IDs for an IN clause. if ( ! empty( $this->query_vars['comment__in'] ) ) { $this->sql_clauses['where']['comment__in'] = "$wpdb->comments.comment_ID IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )'; } // Parse comment IDs for a NOT IN clause. if ( ! empty( $this->query_vars['comment__not_in'] ) ) { $this->sql_clauses['where']['comment__not_in'] = "$wpdb->comments.comment_ID NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )'; } // Parse comment parent IDs for an IN clause. if ( ! empty( $this->query_vars['parent__in'] ) ) { $this->sql_clauses['where']['parent__in'] = 'comment_parent IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__in'] ) ) . ' )'; } // Parse comment parent IDs for a NOT IN clause. if ( ! empty( $this->query_vars['parent__not_in'] ) ) { $this->sql_clauses['where']['parent__not_in'] = 'comment_parent NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__not_in'] ) ) . ' )'; } // Parse comment post IDs for an IN clause. if ( ! empty( $this->query_vars['post__in'] ) ) { $this->sql_clauses['where']['post__in'] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )'; } // Parse comment post IDs for a NOT IN clause. if ( ! empty( $this->query_vars['post__not_in'] ) ) { $this->sql_clauses['where']['post__not_in'] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )'; } if ( '' !== $this->query_vars['author_email'] ) { $this->sql_clauses['where']['author_email'] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] ); } if ( '' !== $this->query_vars['author_url'] ) { $this->sql_clauses['where']['author_url'] = $wpdb->prepare( 'comment_author_url = %s', $this->query_vars['author_url'] ); } if ( '' !== $this->query_vars['karma'] ) { $this->sql_clauses['where']['karma'] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] ); } // Filtering by comment_type: 'type', 'type__in', 'type__not_in'. $raw_types = array( 'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ), 'NOT IN' => (array) $this->query_vars['type__not_in'], ); $comment_types = array(); foreach ( $raw_types as $operator => $_raw_types ) { $_raw_types = array_unique( $_raw_types ); foreach ( $_raw_types as $type ) { switch ( $type ) { // An empty translates to 'all', for backward compatibility. case '': case 'all': break; case 'comment': case 'comments': $comment_types[ $operator ][] = "''"; $comment_types[ $operator ][] = "'comment'"; break; case 'pings': $comment_types[ $operator ][] = "'pingback'"; $comment_types[ $operator ][] = "'trackback'"; break; default: $comment_types[ $operator ][] = $wpdb->prepare( '%s', $type ); break; } } if ( ! empty( $comment_types[ $operator ] ) ) { $types_sql = implode( ', ', $comment_types[ $operator ] ); $this->sql_clauses['where'][ 'comment_type__' . strtolower( str_replace( ' ', '_', $operator ) ) ] = "comment_type $operator ($types_sql)"; } } $parent = $this->query_vars['parent']; if ( $this->query_vars['hierarchical'] && ! $parent ) { $parent = 0; } if ( '' !== $parent ) { $this->sql_clauses['where']['parent'] = $wpdb->prepare( 'comment_parent = %d', $parent ); } if ( is_array( $this->query_vars['user_id'] ) ) { $this->sql_clauses['where']['user_id'] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')'; } elseif ( '' !== $this->query_vars['user_id'] ) { $this->sql_clauses['where']['user_id'] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] ); } // Falsey search strings are ignored. if ( isset( $this->query_vars['search'] ) && strlen( $this->query_vars['search'] ) ) { $search_sql = $this->get_search_sql( $this->query_vars['search'], array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' ) ); // Strip leading 'AND'. $this->sql_clauses['where']['search'] = preg_replace( '/^\s*AND\s*/', '', $search_sql ); } // If any post-related query vars are passed, join the posts table. $join_posts_table = false; $plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent' ) ); $post_fields = array_filter( $plucked ); if ( ! empty( $post_fields ) ) { $join_posts_table = true; foreach ( $post_fields as $field_name => $field_value ) { // $field_value may be an array. $esses = array_fill( 0, count( (array) $field_value ), '%s' ); // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value ); } } // 'post_status' and 'post_type' are handled separately, due to the specialized behavior of 'any'. foreach ( array( 'post_status', 'post_type' ) as $field_name ) { $q_values = array(); if ( ! empty( $this->query_vars[ $field_name ] ) ) { $q_values = $this->query_vars[ $field_name ]; if ( ! is_array( $q_values ) ) { $q_values = explode( ',', $q_values ); } // 'any' will cause the query var to be ignored. if ( in_array( 'any', $q_values, true ) || empty( $q_values ) ) { continue; } $join_posts_table = true; $esses = array_fill( 0, count( $q_values ), '%s' ); // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $q_values ); } } // Comment author IDs for an IN clause. if ( ! empty( $this->query_vars['author__in'] ) ) { $this->sql_clauses['where']['author__in'] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )'; } // Comment author IDs for a NOT IN clause. if ( ! empty( $this->query_vars['author__not_in'] ) ) { $this->sql_clauses['where']['author__not_in'] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )'; } // Post author IDs for an IN clause. if ( ! empty( $this->query_vars['post_author__in'] ) ) { $join_posts_table = true; $this->sql_clauses['where']['post_author__in'] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )'; } // Post author IDs for a NOT IN clause. if ( ! empty( $this->query_vars['post_author__not_in'] ) ) { $join_posts_table = true; $this->sql_clauses['where']['post_author__not_in'] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )'; } $join = ''; $groupby = ''; if ( $join_posts_table ) { $join .= "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID"; } if ( ! empty( $this->meta_query_clauses ) ) { $join .= $this->meta_query_clauses['join']; // Strip leading 'AND'. $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] ); if ( ! $this->query_vars['count'] ) { $groupby = "{$wpdb->comments}.comment_ID"; } } if ( ! empty( $this->query_vars['date_query'] ) && is_array( $this->query_vars['date_query'] ) ) { $this->date_query = new WP_Date_Query( $this->query_vars['date_query'], 'comment_date' ); // Strip leading 'AND'. $this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $this->date_query->get_sql() ); } $where = implode( ' AND ', $this->sql_clauses['where'] ); $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' ); /** * Filters the comment query clauses. * * @since 3.1.0 * * @param string[] $clauses An associative array of comment query clauses. * @param WP_Comment_Query $query Current instance of WP_Comment_Query (passed by reference). */ $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) ); $fields = isset( $clauses['fields'] ) ? $clauses['fields'] : ''; $join = isset( $clauses['join'] ) ? $clauses['join'] : ''; $where = isset( $clauses['where'] ) ? $clauses['where'] : ''; $orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : ''; $limits = isset( $clauses['limits'] ) ? $clauses['limits'] : ''; $groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : ''; $this->filtered_where_clause = $where; if ( $where ) { $where = 'WHERE ' . $where; } if ( $groupby ) { $groupby = 'GROUP BY ' . $groupby; } if ( $orderby ) { $orderby = "ORDER BY $orderby"; } $found_rows = ''; if ( ! $this->query_vars['no_found_rows'] ) { $found_rows = 'SQL_CALC_FOUND_ROWS'; } $this->sql_clauses['select'] = "SELECT $found_rows $fields"; $this->sql_clauses['from'] = "FROM $wpdb->comments $join"; $this->sql_clauses['groupby'] = $groupby; $this->sql_clauses['orderby'] = $orderby; $this->sql_clauses['limits'] = $limits; $this->request = " {$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']} "; if ( $this->query_vars['count'] ) { return (int) $wpdb->get_var( $this->request ); } else { $comment_ids = $wpdb->get_col( $this->request ); return array_map( 'intval', $comment_ids ); } } /** * Populates found_comments and max_num_pages properties for the current * query if the limit clause was used. * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. */ private function set_found_comments() { global $wpdb; if ( $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) { /** * Filters the query used to retrieve found comment count. * * @since 4.4.0 * * @param string $found_comments_query SQL query. Default 'SELECT FOUND_ROWS()'. * @param WP_Comment_Query $comment_query The `WP_Comment_Query` instance. */ $found_comments_query = apply_filters( 'found_comments_query', 'SELECT FOUND_ROWS()', $this ); $this->found_comments = (int) $wpdb->get_var( $found_comments_query ); } } /** * Fetch descendants for located comments. * * Instead of calling `get_children()` separately on each child comment, we do a single set of queries to fetch * the descendant trees for all matched top-level comments. * * @since 4.4.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param WP_Comment[] $comments Array of top-level comments whose descendants should be filled in. * @return array */ protected function fill_descendants( $comments ) { global $wpdb; $levels = array( 0 => wp_list_pluck( $comments, 'comment_ID' ), ); $key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) ); $last_changed = wp_cache_get_last_changed( 'comment' ); // Fetch an entire level of the descendant tree at a time. $level = 0; $exclude_keys = array( 'parent', 'parent__in', 'parent__not_in' ); do { // Parent-child relationships may be cached. Only query for those that are not. $child_ids = array(); $uncached_parent_ids = array(); $_parent_ids = $levels[ $level ]; foreach ( $_parent_ids as $parent_id ) { $cache_key = "get_comment_child_ids:$parent_id:$key:$last_changed"; $parent_child_ids = wp_cache_get( $cache_key, 'comment' ); if ( false !== $parent_child_ids ) { $child_ids = array_merge( $child_ids, $parent_child_ids ); } else { $uncached_parent_ids[] = $parent_id; } } if ( $uncached_parent_ids ) { // Fetch this level of comments. $parent_query_args = $this->query_vars; foreach ( $exclude_keys as $exclude_key ) { $parent_query_args[ $exclude_key ] = ''; } $parent_query_args['parent__in'] = $uncached_parent_ids; $parent_query_args['no_found_rows'] = true; $parent_query_args['hierarchical'] = false; $parent_query_args['offset'] = 0; $parent_query_args['number'] = 0; $level_comments = get_comments( $parent_query_args ); // Cache parent-child relationships. $parent_map = array_fill_keys( $uncached_parent_ids, array() ); foreach ( $level_comments as $level_comment ) { $parent_map[ $level_comment->comment_parent ][] = $level_comment->comment_ID; $child_ids[] = $level_comment->comment_ID; } $data = array(); foreach ( $parent_map as $parent_id => $children ) { $cache_key = "get_comment_child_ids:$parent_id:$key:$last_changed"; $data[ $cache_key ] = $children; } wp_cache_set_multiple( $data, 'comment' ); } $level++; $levels[ $level ] = $child_ids; } while ( $child_ids ); // Prime comment caches for non-top-level comments. $descendant_ids = array(); for ( $i = 1, $c = count( $levels ); $i < $c; $i++ ) { $descendant_ids = array_merge( $descendant_ids, $levels[ $i ] ); } _prime_comment_caches( $descendant_ids, $this->query_vars['update_comment_meta_cache'] ); // Assemble a flat array of all comments + descendants. $all_comments = $comments; foreach ( $descendant_ids as $descendant_id ) { $all_comments[] = get_comment( $descendant_id ); } // If a threaded representation was requested, build the tree. if ( 'threaded' === $this->query_vars['hierarchical'] ) { $threaded_comments = array(); $ref = array(); foreach ( $all_comments as $k => $c ) { $_c = get_comment( $c->comment_ID ); // If the comment isn't in the reference array, it goes in the top level of the thread. if ( ! isset( $ref[ $c->comment_parent ] ) ) { $threaded_comments[ $_c->comment_ID ] = $_c; $ref[ $_c->comment_ID ] = $threaded_comments[ $_c->comment_ID ]; // Otherwise, set it as a child of its parent. } else { $ref[ $_c->comment_parent ]->add_child( $_c ); $ref[ $_c->comment_ID ] = $ref[ $_c->comment_parent ]->get_child( $_c->comment_ID ); } } // Set the 'populated_children' flag, to ensure additional database queries aren't run. foreach ( $ref as $_ref ) { $_ref->populated_children( true ); } $comments = $threaded_comments; } else { $comments = $all_comments; } return $comments; } /** * Used internally to generate an SQL string for searching across multiple columns. * * @since 3.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $search Search string. * @param string[] $columns Array of columns to search. * @return string Search SQL. */ protected function get_search_sql( $search, $columns ) { global $wpdb; $like = '%' . $wpdb->esc_like( $search ) . '%'; $searches = array(); foreach ( $columns as $column ) { $searches[] = $wpdb->prepare( "$column LIKE %s", $like ); } return ' AND (' . implode( ' OR ', $searches ) . ')'; } /** * Parse and sanitize 'orderby' keys passed to the comment query. * * @since 4.2.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $orderby Alias for the field to order by. * @return string|false Value to used in the ORDER clause. False otherwise. */ protected function parse_orderby( $orderby ) { global $wpdb; $allowed_keys = array( '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', ); if ( ! empty( $this->query_vars['meta_key'] ) ) { $allowed_keys[] = $this->query_vars['meta_key']; $allowed_keys[] = 'meta_value'; $allowed_keys[] = 'meta_value_num'; } $meta_query_clauses = $this->meta_query->get_clauses(); if ( $meta_query_clauses ) { $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_query_clauses ) ); } $parsed = false; if ( $this->query_vars['meta_key'] === $orderby || 'meta_value' === $orderby ) { $parsed = "$wpdb->commentmeta.meta_value"; } elseif ( 'meta_value_num' === $orderby ) { $parsed = "$wpdb->commentmeta.meta_value+0"; } elseif ( 'comment__in' === $orderby ) { $comment__in = implode( ',', array_map( 'absint', $this->query_vars['comment__in'] ) ); $parsed = "FIELD( {$wpdb->comments}.comment_ID, $comment__in )"; } elseif ( in_array( $orderby, $allowed_keys, true ) ) { if ( isset( $meta_query_clauses[ $orderby ] ) ) { $meta_clause = $meta_query_clauses[ $orderby ]; $parsed = sprintf( 'CAST(%s.meta_value AS %s)', esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) ); } else { $parsed = "$wpdb->comments.$orderby"; } } return $parsed; } /** * Parse an 'order' query variable and cast it to ASC or DESC as necessary. * * @since 4.2.0 * * @param string $order The 'order' query variable. * @return string The sanitized 'order' query variable. */ protected function parse_order( $order ) { if ( ! is_string( $order ) || empty( $order ) ) { return 'DESC'; } if ( 'ASC' === strtoupper( $order ) ) { return 'ASC'; } else { return 'DESC'; } } } ``` | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
programming_docs
wordpress class WP_Term_Query {} class WP\_Term\_Query {} ======================== Class used for querying terms. * [WP\_Term\_Query::\_\_construct()](wp_term_query/__construct): for accepted arguments. * [\_\_construct](wp_term_query/__construct) β€” Constructor. * [format\_terms](wp_term_query/format_terms) β€” Format response depending on field requested. * [get\_search\_sql](wp_term_query/get_search_sql) β€” Used internally to generate a SQL string related to the 'search' parameter. * [get\_terms](wp_term_query/get_terms) β€” Retrieves the query results. * [parse\_order](wp_term_query/parse_order) β€” Parse an 'order' query variable and cast it to ASC or DESC as necessary. * [parse\_orderby](wp_term_query/parse_orderby) β€” Parse and sanitize 'orderby' keys passed to the term query. * [parse\_orderby\_meta](wp_term_query/parse_orderby_meta) β€” Generate the ORDER BY clause for an 'orderby' param that is potentially related to a meta query. * [parse\_query](wp_term_query/parse_query) β€” Parse arguments passed to the term query with default query parameters. * [populate\_terms](wp_term_query/populate_terms) β€” Creates an array of term objects from an array of term IDs. * [query](wp_term_query/query) β€” Sets up the query and retrieves the results. File: `wp-includes/class-wp-term-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-term-query.php/) ``` class WP_Term_Query { /** * SQL string used to perform database query. * * @since 4.6.0 * @var string */ public $request; /** * Metadata query container. * * @since 4.6.0 * @var WP_Meta_Query A meta query instance. */ public $meta_query = false; /** * Metadata query clauses. * * @since 4.6.0 * @var array */ protected $meta_query_clauses; /** * SQL query clauses. * * @since 4.6.0 * @var array */ protected $sql_clauses = array( 'select' => '', 'from' => '', 'where' => array(), 'orderby' => '', 'limits' => '', ); /** * Query vars set by the user. * * @since 4.6.0 * @var array */ public $query_vars; /** * Default values for query vars. * * @since 4.6.0 * @var array */ public $query_var_defaults; /** * List of terms located by the query. * * @since 4.6.0 * @var array */ public $terms; /** * Constructor. * * Sets up the term query, based on the query vars passed. * * @since 4.6.0 * @since 4.6.0 Introduced 'term_taxonomy_id' parameter. * @since 4.7.0 Introduced 'object_ids' parameter. * @since 4.9.0 Added 'slug__in' support for 'orderby'. * @since 5.1.0 Introduced the 'meta_compare_key' parameter. * @since 5.3.0 Introduced the 'meta_type_key' parameter. * * @param string|array $query { * Optional. Array or query string of term query parameters. Default empty. * * @type string|string[] $taxonomy Taxonomy name, or array of taxonomy names, to which results * should be limited. * @type int|int[] $object_ids Object ID, or array of object IDs. Results will be * limited to terms associated with these objects. * @type string $orderby Field(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'. * @type string $order Whether to order terms in ascending or descending order. * Accepts 'ASC' (ascending) or 'DESC' (descending). * Default 'ASC'. * @type bool|int $hide_empty Whether to hide terms not assigned to any posts. Accepts * 1|true or 0|false. Default 1|true. * @type int[]|string $include Array or comma/space-separated string of term IDs to include. * Default empty array. * @type int[]|string $exclude Array or comma/space-separated string of term IDs to exclude. * If `$include` is non-empty, `$exclude` is ignored. * Default empty array. * @type int[]|string $exclude_tree Array 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. * @type int|string $number Maximum 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. * @type int $offset The number by which to offset the terms query. Default empty. * @type string $fields Term 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'. * @type bool $count Whether to return a term count. If true, will take precedence * over `$fields`. Default false. * @type string|string[] $name Name or array of names to return term(s) for. * Default empty. * @type string|string[] $slug Slug or array of slugs to return term(s) for. * Default empty. * @type int|int[] $term_taxonomy_id Term taxonomy ID, or array of term taxonomy IDs, * to match when querying terms. * @type bool $hierarchical Whether to include terms that have non-empty descendants * (even if `$hide_empty` is set to true). Default true. * @type string $search Search criteria to match terms. Will be SQL-formatted with * wildcards before and after. Default empty. * @type string $name__like Retrieve terms with criteria by which a term is LIKE * `$name__like`. Default empty. * @type string $description__like Retrieve terms where the description is LIKE * `$description__like`. Default empty. * @type bool $pad_counts Whether to pad the quantity of a term's children in the * quantity of each term's "count" object variable. * Default false. * @type string $get Whether to return terms regardless of ancestry or whether the * terms are empty. Accepts 'all' or '' (disabled). * Default ''. * @type int $child_of Term ID to retrieve child terms of. If multiple taxonomies * are passed, `$child_of` is ignored. Default 0. * @type int $parent Parent term ID to retrieve direct-child terms of. * Default empty. * @type bool $childless True to limit results to terms that have no children. * This parameter has no effect on non-hierarchical taxonomies. * Default false. * @type string $cache_domain Unique cache key to be produced when this query is stored in * an object cache. Default 'core'. * @type bool $update_term_meta_cache Whether to prime meta caches for matched terms. Default true. * @type string|string[] $meta_key Meta key or keys to filter by. * @type string|string[] $meta_value Meta value or values to filter by. * @type string $meta_compare MySQL operator used for comparing the meta value. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_compare_key MySQL operator used for comparing the meta key. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_type MySQL data type that the meta_value column will be CAST to for comparisons. * See WP_Meta_Query::__construct() for accepted values and default value. * @type string $meta_type_key MySQL data type that the meta_key column will be CAST to for comparisons. * See WP_Meta_Query::__construct() for accepted values and default value. * @type array $meta_query An associative array of WP_Meta_Query arguments. * See WP_Meta_Query::__construct() for accepted values. * } */ public function __construct( $query = '' ) { $this->query_var_defaults = array( 'taxonomy' => null, 'object_ids' => null, 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => true, 'include' => array(), 'exclude' => array(), 'exclude_tree' => array(), 'number' => '', 'offset' => '', 'fields' => 'all', 'count' => false, 'name' => '', 'slug' => '', 'term_taxonomy_id' => '', 'hierarchical' => true, 'search' => '', 'name__like' => '', 'description__like' => '', 'pad_counts' => false, 'get' => '', 'child_of' => 0, 'parent' => '', 'childless' => false, 'cache_domain' => 'core', 'update_term_meta_cache' => true, 'meta_query' => '', 'meta_key' => '', 'meta_value' => '', 'meta_type' => '', 'meta_compare' => '', ); if ( ! empty( $query ) ) { $this->query( $query ); } } /** * Parse arguments passed to the term query with default query parameters. * * @since 4.6.0 * * @param string|array $query WP_Term_Query arguments. See WP_Term_Query::__construct() */ public function parse_query( $query = '' ) { if ( empty( $query ) ) { $query = $this->query_vars; } $taxonomies = isset( $query['taxonomy'] ) ? (array) $query['taxonomy'] : null; /** * Filters the terms query default arguments. * * Use {@see 'get_terms_args'} to filter the passed arguments. * * @since 4.4.0 * * @param array $defaults An array of default get_terms() arguments. * @param string[] $taxonomies An array of taxonomy names. */ $this->query_var_defaults = apply_filters( 'get_terms_defaults', $this->query_var_defaults, $taxonomies ); $query = wp_parse_args( $query, $this->query_var_defaults ); $query['number'] = absint( $query['number'] ); $query['offset'] = absint( $query['offset'] ); // 'parent' overrides 'child_of'. if ( 0 < (int) $query['parent'] ) { $query['child_of'] = false; } if ( 'all' === $query['get'] ) { $query['childless'] = false; $query['child_of'] = 0; $query['hide_empty'] = 0; $query['hierarchical'] = false; $query['pad_counts'] = false; } $query['taxonomy'] = $taxonomies; $this->query_vars = $query; /** * Fires after term query vars have been parsed. * * @since 4.6.0 * * @param WP_Term_Query $query Current instance of WP_Term_Query. */ do_action( 'parse_term_query', $this ); } /** * Sets up the query and retrieves the results. * * The return type varies depending on the value passed to `$args['fields']`. See * WP_Term_Query::get_terms() for details. * * @since 4.6.0 * * @param string|array $query Array or URL query string of parameters. * @return WP_Term[]|int[]|string[]|string Array of terms, or number of terms as numeric string * when 'count' is passed as a query var. */ public function query( $query ) { $this->query_vars = wp_parse_args( $query ); return $this->get_terms(); } /** * Retrieves the query results. * * The return type varies depending on the value passed to `$args['fields']`. * * The following will result in an array of `WP_Term` objects being returned: * * - 'all' * - 'all_with_object_id' * * The following will result in a numeric string being returned: * * - 'count' * * The following will result in an array of text strings being returned: * * - 'id=>name' * - 'id=>slug' * - 'names' * - 'slugs' * * The following will result in an array of numeric strings being returned: * * - 'id=>parent' * * The following will result in an array of integers being returned: * * - 'ids' * - 'tt_ids' * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @return WP_Term[]|int[]|string[]|string Array of terms, or number of terms as numeric string * when 'count' is passed as a query var. */ public function get_terms() { global $wpdb; $this->parse_query( $this->query_vars ); $args = &$this->query_vars; // Set up meta_query so it's available to 'pre_get_terms'. $this->meta_query = new WP_Meta_Query(); $this->meta_query->parse_query_vars( $args ); /** * Fires before terms are retrieved. * * @since 4.6.0 * * @param WP_Term_Query $query Current instance of WP_Term_Query (passed by reference). */ do_action_ref_array( 'pre_get_terms', array( &$this ) ); $taxonomies = (array) $args['taxonomy']; // Save queries by not crawling the tree in the case of multiple taxes or a flat tax. $has_hierarchical_tax = false; if ( $taxonomies ) { foreach ( $taxonomies as $_tax ) { if ( is_taxonomy_hierarchical( $_tax ) ) { $has_hierarchical_tax = true; } } } else { // When no taxonomies are provided, assume we have to descend the tree. $has_hierarchical_tax = true; } if ( ! $has_hierarchical_tax ) { $args['hierarchical'] = false; $args['pad_counts'] = false; } // 'parent' overrides 'child_of'. if ( 0 < (int) $args['parent'] ) { $args['child_of'] = false; } if ( 'all' === $args['get'] ) { $args['childless'] = false; $args['child_of'] = 0; $args['hide_empty'] = 0; $args['hierarchical'] = false; $args['pad_counts'] = false; } /** * Filters the terms query arguments. * * @since 3.1.0 * * @param array $args An array of get_terms() arguments. * @param string[] $taxonomies An array of taxonomy names. */ $args = apply_filters( 'get_terms_args', $args, $taxonomies ); // Avoid the query if the queried parent/child_of term has no descendants. $child_of = $args['child_of']; $parent = $args['parent']; if ( $child_of ) { $_parent = $child_of; } elseif ( $parent ) { $_parent = $parent; } else { $_parent = false; } if ( $_parent ) { $in_hierarchy = false; foreach ( $taxonomies as $_tax ) { $hierarchy = _get_term_hierarchy( $_tax ); if ( isset( $hierarchy[ $_parent ] ) ) { $in_hierarchy = true; } } if ( ! $in_hierarchy ) { if ( 'count' === $args['fields'] ) { return 0; } else { $this->terms = array(); return $this->terms; } } } // 'term_order' is a legal sort order only when joining the relationship table. $_orderby = $this->query_vars['orderby']; if ( 'term_order' === $_orderby && empty( $this->query_vars['object_ids'] ) ) { $_orderby = 'term_id'; } $orderby = $this->parse_orderby( $_orderby ); if ( $orderby ) { $orderby = "ORDER BY $orderby"; } $order = $this->parse_order( $this->query_vars['order'] ); if ( $taxonomies ) { $this->sql_clauses['where']['taxonomy'] = "tt.taxonomy IN ('" . implode( "', '", array_map( 'esc_sql', $taxonomies ) ) . "')"; } if ( empty( $args['exclude'] ) ) { $args['exclude'] = array(); } if ( empty( $args['include'] ) ) { $args['include'] = array(); } $exclude = $args['exclude']; $exclude_tree = $args['exclude_tree']; $include = $args['include']; $inclusions = ''; if ( ! empty( $include ) ) { $exclude = ''; $exclude_tree = ''; $inclusions = implode( ',', wp_parse_id_list( $include ) ); } if ( ! empty( $inclusions ) ) { $this->sql_clauses['where']['inclusions'] = 't.term_id IN ( ' . $inclusions . ' )'; } $exclusions = array(); if ( ! empty( $exclude_tree ) ) { $exclude_tree = wp_parse_id_list( $exclude_tree ); $excluded_children = $exclude_tree; foreach ( $exclude_tree as $extrunk ) { $excluded_children = array_merge( $excluded_children, (array) get_terms( array( 'taxonomy' => reset( $taxonomies ), 'child_of' => (int) $extrunk, 'fields' => 'ids', 'hide_empty' => 0, ) ) ); } $exclusions = array_merge( $excluded_children, $exclusions ); } if ( ! empty( $exclude ) ) { $exclusions = array_merge( wp_parse_id_list( $exclude ), $exclusions ); } // 'childless' terms are those without an entry in the flattened term hierarchy. $childless = (bool) $args['childless']; if ( $childless ) { foreach ( $taxonomies as $_tax ) { $term_hierarchy = _get_term_hierarchy( $_tax ); $exclusions = array_merge( array_keys( $term_hierarchy ), $exclusions ); } } if ( ! empty( $exclusions ) ) { $exclusions = 't.term_id NOT IN (' . implode( ',', array_map( 'intval', $exclusions ) ) . ')'; } else { $exclusions = ''; } /** * Filters the terms to exclude from the terms query. * * @since 2.3.0 * * @param string $exclusions `NOT IN` clause of the terms query. * @param array $args An array of terms query arguments. * @param string[] $taxonomies An array of taxonomy names. */ $exclusions = apply_filters( 'list_terms_exclusions', $exclusions, $args, $taxonomies ); if ( ! empty( $exclusions ) ) { // Strip leading 'AND'. Must do string manipulation here for backward compatibility with filter. $this->sql_clauses['where']['exclusions'] = preg_replace( '/^\s*AND\s*/', '', $exclusions ); } if ( '' === $args['name'] ) { $args['name'] = array(); } else { $args['name'] = (array) $args['name']; } if ( ! empty( $args['name'] ) ) { $names = $args['name']; foreach ( $names as &$_name ) { // `sanitize_term_field()` returns slashed data. $_name = stripslashes( sanitize_term_field( 'name', $_name, 0, reset( $taxonomies ), 'db' ) ); } $this->sql_clauses['where']['name'] = "t.name IN ('" . implode( "', '", array_map( 'esc_sql', $names ) ) . "')"; } if ( '' === $args['slug'] ) { $args['slug'] = array(); } else { $args['slug'] = array_map( 'sanitize_title', (array) $args['slug'] ); } if ( ! empty( $args['slug'] ) ) { $slug = implode( "', '", $args['slug'] ); $this->sql_clauses['where']['slug'] = "t.slug IN ('" . $slug . "')"; } if ( '' === $args['term_taxonomy_id'] ) { $args['term_taxonomy_id'] = array(); } else { $args['term_taxonomy_id'] = array_map( 'intval', (array) $args['term_taxonomy_id'] ); } if ( ! empty( $args['term_taxonomy_id'] ) ) { $tt_ids = implode( ',', $args['term_taxonomy_id'] ); $this->sql_clauses['where']['term_taxonomy_id'] = "tt.term_taxonomy_id IN ({$tt_ids})"; } if ( ! empty( $args['name__like'] ) ) { $this->sql_clauses['where']['name__like'] = $wpdb->prepare( 't.name LIKE %s', '%' . $wpdb->esc_like( $args['name__like'] ) . '%' ); } if ( ! empty( $args['description__like'] ) ) { $this->sql_clauses['where']['description__like'] = $wpdb->prepare( 'tt.description LIKE %s', '%' . $wpdb->esc_like( $args['description__like'] ) . '%' ); } if ( '' === $args['object_ids'] ) { $args['object_ids'] = array(); } else { $args['object_ids'] = array_map( 'intval', (array) $args['object_ids'] ); } if ( ! empty( $args['object_ids'] ) ) { $object_ids = implode( ', ', $args['object_ids'] ); $this->sql_clauses['where']['object_ids'] = "tr.object_id IN ($object_ids)"; } /* * When querying for object relationships, the 'count > 0' check * added by 'hide_empty' is superfluous. */ if ( ! empty( $args['object_ids'] ) ) { $args['hide_empty'] = false; } if ( '' !== $parent ) { $parent = (int) $parent; $this->sql_clauses['where']['parent'] = "tt.parent = '$parent'"; } $hierarchical = $args['hierarchical']; if ( 'count' === $args['fields'] ) { $hierarchical = false; } if ( $args['hide_empty'] && ! $hierarchical ) { $this->sql_clauses['where']['count'] = 'tt.count > 0'; } $number = $args['number']; $offset = $args['offset']; // Don't limit the query results when we have to descend the family tree. if ( $number && ! $hierarchical && ! $child_of && '' === $parent ) { if ( $offset ) { $limits = 'LIMIT ' . $offset . ',' . $number; } else { $limits = 'LIMIT ' . $number; } } else { $limits = ''; } if ( ! empty( $args['search'] ) ) { $this->sql_clauses['where']['search'] = $this->get_search_sql( $args['search'] ); } // Meta query support. $join = ''; $distinct = ''; // Reparse meta_query query_vars, in case they were modified in a 'pre_get_terms' callback. $this->meta_query->parse_query_vars( $this->query_vars ); $mq_sql = $this->meta_query->get_sql( 'term', 't', 'term_id' ); $meta_clauses = $this->meta_query->get_clauses(); if ( ! empty( $meta_clauses ) ) { $join .= $mq_sql['join']; // Strip leading 'AND'. $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $mq_sql['where'] ); $distinct .= 'DISTINCT'; } $selects = array(); switch ( $args['fields'] ) { case 'count': $orderby = ''; $order = ''; $selects = array( 'COUNT(*)' ); break; default: $selects = array( 't.term_id' ); if ( 'all_with_object_id' === $args['fields'] && ! empty( $args['object_ids'] ) ) { $selects[] = 'tr.object_id'; } break; } $_fields = $args['fields']; /** * Filters the fields to select in the terms query. * * Field lists modified using this filter will only modify the term fields returned * by the function when the `$fields` parameter set to 'count' or 'all'. In all other * cases, the term fields in the results array will be determined by the `$fields` * parameter alone. * * Use of this filter can result in unpredictable behavior, and is not recommended. * * @since 2.8.0 * * @param string[] $selects An array of fields to select for the terms query. * @param array $args An array of term query arguments. * @param string[] $taxonomies An array of taxonomy names. */ $fields = implode( ', ', apply_filters( 'get_terms_fields', $selects, $args, $taxonomies ) ); $join .= " INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id"; if ( ! empty( $this->query_vars['object_ids'] ) ) { $join .= " INNER JOIN {$wpdb->term_relationships} AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id"; $distinct = 'DISTINCT'; } $where = implode( ' AND ', $this->sql_clauses['where'] ); $pieces = array( 'fields', 'join', 'where', 'distinct', 'orderby', 'order', 'limits' ); /** * Filters the terms query SQL clauses. * * @since 3.1.0 * * @param string[] $clauses { * Associative array of the clauses for the query. * * @type string $fields The SELECT clause of the query. * @type string $join The JOIN clause of the query. * @type string $where The WHERE clause of the query. * @type string $distinct The DISTINCT clause of the query. * @type string $orderby The ORDER BY clause of the query. * @type string $order The ORDER clause of the query. * @type string $limits The LIMIT clause of the query. * } * @param string[] $taxonomies An array of taxonomy names. * @param array $args An array of term query arguments. */ $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args ); $fields = isset( $clauses['fields'] ) ? $clauses['fields'] : ''; $join = isset( $clauses['join'] ) ? $clauses['join'] : ''; $where = isset( $clauses['where'] ) ? $clauses['where'] : ''; $distinct = isset( $clauses['distinct'] ) ? $clauses['distinct'] : ''; $orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : ''; $order = isset( $clauses['order'] ) ? $clauses['order'] : ''; $limits = isset( $clauses['limits'] ) ? $clauses['limits'] : ''; if ( $where ) { $where = "WHERE $where"; } $this->sql_clauses['select'] = "SELECT $distinct $fields"; $this->sql_clauses['from'] = "FROM $wpdb->terms AS t $join"; $this->sql_clauses['orderby'] = $orderby ? "$orderby $order" : ''; $this->sql_clauses['limits'] = $limits; $this->request = " {$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']} "; $this->terms = null; /** * Filters the terms array before the query takes place. * * Return a non-null value to bypass WordPress' default term queries. * * @since 5.3.0 * * @param array|null $terms Return an array of term data to short-circuit WP's term query, * or null to allow WP queries to run normally. * @param WP_Term_Query $query The WP_Term_Query instance, passed by reference. */ $this->terms = apply_filters_ref_array( 'terms_pre_query', array( $this->terms, &$this ) ); if ( null !== $this->terms ) { return $this->terms; } // $args can be anything. Only use the args defined in defaults to compute the key. $cache_args = wp_array_slice_assoc( $args, array_keys( $this->query_var_defaults ) ); unset( $cache_args['update_term_meta_cache'] ); if ( 'count' !== $_fields && 'all_with_object_id' !== $_fields ) { $cache_args['fields'] = 'all'; } $key = md5( serialize( $cache_args ) . serialize( $taxonomies ) . $this->request ); $last_changed = wp_cache_get_last_changed( 'terms' ); $cache_key = "get_terms:$key:$last_changed"; $cache = wp_cache_get( $cache_key, 'terms' ); if ( false !== $cache ) { if ( 'ids' === $_fields ) { $cache = array_map( 'intval', $cache ); } elseif ( 'count' !== $_fields ) { if ( ( 'all_with_object_id' === $_fields && ! empty( $args['object_ids'] ) ) || ( 'all' === $_fields && $args['pad_counts'] ) ) { $term_ids = wp_list_pluck( $cache, 'term_id' ); } else { $term_ids = array_map( 'intval', $cache ); } _prime_term_caches( $term_ids, $args['update_term_meta_cache'] ); $term_objects = $this->populate_terms( $cache ); $cache = $this->format_terms( $term_objects, $_fields ); } $this->terms = $cache; return $this->terms; } if ( 'count' === $_fields ) { $count = $wpdb->get_var( $this->request ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared wp_cache_set( $cache_key, $count, 'terms' ); return $count; } $terms = $wpdb->get_results( $this->request ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared if ( empty( $terms ) ) { wp_cache_add( $cache_key, array(), 'terms' ); return array(); } $term_ids = wp_list_pluck( $terms, 'term_id' ); _prime_term_caches( $term_ids, false ); $term_objects = $this->populate_terms( $terms ); if ( $child_of ) { foreach ( $taxonomies as $_tax ) { $children = _get_term_hierarchy( $_tax ); if ( ! empty( $children ) ) { $term_objects = _get_term_children( $child_of, $term_objects, $_tax ); } } } // Update term counts to include children. if ( $args['pad_counts'] && 'all' === $_fields ) { foreach ( $taxonomies as $_tax ) { _pad_term_counts( $term_objects, $_tax ); } } // Make sure we show empty categories that have children. if ( $hierarchical && $args['hide_empty'] && is_array( $term_objects ) ) { foreach ( $term_objects as $k => $term ) { if ( ! $term->count ) { $children = get_term_children( $term->term_id, $term->taxonomy ); if ( is_array( $children ) ) { foreach ( $children as $child_id ) { $child = get_term( $child_id, $term->taxonomy ); if ( $child->count ) { continue 2; } } } // It really is empty. unset( $term_objects[ $k ] ); } } } // Hierarchical queries are not limited, so 'offset' and 'number' must be handled now. if ( $hierarchical && $number && is_array( $term_objects ) ) { if ( $offset >= count( $term_objects ) ) { $term_objects = array(); } else { $term_objects = array_slice( $term_objects, $offset, $number, true ); } } // Prime termmeta cache. if ( $args['update_term_meta_cache'] ) { $term_ids = wp_list_pluck( $term_objects, 'term_id' ); update_termmeta_cache( $term_ids ); } if ( 'all_with_object_id' === $_fields && ! empty( $args['object_ids'] ) ) { $term_cache = array(); foreach ( $term_objects as $term ) { $object = new stdClass(); $object->term_id = $term->term_id; $object->object_id = $term->object_id; $term_cache[] = $object; } } elseif ( 'all' === $_fields && $args['pad_counts'] ) { $term_cache = array(); foreach ( $term_objects as $term ) { $object = new stdClass(); $object->term_id = $term->term_id; $object->count = $term->count; $term_cache[] = $object; } } else { $term_cache = wp_list_pluck( $term_objects, 'term_id' ); } wp_cache_add( $cache_key, $term_cache, 'terms' ); $this->terms = $this->format_terms( $term_objects, $_fields ); return $this->terms; } /** * Parse and sanitize 'orderby' keys passed to the term query. * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $orderby_raw Alias for the field to order by. * @return string|false Value to used in the ORDER clause. False otherwise. */ protected function parse_orderby( $orderby_raw ) { $_orderby = strtolower( $orderby_raw ); $maybe_orderby_meta = false; if ( in_array( $_orderby, array( 'term_id', 'name', 'slug', 'term_group' ), true ) ) { $orderby = "t.$_orderby"; } elseif ( in_array( $_orderby, array( 'count', 'parent', 'taxonomy', 'term_taxonomy_id', 'description' ), true ) ) { $orderby = "tt.$_orderby"; } elseif ( 'term_order' === $_orderby ) { $orderby = 'tr.term_order'; } elseif ( 'include' === $_orderby && ! empty( $this->query_vars['include'] ) ) { $include = implode( ',', wp_parse_id_list( $this->query_vars['include'] ) ); $orderby = "FIELD( t.term_id, $include )"; } elseif ( 'slug__in' === $_orderby && ! empty( $this->query_vars['slug'] ) && is_array( $this->query_vars['slug'] ) ) { $slugs = implode( "', '", array_map( 'sanitize_title_for_query', $this->query_vars['slug'] ) ); $orderby = "FIELD( t.slug, '" . $slugs . "')"; } elseif ( 'none' === $_orderby ) { $orderby = ''; } elseif ( empty( $_orderby ) || 'id' === $_orderby || 'term_id' === $_orderby ) { $orderby = 't.term_id'; } else { $orderby = 't.name'; // This may be a value of orderby related to meta. $maybe_orderby_meta = true; } /** * Filters the ORDERBY clause of the terms query. * * @since 2.8.0 * * @param string $orderby `ORDERBY` clause of the terms query. * @param array $args An array of term query arguments. * @param string[] $taxonomies An array of taxonomy names. */ $orderby = apply_filters( 'get_terms_orderby', $orderby, $this->query_vars, $this->query_vars['taxonomy'] ); // Run after the 'get_terms_orderby' filter for backward compatibility. if ( $maybe_orderby_meta ) { $maybe_orderby_meta = $this->parse_orderby_meta( $_orderby ); if ( $maybe_orderby_meta ) { $orderby = $maybe_orderby_meta; } } return $orderby; } /** * Format response depending on field requested. * * @since 6.0.0 * * @param WP_Term[] $term_objects Array of term objects. * @param string $_fields Field to format. * * @return WP_Term[]|int[]|string[] Array of terms / strings / ints depending on field requested. */ protected function format_terms( $term_objects, $_fields ) { $_terms = array(); if ( 'id=>parent' === $_fields ) { foreach ( $term_objects as $term ) { $_terms[ $term->term_id ] = $term->parent; } } elseif ( 'ids' === $_fields ) { foreach ( $term_objects as $term ) { $_terms[] = (int) $term->term_id; } } elseif ( 'tt_ids' === $_fields ) { foreach ( $term_objects as $term ) { $_terms[] = (int) $term->term_taxonomy_id; } } elseif ( 'names' === $_fields ) { foreach ( $term_objects as $term ) { $_terms[] = $term->name; } } elseif ( 'slugs' === $_fields ) { foreach ( $term_objects as $term ) { $_terms[] = $term->slug; } } elseif ( 'id=>name' === $_fields ) { foreach ( $term_objects as $term ) { $_terms[ $term->term_id ] = $term->name; } } elseif ( 'id=>slug' === $_fields ) { foreach ( $term_objects as $term ) { $_terms[ $term->term_id ] = $term->slug; } } elseif ( 'all' === $_fields || 'all_with_object_id' === $_fields ) { $_terms = $term_objects; } return $_terms; } /** * Generate the ORDER BY clause for an 'orderby' param that is potentially related to a meta query. * * @since 4.6.0 * * @param string $orderby_raw Raw 'orderby' value passed to WP_Term_Query. * @return string ORDER BY clause. */ protected function parse_orderby_meta( $orderby_raw ) { $orderby = ''; // Tell the meta query to generate its SQL, so we have access to table aliases. $this->meta_query->get_sql( 'term', 't', 'term_id' ); $meta_clauses = $this->meta_query->get_clauses(); if ( ! $meta_clauses || ! $orderby_raw ) { return $orderby; } $allowed_keys = array(); $primary_meta_key = null; $primary_meta_query = reset( $meta_clauses ); if ( ! empty( $primary_meta_query['key'] ) ) { $primary_meta_key = $primary_meta_query['key']; $allowed_keys[] = $primary_meta_key; } $allowed_keys[] = 'meta_value'; $allowed_keys[] = 'meta_value_num'; $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_clauses ) ); if ( ! in_array( $orderby_raw, $allowed_keys, true ) ) { return $orderby; } switch ( $orderby_raw ) { case $primary_meta_key: case 'meta_value': if ( ! empty( $primary_meta_query['type'] ) ) { $orderby = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})"; } else { $orderby = "{$primary_meta_query['alias']}.meta_value"; } break; case 'meta_value_num': $orderby = "{$primary_meta_query['alias']}.meta_value+0"; break; default: if ( array_key_exists( $orderby_raw, $meta_clauses ) ) { // $orderby corresponds to a meta_query clause. $meta_clause = $meta_clauses[ $orderby_raw ]; $orderby = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})"; } break; } return $orderby; } /** * Parse an 'order' query variable and cast it to ASC or DESC as necessary. * * @since 4.6.0 * * @param string $order The 'order' query variable. * @return string The sanitized 'order' query variable. */ protected function parse_order( $order ) { if ( ! is_string( $order ) || empty( $order ) ) { return 'DESC'; } if ( 'ASC' === strtoupper( $order ) ) { return 'ASC'; } else { return 'DESC'; } } /** * Used internally to generate a SQL string related to the 'search' parameter. * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $search Search string. * @return string Search SQL. */ protected function get_search_sql( $search ) { global $wpdb; $like = '%' . $wpdb->esc_like( $search ) . '%'; return $wpdb->prepare( '((t.name LIKE %s) OR (t.slug LIKE %s))', $like, $like ); } /** * Creates an array of term objects from an array of term IDs. * * Also discards invalid term objects. * * @since 4.9.8 * * @param Object[]|int[] $terms List of objects or term ids. * @return WP_Term[] Array of `WP_Term` objects. */ protected function populate_terms( $terms ) { $term_objects = array(); if ( ! is_array( $terms ) ) { return $term_objects; } foreach ( $terms as $key => $term_data ) { if ( is_object( $term_data ) && property_exists( $term_data, 'term_id' ) ) { $term = get_term( $term_data->term_id ); if ( property_exists( $term_data, 'object_id' ) ) { $term->object_id = (int) $term_data->object_id; } if ( property_exists( $term_data, 'count' ) ) { $term->count = (int) $term_data->count; } } else { $term = get_term( $term_data ); } if ( $term instanceof WP_Term ) { $term_objects[ $key ] = $term; } } return $term_objects; } } ``` | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
programming_docs
wordpress class WP_Customize_Manager {} class WP\_Customize\_Manager {} =============================== Customize Manager class. Bootstraps the Customize experience on the server-side. Sets up the theme-switching process if a theme other than the active one is being previewed and customized. Serves as a factory for Customize Controls and Settings, and instantiates default Customize Controls and Settings. This is the class that controls most of the [Theme Customization API](https://developer.wordpress.org/themes/customize-api/) for WordPress 3.4 and newer. The $wp\_customize object is an instance of the [WP\_Customize\_Manager](wp_customize_manager) class, and is primarily how this class is utilized. For more information, see the documentation for the [Theme Customization API](https://developer.wordpress.org/themes/customize-api/). * [\_\_construct](wp_customize_manager/__construct) β€” Constructor. * [\_cmp\_priority](wp_customize_manager/_cmp_priority) β€” Helper function to compare two objects by priority, ensuring sort stability via instance\_number. β€” deprecated * [\_filter\_revision\_post\_has\_changed](wp_customize_manager/_filter_revision_post_has_changed) β€” Filters whether a changeset has changed to create a new revision. * [\_publish\_changeset\_values](wp_customize_manager/_publish_changeset_values) β€” Publishes the values of a changeset. * [\_render\_custom\_logo\_partial](wp_customize_manager/_render_custom_logo_partial) β€” Callback for rendering the custom logo, used in the custom\_logo partial. * [\_sanitize\_background\_setting](wp_customize_manager/_sanitize_background_setting) β€” Callback for validating a background setting value. * [\_sanitize\_external\_header\_video](wp_customize_manager/_sanitize_external_header_video) β€” Callback for sanitizing the external\_header\_video value. * [\_sanitize\_header\_textcolor](wp_customize_manager/_sanitize_header_textcolor) β€” Callback for validating the header\_textcolor value. * [\_save\_starter\_content\_changeset](wp_customize_manager/_save_starter_content_changeset) β€” Saves starter content changeset. * [\_validate\_external\_header\_video](wp_customize_manager/_validate_external_header_video) β€” Callback for validating the external\_header\_video value. * [\_validate\_header\_video](wp_customize_manager/_validate_header_video) β€” Callback for validating the header\_video value. * [add\_control](wp_customize_manager/add_control) β€” Adds a customize control. * [add\_customize\_screen\_to\_heartbeat\_settings](wp_customize_manager/add_customize_screen_to_heartbeat_settings) β€” Filters heartbeat settings for the Customizer. * [add\_dynamic\_settings](wp_customize_manager/add_dynamic_settings) β€” Registers any dynamically-created settings, such as those from $\_POST['customized'] that have no corresponding setting created. * [add\_panel](wp_customize_manager/add_panel) β€” Adds a customize panel. * [add\_section](wp_customize_manager/add_section) β€” Adds a customize section. * [add\_setting](wp_customize_manager/add_setting) β€” Adds a customize setting. * [add\_state\_query\_params](wp_customize_manager/add_state_query_params) β€” Adds customize state query params to a given URL if preview is allowed. * [after\_setup\_theme](wp_customize_manager/after_setup_theme) β€” Callback to validate a theme once it is loaded * [autosaved](wp_customize_manager/autosaved) β€” Gets whether data from a changeset's autosaved revision should be loaded if it exists. * [branching](wp_customize_manager/branching) β€” Whether the changeset branching is allowed. * [changeset\_data](wp_customize_manager/changeset_data) β€” Gets changeset data. * [changeset\_post\_id](wp_customize_manager/changeset_post_id) β€” Gets the changeset post ID for the loaded changeset. * [changeset\_uuid](wp_customize_manager/changeset_uuid) β€” Gets the changeset UUID. * [check\_changeset\_lock\_with\_heartbeat](wp_customize_manager/check_changeset_lock_with_heartbeat) β€” Checks locked changeset with heartbeat API. * [containers](wp_customize_manager/containers) β€” Gets the registered containers. * [controls](wp_customize_manager/controls) β€” Gets the registered controls. * [current\_theme](wp_customize_manager/current_theme) β€” Filters the active theme and return the name of the previewed theme. * [customize\_pane\_settings](wp_customize_manager/customize_pane_settings) β€” Prints JavaScript settings for parent window. * [customize\_preview\_base](wp_customize_manager/customize_preview_base) β€” Prints base element for preview frame. β€” deprecated * [customize\_preview\_html5](wp_customize_manager/customize_preview_html5) β€” Prints a workaround to handle HTML5 tags in IE < 9. β€” deprecated * [customize\_preview\_init](wp_customize_manager/customize_preview_init) β€” Prints JavaScript settings. * [customize\_preview\_loading\_style](wp_customize_manager/customize_preview_loading_style) β€” Prints CSS for loading indicators for the Customizer preview. * [customize\_preview\_override\_404\_status](wp_customize_manager/customize_preview_override_404_status) β€” Prevents sending a 404 status when returning the response for the customize preview, since it causes the jQuery Ajax to fail. Send 200 instead. β€” deprecated * [customize\_preview\_settings](wp_customize_manager/customize_preview_settings) β€” Prints JavaScript settings for preview frame. * [customize\_preview\_signature](wp_customize_manager/customize_preview_signature) β€” Prints a signature so we can ensure the Customizer was properly executed. β€” deprecated * [dismiss\_user\_auto\_draft\_changesets](wp_customize_manager/dismiss_user_auto_draft_changesets) β€” Dismisses all of the current user's auto-drafts (other than the present one). * [doing\_ajax](wp_customize_manager/doing_ajax) β€” Returns true if it's an Ajax request. * [enqueue\_control\_scripts](wp_customize_manager/enqueue_control_scripts) β€” Enqueues scripts for customize controls. * [establish\_loaded\_changeset](wp_customize_manager/establish_loaded_changeset) β€” Establishes the loaded changeset. * [export\_header\_video\_settings](wp_customize_manager/export_header_video_settings) β€” Exports header video settings to facilitate selective refresh. * [filter\_iframe\_security\_headers](wp_customize_manager/filter_iframe_security_headers) β€” Filters the X-Frame-Options and Content-Security-Policy headers to ensure frontend can load in customizer. * [find\_changeset\_post\_id](wp_customize_manager/find_changeset_post_id) β€” Finds the changeset post ID for a given changeset UUID. * [get\_allowed\_urls](wp_customize_manager/get_allowed_urls) β€” Gets URLs allowed to be previewed. * [get\_autofocus](wp_customize_manager/get_autofocus) β€” Gets the autofocused constructs. * [get\_changeset\_post\_data](wp_customize_manager/get_changeset_post_data) β€” Gets the data stored in a changeset post. * [get\_changeset\_posts](wp_customize_manager/get_changeset_posts) β€” Gets changeset posts. * [get\_control](wp_customize_manager/get_control) β€” Retrieves a customize control. * [get\_document\_title\_template](wp_customize_manager/get_document_title_template) β€” Gets the template string for the Customizer pane document title. * [get\_lock\_user\_data](wp_customize_manager/get_lock_user_data) β€” Gets lock user data. * [get\_messenger\_channel](wp_customize_manager/get_messenger_channel) β€” Gets messenger channel. * [get\_nonces](wp_customize_manager/get_nonces) β€” Gets nonces for the Customizer. * [get\_panel](wp_customize_manager/get_panel) β€” Retrieves a customize panel. * [get\_preview\_url](wp_customize_manager/get_preview_url) β€” Gets the initial URL to be previewed. * [get\_previewable\_devices](wp_customize_manager/get_previewable_devices) β€” Returns a list of devices to allow previewing. * [get\_return\_url](wp_customize_manager/get_return_url) β€” Gets URL to link the user to when closing the Customizer. * [get\_section](wp_customize_manager/get_section) β€” Retrieves a customize section. * [get\_setting](wp_customize_manager/get_setting) β€” Retrieves a customize setting. * [get\_stylesheet](wp_customize_manager/get_stylesheet) β€” Retrieves the stylesheet name of the previewed theme. * [get\_stylesheet\_root](wp_customize_manager/get_stylesheet_root) β€” Retrieves the stylesheet root of the previewed theme. * [get\_template](wp_customize_manager/get_template) β€” Retrieves the template name of the previewed theme. * [get\_template\_root](wp_customize_manager/get_template_root) β€” Retrieves the template root of the previewed theme. * [grant\_edit\_post\_capability\_for\_changeset](wp_customize_manager/grant_edit_post_capability_for_changeset) β€” Re-maps 'edit\_post' meta cap for a customize\_changeset post to be the same as 'customize' maps. * [handle\_changeset\_trash\_request](wp_customize_manager/handle_changeset_trash_request) β€” Handles request to trash a changeset. * [handle\_dismiss\_autosave\_or\_lock\_request](wp_customize_manager/handle_dismiss_autosave_or_lock_request) β€” Deletes a given auto-draft changeset or the autosave revision for a given changeset or delete changeset lock. * [handle\_load\_themes\_request](wp_customize_manager/handle_load_themes_request) β€” Loads themes into the theme browsing/installation UI. * [handle\_override\_changeset\_lock\_request](wp_customize_manager/handle_override_changeset_lock_request) β€” Removes changeset lock when take over request is sent via Ajax. * [has\_published\_pages](wp_customize_manager/has_published_pages) β€” Returns whether there are published pages. * [import\_theme\_starter\_content](wp_customize_manager/import_theme_starter_content) β€” Imports theme starter content into the customized state. * [is\_cross\_domain](wp_customize_manager/is_cross_domain) β€” Determines whether the admin and the frontend are on different domains. * [is\_ios](wp_customize_manager/is_ios) β€” Determines whether the user agent is iOS. * [is\_preview](wp_customize_manager/is_preview) β€” Determines whether it is a theme preview or not. * [is\_theme\_active](wp_customize_manager/is_theme_active) β€” Checks if the current theme is active. * [panels](wp_customize_manager/panels) β€” Gets the registered panels. * [post\_value](wp_customize_manager/post_value) β€” Returns the sanitized value for a given setting from the current customized state. * [prepare\_controls](wp_customize_manager/prepare_controls) β€” Prepares panels, sections, and controls. * [prepare\_setting\_validity\_for\_js](wp_customize_manager/prepare_setting_validity_for_js) β€” Prepares setting validity for exporting to the client (JS). * [prepare\_starter\_content\_attachments](wp_customize_manager/prepare_starter_content_attachments) β€” Prepares starter content attachments. * [preserve\_insert\_changeset\_post\_content](wp_customize_manager/preserve_insert_changeset_post_content) β€” Preserves the initial JSON post\_content passed to save into the post. * [refresh\_changeset\_lock](wp_customize_manager/refresh_changeset_lock) β€” Refreshes changeset lock with the current time if current user edited the changeset before. * [refresh\_nonces](wp_customize_manager/refresh_nonces) β€” Refreshes nonces for the current preview. * [register\_control\_type](wp_customize_manager/register_control_type) β€” Registers a customize control type. * [register\_controls](wp_customize_manager/register_controls) β€” Registers some default controls. * [register\_dynamic\_settings](wp_customize_manager/register_dynamic_settings) β€” Adds settings from the POST data that were not added with code, e.g. dynamically-created settings for Widgets * [register\_panel\_type](wp_customize_manager/register_panel_type) β€” Registers a customize panel type. * [register\_section\_type](wp_customize_manager/register_section_type) β€” Registers a customize section type. * [remove\_control](wp_customize_manager/remove_control) β€” Removes a customize control. * [remove\_frameless\_preview\_messenger\_channel](wp_customize_manager/remove_frameless_preview_messenger_channel) β€” Removes customize\_messenger\_channel query parameter from the preview window when it is not in an iframe. * [remove\_panel](wp_customize_manager/remove_panel) β€” Removes a customize panel. * [remove\_preview\_signature](wp_customize_manager/remove_preview_signature) β€” Removes the signature in case we experience a case where the Customizer was not properly executed. β€” deprecated * [remove\_section](wp_customize_manager/remove_section) β€” Removes a customize section. * [remove\_setting](wp_customize_manager/remove_setting) β€” Removes a customize setting. * [render\_control\_templates](wp_customize_manager/render_control_templates) β€” Renders JS templates for all registered control types. * [render\_panel\_templates](wp_customize_manager/render_panel_templates) β€” Renders JS templates for all registered panel types. * [render\_section\_templates](wp_customize_manager/render_section_templates) β€” Renders JS templates for all registered section types. * [save](wp_customize_manager/save) β€” Handles customize\_save WP Ajax request to save/update a changeset. * [save\_changeset\_post](wp_customize_manager/save_changeset_post) β€” Saves the post for the loaded changeset. * [sections](wp_customize_manager/sections) β€” Gets the registered sections. * [set\_autofocus](wp_customize_manager/set_autofocus) β€” Sets the autofocused constructs. * [set\_changeset\_lock](wp_customize_manager/set_changeset_lock) β€” Marks the changeset post as being currently edited by the current user. * [set\_post\_value](wp_customize_manager/set_post_value) β€” Overrides a setting's value in the current customized state. * [set\_preview\_url](wp_customize_manager/set_preview_url) β€” Sets the initial URL to be previewed. * [set\_return\_url](wp_customize_manager/set_return_url) β€” Sets URL to link the user to when closing the Customizer. * [settings](wp_customize_manager/settings) β€” Gets the registered settings. * [settings\_previewed](wp_customize_manager/settings_previewed) β€” Gets whether settings are or will be previewed. * [setup\_theme](wp_customize_manager/setup_theme) β€” Starts preview and customize theme. * [start\_previewing\_theme](wp_customize_manager/start_previewing_theme) β€” If the theme to be previewed isn't the active theme, add filter callbacks to swap it out at runtime. * [stop\_previewing\_theme](wp_customize_manager/stop_previewing_theme) β€” Stops previewing the selected theme. * [theme](wp_customize_manager/theme) β€” Gets the theme being customized. * [trash\_changeset\_post](wp_customize_manager/trash_changeset_post) β€” Trashes or deletes a changeset post. * [unsanitized\_post\_values](wp_customize_manager/unsanitized_post_values) β€” Gets dirty pre-sanitized setting values in the current customized state. * [update\_stashed\_theme\_mod\_settings](wp_customize_manager/update_stashed_theme_mod_settings) β€” Updates stashed theme mod settings. * [validate\_setting\_values](wp_customize_manager/validate_setting_values) β€” Validates setting values. * [wp\_die](wp_customize_manager/wp_die) β€” Custom wp\_die wrapper. Returns either the standard message for UI or the Ajax message. * [wp\_die\_handler](wp_customize_manager/wp_die_handler) β€” Returns the Ajax wp\_die() handler if it's a customized request. β€” deprecated * [wp\_loaded](wp_customize_manager/wp_loaded) β€” Registers styles/scripts and initialize the preview of each setting * [wp\_redirect\_status](wp_customize_manager/wp_redirect_status) β€” Prevents Ajax requests from following redirects when previewing a theme by issuing a 200 response instead of a 30x. β€” deprecated File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/) ``` final class WP_Customize_Manager { /** * An instance of the theme being previewed. * * @since 3.4.0 * @var WP_Theme */ protected $theme; /** * The directory name of the previously active theme (within the theme_root). * * @since 3.4.0 * @var string */ protected $original_stylesheet; /** * Whether this is a Customizer pageload. * * @since 3.4.0 * @var bool */ protected $previewing = false; /** * Methods and properties dealing with managing widgets in the Customizer. * * @since 3.9.0 * @var WP_Customize_Widgets */ public $widgets; /** * Methods and properties dealing with managing nav menus in the Customizer. * * @since 4.3.0 * @var WP_Customize_Nav_Menus */ public $nav_menus; /** * Methods and properties dealing with selective refresh in the Customizer preview. * * @since 4.5.0 * @var WP_Customize_Selective_Refresh */ public $selective_refresh; /** * Registered instances of WP_Customize_Setting. * * @since 3.4.0 * @var array */ protected $settings = array(); /** * Sorted top-level instances of WP_Customize_Panel and WP_Customize_Section. * * @since 4.0.0 * @var array */ protected $containers = array(); /** * Registered instances of WP_Customize_Panel. * * @since 4.0.0 * @var array */ protected $panels = array(); /** * List of core components. * * @since 4.5.0 * @var array */ protected $components = array( 'widgets', 'nav_menus' ); /** * Registered instances of WP_Customize_Section. * * @since 3.4.0 * @var array */ protected $sections = array(); /** * Registered instances of WP_Customize_Control. * * @since 3.4.0 * @var array */ protected $controls = array(); /** * Panel types that may be rendered from JS templates. * * @since 4.3.0 * @var array */ protected $registered_panel_types = array(); /** * Section types that may be rendered from JS templates. * * @since 4.3.0 * @var array */ protected $registered_section_types = array(); /** * Control types that may be rendered from JS templates. * * @since 4.1.0 * @var array */ protected $registered_control_types = array(); /** * Initial URL being previewed. * * @since 4.4.0 * @var string */ protected $preview_url; /** * URL to link the user to when closing the Customizer. * * @since 4.4.0 * @var string */ protected $return_url; /** * Mapping of 'panel', 'section', 'control' to the ID which should be autofocused. * * @since 4.4.0 * @var string[] */ protected $autofocus = array(); /** * Messenger channel. * * @since 4.7.0 * @var string */ protected $messenger_channel; /** * Whether the autosave revision of the changeset should be loaded. * * @since 4.9.0 * @var bool */ protected $autosaved = false; /** * Whether the changeset branching is allowed. * * @since 4.9.0 * @var bool */ protected $branching = true; /** * Whether settings should be previewed. * * @since 4.9.0 * @var bool */ protected $settings_previewed = true; /** * Whether a starter content changeset was saved. * * @since 4.9.0 * @var bool */ protected $saved_starter_content_changeset = false; /** * Unsanitized values for Customize Settings parsed from $_POST['customized']. * * @var array */ private $_post_values; /** * Changeset UUID. * * @since 4.7.0 * @var string */ private $_changeset_uuid; /** * Changeset post ID. * * @since 4.7.0 * @var int|false */ private $_changeset_post_id; /** * Changeset data loaded from a customize_changeset post. * * @since 4.7.0 * @var array|null */ private $_changeset_data; /** * Constructor. * * @since 3.4.0 * @since 4.7.0 Added `$args` parameter. * * @param array $args { * Args. * * @type null|string|false $changeset_uuid Changeset UUID, the `post_name` for the customize_changeset post containing the customized state. * Defaults to `null` resulting in a UUID to be immediately generated. If `false` is provided, then * then the changeset UUID will be determined during `after_setup_theme`: when the * `customize_changeset_branching` filter returns false, then the default UUID will be that * of the most recent `customize_changeset` post that has a status other than 'auto-draft', * 'publish', or 'trash'. Otherwise, if changeset branching is enabled, then a random UUID will be used. * @type string $theme Theme to be previewed (for theme switch). Defaults to customize_theme or theme query params. * @type string $messenger_channel Messenger channel. Defaults to customize_messenger_channel query param. * @type bool $settings_previewed If settings should be previewed. Defaults to true. * @type bool $branching If changeset branching is allowed; otherwise, changesets are linear. Defaults to true. * @type bool $autosaved If data from a changeset's autosaved revision should be loaded if it exists. Defaults to false. * } */ public function __construct( $args = array() ) { $args = array_merge( array_fill_keys( array( 'changeset_uuid', 'theme', 'messenger_channel', 'settings_previewed', 'autosaved', 'branching' ), null ), $args ); // Note that the UUID format will be validated in the setup_theme() method. if ( ! isset( $args['changeset_uuid'] ) ) { $args['changeset_uuid'] = wp_generate_uuid4(); } // The theme and messenger_channel should be supplied via $args, // but they are also looked at in the $_REQUEST global here for back-compat. if ( ! isset( $args['theme'] ) ) { if ( isset( $_REQUEST['customize_theme'] ) ) { $args['theme'] = wp_unslash( $_REQUEST['customize_theme'] ); } elseif ( isset( $_REQUEST['theme'] ) ) { // Deprecated. $args['theme'] = wp_unslash( $_REQUEST['theme'] ); } } if ( ! isset( $args['messenger_channel'] ) && isset( $_REQUEST['customize_messenger_channel'] ) ) { $args['messenger_channel'] = sanitize_key( wp_unslash( $_REQUEST['customize_messenger_channel'] ) ); } $this->original_stylesheet = get_stylesheet(); $this->theme = wp_get_theme( 0 === validate_file( $args['theme'] ) ? $args['theme'] : null ); $this->messenger_channel = $args['messenger_channel']; $this->_changeset_uuid = $args['changeset_uuid']; foreach ( array( 'settings_previewed', 'autosaved', 'branching' ) as $key ) { if ( isset( $args[ $key ] ) ) { $this->$key = (bool) $args[ $key ]; } } require_once ABSPATH . WPINC . '/class-wp-customize-setting.php'; require_once ABSPATH . WPINC . '/class-wp-customize-panel.php'; require_once ABSPATH . WPINC . '/class-wp-customize-section.php'; require_once ABSPATH . WPINC . '/class-wp-customize-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-color-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-media-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-upload-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-image-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-background-image-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-background-position-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-cropped-image-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-site-icon-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-header-image-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-theme-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-code-editor-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-widget-area-customize-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-widget-form-customize-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-item-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-location-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-name-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-locations-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-auto-add-control.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menus-panel.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-themes-panel.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-themes-section.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-sidebar-section.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-section.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-custom-css-setting.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-filter-setting.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-header-image-setting.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-background-image-setting.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-item-setting.php'; require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-setting.php'; /** * Filters the core Customizer components to load. * * This allows Core components to be excluded from being instantiated by * filtering them out of the array. Note that this filter generally runs * during the {@see 'plugins_loaded'} action, so it cannot be added * in a theme. * * @since 4.4.0 * * @see WP_Customize_Manager::__construct() * * @param string[] $components Array of core components to load. * @param WP_Customize_Manager $manager WP_Customize_Manager instance. */ $components = apply_filters( 'customize_loaded_components', $this->components, $this ); require_once ABSPATH . WPINC . '/customize/class-wp-customize-selective-refresh.php'; $this->selective_refresh = new WP_Customize_Selective_Refresh( $this ); if ( in_array( 'widgets', $components, true ) ) { require_once ABSPATH . WPINC . '/class-wp-customize-widgets.php'; $this->widgets = new WP_Customize_Widgets( $this ); } if ( in_array( 'nav_menus', $components, true ) ) { require_once ABSPATH . WPINC . '/class-wp-customize-nav-menus.php'; $this->nav_menus = new WP_Customize_Nav_Menus( $this ); } add_action( 'setup_theme', array( $this, 'setup_theme' ) ); add_action( 'wp_loaded', array( $this, 'wp_loaded' ) ); // Do not spawn cron (especially the alternate cron) while running the Customizer. remove_action( 'init', 'wp_cron' ); // Do not run update checks when rendering the controls. remove_action( 'admin_init', '_maybe_update_core' ); remove_action( 'admin_init', '_maybe_update_plugins' ); remove_action( 'admin_init', '_maybe_update_themes' ); add_action( 'wp_ajax_customize_save', array( $this, 'save' ) ); add_action( 'wp_ajax_customize_trash', array( $this, 'handle_changeset_trash_request' ) ); add_action( 'wp_ajax_customize_refresh_nonces', array( $this, 'refresh_nonces' ) ); add_action( 'wp_ajax_customize_load_themes', array( $this, 'handle_load_themes_request' ) ); add_filter( 'heartbeat_settings', array( $this, 'add_customize_screen_to_heartbeat_settings' ) ); add_filter( 'heartbeat_received', array( $this, 'check_changeset_lock_with_heartbeat' ), 10, 3 ); add_action( 'wp_ajax_customize_override_changeset_lock', array( $this, 'handle_override_changeset_lock_request' ) ); add_action( 'wp_ajax_customize_dismiss_autosave_or_lock', array( $this, 'handle_dismiss_autosave_or_lock_request' ) ); add_action( 'customize_register', array( $this, 'register_controls' ) ); add_action( 'customize_register', array( $this, 'register_dynamic_settings' ), 11 ); // Allow code to create settings first. add_action( 'customize_controls_init', array( $this, 'prepare_controls' ) ); add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_control_scripts' ) ); // Render Common, Panel, Section, and Control templates. add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_panel_templates' ), 1 ); add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_section_templates' ), 1 ); add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_control_templates' ), 1 ); // Export header video settings with the partial response. add_filter( 'customize_render_partials_response', array( $this, 'export_header_video_settings' ), 10, 3 ); // Export the settings to JS via the _wpCustomizeSettings variable. add_action( 'customize_controls_print_footer_scripts', array( $this, 'customize_pane_settings' ), 1000 ); // Add theme update notices. if ( current_user_can( 'install_themes' ) || current_user_can( 'update_themes' ) ) { require_once ABSPATH . 'wp-admin/includes/update.php'; add_action( 'customize_controls_print_footer_scripts', 'wp_print_admin_notice_templates' ); } } /** * Returns true if it's an Ajax request. * * @since 3.4.0 * @since 4.2.0 Added `$action` param. * * @param string|null $action Whether the supplied Ajax action is being run. * @return bool True if it's an Ajax request, false otherwise. */ public function doing_ajax( $action = null ) { if ( ! wp_doing_ajax() ) { return false; } if ( ! $action ) { return true; } else { /* * Note: we can't just use doing_action( "wp_ajax_{$action}" ) because we need * to check before admin-ajax.php gets to that point. */ return isset( $_REQUEST['action'] ) && wp_unslash( $_REQUEST['action'] ) === $action; } } /** * Custom wp_die wrapper. Returns either the standard message for UI * or the Ajax message. * * @since 3.4.0 * * @param string|WP_Error $ajax_message Ajax return. * @param string $message Optional. UI message. */ protected function wp_die( $ajax_message, $message = null ) { if ( $this->doing_ajax() ) { wp_die( $ajax_message ); } if ( ! $message ) { $message = __( 'Something went wrong.' ); } if ( $this->messenger_channel ) { ob_start(); wp_enqueue_scripts(); wp_print_scripts( array( 'customize-base' ) ); $settings = array( 'messengerArgs' => array( 'channel' => $this->messenger_channel, 'url' => wp_customize_url(), ), 'error' => $ajax_message, ); ?> <script> ( function( api, settings ) { var preview = new api.Messenger( settings.messengerArgs ); preview.send( 'iframe-loading-error', settings.error ); } )( wp.customize, <?php echo wp_json_encode( $settings ); ?> ); </script> <?php $message .= ob_get_clean(); } wp_die( $message ); } /** * Returns the Ajax wp_die() handler if it's a customized request. * * @since 3.4.0 * @deprecated 4.7.0 * * @return callable Die handler. */ public function wp_die_handler() { _deprecated_function( __METHOD__, '4.7.0' ); if ( $this->doing_ajax() || isset( $_POST['customized'] ) ) { return '_ajax_wp_die_handler'; } return '_default_wp_die_handler'; } /** * Starts preview and customize theme. * * Check if customize query variable exist. Init filters to filter the active theme. * * @since 3.4.0 * * @global string $pagenow The filename of the current screen. */ public function setup_theme() { global $pagenow; // Check permissions for customize.php access since this method is called before customize.php can run any code. if ( 'customize.php' === $pagenow && ! current_user_can( 'customize' ) ) { if ( ! is_user_logged_in() ) { auth_redirect(); } else { wp_die( '<h1>' . __( 'You need a higher level of permission.' ) . '</h1>' . '<p>' . __( 'Sorry, you are not allowed to customize this site.' ) . '</p>', 403 ); } return; } // If a changeset was provided is invalid. if ( isset( $this->_changeset_uuid ) && false !== $this->_changeset_uuid && ! wp_is_uuid( $this->_changeset_uuid ) ) { $this->wp_die( -1, __( 'Invalid changeset UUID' ) ); } /* * Clear incoming post data if the user lacks a CSRF token (nonce). Note that the customizer * application will inject the customize_preview_nonce query parameter into all Ajax requests. * For similar behavior elsewhere in WordPress, see rest_cookie_check_errors() which logs out * a user when a valid nonce isn't present. */ $has_post_data_nonce = ( check_ajax_referer( 'preview-customize_' . $this->get_stylesheet(), 'nonce', false ) || check_ajax_referer( 'save-customize_' . $this->get_stylesheet(), 'nonce', false ) || check_ajax_referer( 'preview-customize_' . $this->get_stylesheet(), 'customize_preview_nonce', false ) ); if ( ! current_user_can( 'customize' ) || ! $has_post_data_nonce ) { unset( $_POST['customized'] ); unset( $_REQUEST['customized'] ); } /* * If unauthenticated then require a valid changeset UUID to load the preview. * In this way, the UUID serves as a secret key. If the messenger channel is present, * then send unauthenticated code to prompt re-auth. */ if ( ! current_user_can( 'customize' ) && ! $this->changeset_post_id() ) { $this->wp_die( $this->messenger_channel ? 0 : -1, __( 'Non-existent changeset UUID.' ) ); } if ( ! headers_sent() ) { send_origin_headers(); } // Hide the admin bar if we're embedded in the customizer iframe. if ( $this->messenger_channel ) { show_admin_bar( false ); } if ( $this->is_theme_active() ) { // Once the theme is loaded, we'll validate it. add_action( 'after_setup_theme', array( $this, 'after_setup_theme' ) ); } else { // If the requested theme is not the active theme and the user doesn't have // the switch_themes cap, bail. if ( ! current_user_can( 'switch_themes' ) ) { $this->wp_die( -1, __( 'Sorry, you are not allowed to edit theme options on this site.' ) ); } // If the theme has errors while loading, bail. if ( $this->theme()->errors() ) { $this->wp_die( -1, $this->theme()->errors()->get_error_message() ); } // If the theme isn't allowed per multisite settings, bail. if ( ! $this->theme()->is_allowed() ) { $this->wp_die( -1, __( 'The requested theme does not exist.' ) ); } } // Make sure changeset UUID is established immediately after the theme is loaded. add_action( 'after_setup_theme', array( $this, 'establish_loaded_changeset' ), 5 ); /* * Import theme starter content for fresh installations when landing in the customizer. * Import starter content at after_setup_theme:100 so that any * add_theme_support( 'starter-content' ) calls will have been made. */ if ( get_option( 'fresh_site' ) && 'customize.php' === $pagenow ) { add_action( 'after_setup_theme', array( $this, 'import_theme_starter_content' ), 100 ); } $this->start_previewing_theme(); } /** * Establishes the loaded changeset. * * This method runs right at after_setup_theme and applies the 'customize_changeset_branching' filter to determine * whether concurrent changesets are allowed. Then if the Customizer is not initialized with a `changeset_uuid` param, * this method will determine which UUID should be used. If changeset branching is disabled, then the most saved * changeset will be loaded by default. Otherwise, if there are no existing saved changesets or if changeset branching is * enabled, then a new UUID will be generated. * * @since 4.9.0 * * @global string $pagenow The filename of the current screen. */ public function establish_loaded_changeset() { global $pagenow; if ( empty( $this->_changeset_uuid ) ) { $changeset_uuid = null; if ( ! $this->branching() && $this->is_theme_active() ) { $unpublished_changeset_posts = $this->get_changeset_posts( array( 'post_status' => array_diff( get_post_stati(), array( 'auto-draft', 'publish', 'trash', 'inherit', 'private' ) ), 'exclude_restore_dismissed' => false, 'author' => 'any', 'posts_per_page' => 1, 'order' => 'DESC', 'orderby' => 'date', ) ); $unpublished_changeset_post = array_shift( $unpublished_changeset_posts ); if ( ! empty( $unpublished_changeset_post ) && wp_is_uuid( $unpublished_changeset_post->post_name ) ) { $changeset_uuid = $unpublished_changeset_post->post_name; } } // If no changeset UUID has been set yet, then generate a new one. if ( empty( $changeset_uuid ) ) { $changeset_uuid = wp_generate_uuid4(); } $this->_changeset_uuid = $changeset_uuid; } if ( is_admin() && 'customize.php' === $pagenow ) { $this->set_changeset_lock( $this->changeset_post_id() ); } } /** * Callback to validate a theme once it is loaded * * @since 3.4.0 */ public function after_setup_theme() { $doing_ajax_or_is_customized = ( $this->doing_ajax() || isset( $_POST['customized'] ) ); if ( ! $doing_ajax_or_is_customized && ! validate_current_theme() ) { wp_redirect( 'themes.php?broken=true' ); exit; } } /** * If the theme to be previewed isn't the active theme, add filter callbacks * to swap it out at runtime. * * @since 3.4.0 */ public function start_previewing_theme() { // Bail if we're already previewing. if ( $this->is_preview() ) { return; } $this->previewing = true; if ( ! $this->is_theme_active() ) { add_filter( 'template', array( $this, 'get_template' ) ); add_filter( 'stylesheet', array( $this, 'get_stylesheet' ) ); add_filter( 'pre_option_current_theme', array( $this, 'current_theme' ) ); // @link: https://core.trac.wordpress.org/ticket/20027 add_filter( 'pre_option_stylesheet', array( $this, 'get_stylesheet' ) ); add_filter( 'pre_option_template', array( $this, 'get_template' ) ); // Handle custom theme roots. add_filter( 'pre_option_stylesheet_root', array( $this, 'get_stylesheet_root' ) ); add_filter( 'pre_option_template_root', array( $this, 'get_template_root' ) ); } /** * Fires once the Customizer theme preview has started. * * @since 3.4.0 * * @param WP_Customize_Manager $manager WP_Customize_Manager instance. */ do_action( 'start_previewing_theme', $this ); } /** * Stops previewing the selected theme. * * Removes filters to change the active theme. * * @since 3.4.0 */ public function stop_previewing_theme() { if ( ! $this->is_preview() ) { return; } $this->previewing = false; if ( ! $this->is_theme_active() ) { remove_filter( 'template', array( $this, 'get_template' ) ); remove_filter( 'stylesheet', array( $this, 'get_stylesheet' ) ); remove_filter( 'pre_option_current_theme', array( $this, 'current_theme' ) ); // @link: https://core.trac.wordpress.org/ticket/20027 remove_filter( 'pre_option_stylesheet', array( $this, 'get_stylesheet' ) ); remove_filter( 'pre_option_template', array( $this, 'get_template' ) ); // Handle custom theme roots. remove_filter( 'pre_option_stylesheet_root', array( $this, 'get_stylesheet_root' ) ); remove_filter( 'pre_option_template_root', array( $this, 'get_template_root' ) ); } /** * Fires once the Customizer theme preview has stopped. * * @since 3.4.0 * * @param WP_Customize_Manager $manager WP_Customize_Manager instance. */ do_action( 'stop_previewing_theme', $this ); } /** * Gets whether settings are or will be previewed. * * @since 4.9.0 * * @see WP_Customize_Setting::preview() * * @return bool */ public function settings_previewed() { return $this->settings_previewed; } /** * Gets whether data from a changeset's autosaved revision should be loaded if it exists. * * @since 4.9.0 * * @see WP_Customize_Manager::changeset_data() * * @return bool Is using autosaved changeset revision. */ public function autosaved() { return $this->autosaved; } /** * Whether the changeset branching is allowed. * * @since 4.9.0 * * @see WP_Customize_Manager::establish_loaded_changeset() * * @return bool Is changeset branching. */ public function branching() { /** * Filters whether or not changeset branching isΒ allowed. * * By default in core, when changeset branching is not allowed, changesets will operate * linearly in that only one saved changeset will exist at a time (with a 'draft' or * 'future' status). This makes the Customizer operate in a way that is similar to going to * "edit" to one existing post: all users will be making changes to the same post, and autosave * revisions will be made for that post. * * By contrast, when changeset branching is allowed, then the model is like users going * to "add new" for a page and each user makes changes independently of each other since * they are all operating on their own separate pages, each getting their own separate * initial auto-drafts and then once initially saved, autosave revisions on top of that * user's specific post. * * Since linear changesets are deemed to be more suitable for the majority of WordPress users, * they are the default. For WordPress sites that have heavy site management in the Customizer * by multiple users then branching changesets should be enabled by means of this filter. * * @since 4.9.0 * * @param bool $allow_branching Whether branching is allowed. If `false`, the default, * then only one saved changeset exists at a time. * @param WP_Customize_Manager $wp_customize Manager instance. */ $this->branching = apply_filters( 'customize_changeset_branching', $this->branching, $this ); return $this->branching; } /** * Gets the changeset UUID. * * @since 4.7.0 * * @see WP_Customize_Manager::establish_loaded_changeset() * * @return string UUID. */ public function changeset_uuid() { if ( empty( $this->_changeset_uuid ) ) { $this->establish_loaded_changeset(); } return $this->_changeset_uuid; } /** * Gets the theme being customized. * * @since 3.4.0 * * @return WP_Theme */ public function theme() { if ( ! $this->theme ) { $this->theme = wp_get_theme(); } return $this->theme; } /** * Gets the registered settings. * * @since 3.4.0 * * @return array */ public function settings() { return $this->settings; } /** * Gets the registered controls. * * @since 3.4.0 * * @return array */ public function controls() { return $this->controls; } /** * Gets the registered containers. * * @since 4.0.0 * * @return array */ public function containers() { return $this->containers; } /** * Gets the registered sections. * * @since 3.4.0 * * @return array */ public function sections() { return $this->sections; } /** * Gets the registered panels. * * @since 4.0.0 * * @return array Panels. */ public function panels() { return $this->panels; } /** * Checks if the current theme is active. * * @since 3.4.0 * * @return bool */ public function is_theme_active() { return $this->get_stylesheet() === $this->original_stylesheet; } /** * Registers styles/scripts and initialize the preview of each setting * * @since 3.4.0 */ public function wp_loaded() { // Unconditionally register core types for panels, sections, and controls // in case plugin unhooks all customize_register actions. $this->register_panel_type( 'WP_Customize_Panel' ); $this->register_panel_type( 'WP_Customize_Themes_Panel' ); $this->register_section_type( 'WP_Customize_Section' ); $this->register_section_type( 'WP_Customize_Sidebar_Section' ); $this->register_section_type( 'WP_Customize_Themes_Section' ); $this->register_control_type( 'WP_Customize_Color_Control' ); $this->register_control_type( 'WP_Customize_Media_Control' ); $this->register_control_type( 'WP_Customize_Upload_Control' ); $this->register_control_type( 'WP_Customize_Image_Control' ); $this->register_control_type( 'WP_Customize_Background_Image_Control' ); $this->register_control_type( 'WP_Customize_Background_Position_Control' ); $this->register_control_type( 'WP_Customize_Cropped_Image_Control' ); $this->register_control_type( 'WP_Customize_Site_Icon_Control' ); $this->register_control_type( 'WP_Customize_Theme_Control' ); $this->register_control_type( 'WP_Customize_Code_Editor_Control' ); $this->register_control_type( 'WP_Customize_Date_Time_Control' ); /** * Fires once WordPress has loaded, allowing scripts and styles to be initialized. * * @since 3.4.0 * * @param WP_Customize_Manager $manager WP_Customize_Manager instance. */ do_action( 'customize_register', $this ); if ( $this->settings_previewed() ) { foreach ( $this->settings as $setting ) { $setting->preview(); } } if ( $this->is_preview() && ! is_admin() ) { $this->customize_preview_init(); } } /** * Prevents Ajax requests from following redirects when previewing a theme * by issuing a 200 response instead of a 30x. * * Instead, the JS will sniff out the location header. * * @since 3.4.0 * @deprecated 4.7.0 * * @param int $status Status. * @return int */ public function wp_redirect_status( $status ) { _deprecated_function( __FUNCTION__, '4.7.0' ); if ( $this->is_preview() && ! is_admin() ) { return 200; } return $status; } /** * Finds the changeset post ID for a given changeset UUID. * * @since 4.7.0 * * @param string $uuid Changeset UUID. * @return int|null Returns post ID on success and null on failure. */ public function find_changeset_post_id( $uuid ) { $cache_group = 'customize_changeset_post'; $changeset_post_id = wp_cache_get( $uuid, $cache_group ); if ( $changeset_post_id && 'customize_changeset' === get_post_type( $changeset_post_id ) ) { return $changeset_post_id; } $changeset_post_query = new WP_Query( array( 'post_type' => 'customize_changeset', 'post_status' => get_post_stati(), 'name' => $uuid, 'posts_per_page' => 1, 'no_found_rows' => true, 'cache_results' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, 'lazy_load_term_meta' => false, ) ); if ( ! empty( $changeset_post_query->posts ) ) { // Note: 'fields'=>'ids' is not being used in order to cache the post object as it will be needed. $changeset_post_id = $changeset_post_query->posts[0]->ID; wp_cache_set( $uuid, $changeset_post_id, $cache_group ); return $changeset_post_id; } return null; } /** * Gets changeset posts. * * @since 4.9.0 * * @param array $args { * Args to pass into `get_posts()` to query changesets. * * @type int $posts_per_page Number of posts to return. Defaults to -1 (all posts). * @type int $author Post author. Defaults to current user. * @type string $post_status Status of changeset. Defaults to 'auto-draft'. * @type bool $exclude_restore_dismissed Whether to exclude changeset auto-drafts that have been dismissed. Defaults to true. * } * @return WP_Post[] Auto-draft changesets. */ protected function get_changeset_posts( $args = array() ) { $default_args = array( 'exclude_restore_dismissed' => true, 'posts_per_page' => -1, 'post_type' => 'customize_changeset', 'post_status' => 'auto-draft', 'order' => 'DESC', 'orderby' => 'date', 'no_found_rows' => true, 'cache_results' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, 'lazy_load_term_meta' => false, ); if ( get_current_user_id() ) { $default_args['author'] = get_current_user_id(); } $args = array_merge( $default_args, $args ); if ( ! empty( $args['exclude_restore_dismissed'] ) ) { unset( $args['exclude_restore_dismissed'] ); $args['meta_query'] = array( array( 'key' => '_customize_restore_dismissed', 'compare' => 'NOT EXISTS', ), ); } return get_posts( $args ); } /** * Dismisses all of the current user's auto-drafts (other than the present one). * * @since 4.9.0 * @return int The number of auto-drafts that were dismissed. */ protected function dismiss_user_auto_draft_changesets() { $changeset_autodraft_posts = $this->get_changeset_posts( array( 'post_status' => 'auto-draft', 'exclude_restore_dismissed' => true, 'posts_per_page' => -1, ) ); $dismissed = 0; foreach ( $changeset_autodraft_posts as $autosave_autodraft_post ) { if ( $autosave_autodraft_post->ID === $this->changeset_post_id() ) { continue; } if ( update_post_meta( $autosave_autodraft_post->ID, '_customize_restore_dismissed', true ) ) { $dismissed++; } } return $dismissed; } /** * Gets the changeset post ID for the loaded changeset. * * @since 4.7.0 * * @return int|null Post ID on success or null if there is no post yet saved. */ public function changeset_post_id() { if ( ! isset( $this->_changeset_post_id ) ) { $post_id = $this->find_changeset_post_id( $this->changeset_uuid() ); if ( ! $post_id ) { $post_id = false; } $this->_changeset_post_id = $post_id; } if ( false === $this->_changeset_post_id ) { return null; } return $this->_changeset_post_id; } /** * Gets the data stored in a changeset post. * * @since 4.7.0 * * @param int $post_id Changeset post ID. * @return array|WP_Error Changeset data or WP_Error on error. */ protected function get_changeset_post_data( $post_id ) { if ( ! $post_id ) { return new WP_Error( 'empty_post_id' ); } $changeset_post = get_post( $post_id ); if ( ! $changeset_post ) { return new WP_Error( 'missing_post' ); } if ( 'revision' === $changeset_post->post_type ) { if ( 'customize_changeset' !== get_post_type( $changeset_post->post_parent ) ) { return new WP_Error( 'wrong_post_type' ); } } elseif ( 'customize_changeset' !== $changeset_post->post_type ) { return new WP_Error( 'wrong_post_type' ); } $changeset_data = json_decode( $changeset_post->post_content, true ); $last_error = json_last_error(); if ( $last_error ) { return new WP_Error( 'json_parse_error', '', $last_error ); } if ( ! is_array( $changeset_data ) ) { return new WP_Error( 'expected_array' ); } return $changeset_data; } /** * Gets changeset data. * * @since 4.7.0 * @since 4.9.0 This will return the changeset's data with a user's autosave revision merged on top, if one exists and $autosaved is true. * * @return array Changeset data. */ public function changeset_data() { if ( isset( $this->_changeset_data ) ) { return $this->_changeset_data; } $changeset_post_id = $this->changeset_post_id(); if ( ! $changeset_post_id ) { $this->_changeset_data = array(); } else { if ( $this->autosaved() && is_user_logged_in() ) { $autosave_post = wp_get_post_autosave( $changeset_post_id, get_current_user_id() ); if ( $autosave_post ) { $data = $this->get_changeset_post_data( $autosave_post->ID ); if ( ! is_wp_error( $data ) ) { $this->_changeset_data = $data; } } } // Load data from the changeset if it was not loaded from an autosave. if ( ! isset( $this->_changeset_data ) ) { $data = $this->get_changeset_post_data( $changeset_post_id ); if ( ! is_wp_error( $data ) ) { $this->_changeset_data = $data; } else { $this->_changeset_data = array(); } } } return $this->_changeset_data; } /** * Starter content setting IDs. * * @since 4.7.0 * @var array */ protected $pending_starter_content_settings_ids = array(); /** * Imports theme starter content into the customized state. * * @since 4.7.0 * * @param array $starter_content Starter content. Defaults to `get_theme_starter_content()`. */ public function import_theme_starter_content( $starter_content = array() ) { if ( empty( $starter_content ) ) { $starter_content = get_theme_starter_content(); } $changeset_data = array(); if ( $this->changeset_post_id() ) { /* * Don't re-import starter content into a changeset saved persistently. * This will need to be revisited in the future once theme switching * is allowed with drafted/scheduled changesets, since switching to * another theme could result in more starter content being applied. * However, when doing an explicit save it is currently possible for * nav menus and nav menu items specifically to lose their starter_content * flags, thus resulting in duplicates being created since they fail * to get re-used. See #40146. */ if ( 'auto-draft' !== get_post_status( $this->changeset_post_id() ) ) { return; } $changeset_data = $this->get_changeset_post_data( $this->changeset_post_id() ); } $sidebars_widgets = isset( $starter_content['widgets'] ) && ! empty( $this->widgets ) ? $starter_content['widgets'] : array(); $attachments = isset( $starter_content['attachments'] ) && ! empty( $this->nav_menus ) ? $starter_content['attachments'] : array(); $posts = isset( $starter_content['posts'] ) && ! empty( $this->nav_menus ) ? $starter_content['posts'] : array(); $options = isset( $starter_content['options'] ) ? $starter_content['options'] : array(); $nav_menus = isset( $starter_content['nav_menus'] ) && ! empty( $this->nav_menus ) ? $starter_content['nav_menus'] : array(); $theme_mods = isset( $starter_content['theme_mods'] ) ? $starter_content['theme_mods'] : array(); // Widgets. $max_widget_numbers = array(); foreach ( $sidebars_widgets as $sidebar_id => $widgets ) { $sidebar_widget_ids = array(); foreach ( $widgets as $widget ) { list( $id_base, $instance ) = $widget; if ( ! isset( $max_widget_numbers[ $id_base ] ) ) { // When $settings is an array-like object, get an intrinsic array for use with array_keys(). $settings = get_option( "widget_{$id_base}", array() ); if ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) { $settings = $settings->getArrayCopy(); } unset( $settings['_multiwidget'] ); // Find the max widget number for this type. $widget_numbers = array_keys( $settings ); if ( count( $widget_numbers ) > 0 ) { $widget_numbers[] = 1; $max_widget_numbers[ $id_base ] = max( ...$widget_numbers ); } else { $max_widget_numbers[ $id_base ] = 1; } } $max_widget_numbers[ $id_base ] += 1; $widget_id = sprintf( '%s-%d', $id_base, $max_widget_numbers[ $id_base ] ); $setting_id = sprintf( 'widget_%s[%d]', $id_base, $max_widget_numbers[ $id_base ] ); $setting_value = $this->widgets->sanitize_widget_js_instance( $instance ); if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) { $this->set_post_value( $setting_id, $setting_value ); $this->pending_starter_content_settings_ids[] = $setting_id; } $sidebar_widget_ids[] = $widget_id; } $setting_id = sprintf( 'sidebars_widgets[%s]', $sidebar_id ); if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) { $this->set_post_value( $setting_id, $sidebar_widget_ids ); $this->pending_starter_content_settings_ids[] = $setting_id; } } $starter_content_auto_draft_post_ids = array(); if ( ! empty( $changeset_data['nav_menus_created_posts']['value'] ) ) { $starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, $changeset_data['nav_menus_created_posts']['value'] ); } // Make an index of all the posts needed and what their slugs are. $needed_posts = array(); $attachments = $this->prepare_starter_content_attachments( $attachments ); foreach ( $attachments as $attachment ) { $key = 'attachment:' . $attachment['post_name']; $needed_posts[ $key ] = true; } foreach ( array_keys( $posts ) as $post_symbol ) { if ( empty( $posts[ $post_symbol ]['post_name'] ) && empty( $posts[ $post_symbol ]['post_title'] ) ) { unset( $posts[ $post_symbol ] ); continue; } if ( empty( $posts[ $post_symbol ]['post_name'] ) ) { $posts[ $post_symbol ]['post_name'] = sanitize_title( $posts[ $post_symbol ]['post_title'] ); } if ( empty( $posts[ $post_symbol ]['post_type'] ) ) { $posts[ $post_symbol ]['post_type'] = 'post'; } $needed_posts[ $posts[ $post_symbol ]['post_type'] . ':' . $posts[ $post_symbol ]['post_name'] ] = true; } $all_post_slugs = array_merge( wp_list_pluck( $attachments, 'post_name' ), wp_list_pluck( $posts, 'post_name' ) ); /* * Obtain all post types referenced in starter content to use in query. * This is needed because 'any' will not account for post types not yet registered. */ $post_types = array_filter( array_merge( array( 'attachment' ), wp_list_pluck( $posts, 'post_type' ) ) ); // Re-use auto-draft starter content posts referenced in the current customized state. $existing_starter_content_posts = array(); if ( ! empty( $starter_content_auto_draft_post_ids ) ) { $existing_posts_query = new WP_Query( array( 'post__in' => $starter_content_auto_draft_post_ids, 'post_status' => 'auto-draft', 'post_type' => $post_types, 'posts_per_page' => -1, ) ); foreach ( $existing_posts_query->posts as $existing_post ) { $post_name = $existing_post->post_name; if ( empty( $post_name ) ) { $post_name = get_post_meta( $existing_post->ID, '_customize_draft_post_name', true ); } $existing_starter_content_posts[ $existing_post->post_type . ':' . $post_name ] = $existing_post; } } // Re-use non-auto-draft posts. if ( ! empty( $all_post_slugs ) ) { $existing_posts_query = new WP_Query( array( 'post_name__in' => $all_post_slugs, 'post_status' => array_diff( get_post_stati(), array( 'auto-draft' ) ), 'post_type' => 'any', 'posts_per_page' => -1, ) ); foreach ( $existing_posts_query->posts as $existing_post ) { $key = $existing_post->post_type . ':' . $existing_post->post_name; if ( isset( $needed_posts[ $key ] ) && ! isset( $existing_starter_content_posts[ $key ] ) ) { $existing_starter_content_posts[ $key ] = $existing_post; } } } // Attachments are technically posts but handled differently. if ( ! empty( $attachments ) ) { $attachment_ids = array(); foreach ( $attachments as $symbol => $attachment ) { $file_array = array( 'name' => $attachment['file_name'], ); $file_path = $attachment['file_path']; $attachment_id = null; $attached_file = null; if ( isset( $existing_starter_content_posts[ 'attachment:' . $attachment['post_name'] ] ) ) { $attachment_post = $existing_starter_content_posts[ 'attachment:' . $attachment['post_name'] ]; $attachment_id = $attachment_post->ID; $attached_file = get_attached_file( $attachment_id ); if ( empty( $attached_file ) || ! file_exists( $attached_file ) ) { $attachment_id = null; $attached_file = null; } elseif ( $this->get_stylesheet() !== get_post_meta( $attachment_post->ID, '_starter_content_theme', true ) ) { // Re-generate attachment metadata since it was previously generated for a different theme. $metadata = wp_generate_attachment_metadata( $attachment_post->ID, $attached_file ); wp_update_attachment_metadata( $attachment_id, $metadata ); update_post_meta( $attachment_id, '_starter_content_theme', $this->get_stylesheet() ); } } // Insert the attachment auto-draft because it doesn't yet exist or the attached file is gone. if ( ! $attachment_id ) { // Copy file to temp location so that original file won't get deleted from theme after sideloading. $temp_file_name = wp_tempnam( wp_basename( $file_path ) ); if ( $temp_file_name && copy( $file_path, $temp_file_name ) ) { $file_array['tmp_name'] = $temp_file_name; } if ( empty( $file_array['tmp_name'] ) ) { continue; } $attachment_post_data = array_merge( wp_array_slice_assoc( $attachment, array( 'post_title', 'post_content', 'post_excerpt' ) ), array( 'post_status' => 'auto-draft', // So attachment will be garbage collected in a week if changeset is never published. ) ); $attachment_id = media_handle_sideload( $file_array, 0, null, $attachment_post_data ); if ( is_wp_error( $attachment_id ) ) { continue; } update_post_meta( $attachment_id, '_starter_content_theme', $this->get_stylesheet() ); update_post_meta( $attachment_id, '_customize_draft_post_name', $attachment['post_name'] ); } $attachment_ids[ $symbol ] = $attachment_id; } $starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, array_values( $attachment_ids ) ); } // Posts & pages. if ( ! empty( $posts ) ) { foreach ( array_keys( $posts ) as $post_symbol ) { if ( empty( $posts[ $post_symbol ]['post_type'] ) || empty( $posts[ $post_symbol ]['post_name'] ) ) { continue; } $post_type = $posts[ $post_symbol ]['post_type']; if ( ! empty( $posts[ $post_symbol ]['post_name'] ) ) { $post_name = $posts[ $post_symbol ]['post_name']; } elseif ( ! empty( $posts[ $post_symbol ]['post_title'] ) ) { $post_name = sanitize_title( $posts[ $post_symbol ]['post_title'] ); } else { continue; } // Use existing auto-draft post if one already exists with the same type and name. if ( isset( $existing_starter_content_posts[ $post_type . ':' . $post_name ] ) ) { $posts[ $post_symbol ]['ID'] = $existing_starter_content_posts[ $post_type . ':' . $post_name ]->ID; continue; } // Translate the featured image symbol. if ( ! empty( $posts[ $post_symbol ]['thumbnail'] ) && preg_match( '/^{{(?P<symbol>.+)}}$/', $posts[ $post_symbol ]['thumbnail'], $matches ) && isset( $attachment_ids[ $matches['symbol'] ] ) ) { $posts[ $post_symbol ]['meta_input']['_thumbnail_id'] = $attachment_ids[ $matches['symbol'] ]; } if ( ! empty( $posts[ $post_symbol ]['template'] ) ) { $posts[ $post_symbol ]['meta_input']['_wp_page_template'] = $posts[ $post_symbol ]['template']; } $r = $this->nav_menus->insert_auto_draft_post( $posts[ $post_symbol ] ); if ( $r instanceof WP_Post ) { $posts[ $post_symbol ]['ID'] = $r->ID; } } $starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, wp_list_pluck( $posts, 'ID' ) ); } // The nav_menus_created_posts setting is why nav_menus component is dependency for adding posts. if ( ! empty( $this->nav_menus ) && ! empty( $starter_content_auto_draft_post_ids ) ) { $setting_id = 'nav_menus_created_posts'; $this->set_post_value( $setting_id, array_unique( array_values( $starter_content_auto_draft_post_ids ) ) ); $this->pending_starter_content_settings_ids[] = $setting_id; } // Nav menus. $placeholder_id = -1; $reused_nav_menu_setting_ids = array(); foreach ( $nav_menus as $nav_menu_location => $nav_menu ) { $nav_menu_term_id = null; $nav_menu_setting_id = null; $matches = array(); // Look for an existing placeholder menu with starter content to re-use. foreach ( $changeset_data as $setting_id => $setting_params ) { $can_reuse = ( ! empty( $setting_params['starter_content'] ) && ! in_array( $setting_id, $reused_nav_menu_setting_ids, true ) && preg_match( '#^nav_menu\[(?P<nav_menu_id>-?\d+)\]$#', $setting_id, $matches ) ); if ( $can_reuse ) { $nav_menu_term_id = (int) $matches['nav_menu_id']; $nav_menu_setting_id = $setting_id; $reused_nav_menu_setting_ids[] = $setting_id; break; } } if ( ! $nav_menu_term_id ) { while ( isset( $changeset_data[ sprintf( 'nav_menu[%d]', $placeholder_id ) ] ) ) { $placeholder_id--; } $nav_menu_term_id = $placeholder_id; $nav_menu_setting_id = sprintf( 'nav_menu[%d]', $placeholder_id ); } $this->set_post_value( $nav_menu_setting_id, array( 'name' => isset( $nav_menu['name'] ) ? $nav_menu['name'] : $nav_menu_location, ) ); $this->pending_starter_content_settings_ids[] = $nav_menu_setting_id; // @todo Add support for menu_item_parent. $position = 0; foreach ( $nav_menu['items'] as $nav_menu_item ) { $nav_menu_item_setting_id = sprintf( 'nav_menu_item[%d]', $placeholder_id-- ); if ( ! isset( $nav_menu_item['position'] ) ) { $nav_menu_item['position'] = $position++; } $nav_menu_item['nav_menu_term_id'] = $nav_menu_term_id; if ( isset( $nav_menu_item['object_id'] ) ) { if ( 'post_type' === $nav_menu_item['type'] && preg_match( '/^{{(?P<symbol>.+)}}$/', $nav_menu_item['object_id'], $matches ) && isset( $posts[ $matches['symbol'] ] ) ) { $nav_menu_item['object_id'] = $posts[ $matches['symbol'] ]['ID']; if ( empty( $nav_menu_item['title'] ) ) { $original_object = get_post( $nav_menu_item['object_id'] ); $nav_menu_item['title'] = $original_object->post_title; } } else { continue; } } else { $nav_menu_item['object_id'] = 0; } if ( empty( $changeset_data[ $nav_menu_item_setting_id ] ) || ! empty( $changeset_data[ $nav_menu_item_setting_id ]['starter_content'] ) ) { $this->set_post_value( $nav_menu_item_setting_id, $nav_menu_item ); $this->pending_starter_content_settings_ids[] = $nav_menu_item_setting_id; } } $setting_id = sprintf( 'nav_menu_locations[%s]', $nav_menu_location ); if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) { $this->set_post_value( $setting_id, $nav_menu_term_id ); $this->pending_starter_content_settings_ids[] = $setting_id; } } // Options. foreach ( $options as $name => $value ) { // Serialize the value to check for post symbols. $value = maybe_serialize( $value ); if ( is_serialized( $value ) ) { if ( preg_match( '/s:\d+:"{{(?P<symbol>.+)}}"/', $value, $matches ) ) { if ( isset( $posts[ $matches['symbol'] ] ) ) { $symbol_match = $posts[ $matches['symbol'] ]['ID']; } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) { $symbol_match = $attachment_ids[ $matches['symbol'] ]; } // If we have any symbol matches, update the values. if ( isset( $symbol_match ) ) { // Replace found string matches with post IDs. $value = str_replace( $matches[0], "i:{$symbol_match}", $value ); } else { continue; } } } elseif ( preg_match( '/^{{(?P<symbol>.+)}}$/', $value, $matches ) ) { if ( isset( $posts[ $matches['symbol'] ] ) ) { $value = $posts[ $matches['symbol'] ]['ID']; } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) { $value = $attachment_ids[ $matches['symbol'] ]; } else { continue; } } // Unserialize values after checking for post symbols, so they can be properly referenced. $value = maybe_unserialize( $value ); if ( empty( $changeset_data[ $name ] ) || ! empty( $changeset_data[ $name ]['starter_content'] ) ) { $this->set_post_value( $name, $value ); $this->pending_starter_content_settings_ids[] = $name; } } // Theme mods. foreach ( $theme_mods as $name => $value ) { // Serialize the value to check for post symbols. $value = maybe_serialize( $value ); // Check if value was serialized. if ( is_serialized( $value ) ) { if ( preg_match( '/s:\d+:"{{(?P<symbol>.+)}}"/', $value, $matches ) ) { if ( isset( $posts[ $matches['symbol'] ] ) ) { $symbol_match = $posts[ $matches['symbol'] ]['ID']; } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) { $symbol_match = $attachment_ids[ $matches['symbol'] ]; } // If we have any symbol matches, update the values. if ( isset( $symbol_match ) ) { // Replace found string matches with post IDs. $value = str_replace( $matches[0], "i:{$symbol_match}", $value ); } else { continue; } } } elseif ( preg_match( '/^{{(?P<symbol>.+)}}$/', $value, $matches ) ) { if ( isset( $posts[ $matches['symbol'] ] ) ) { $value = $posts[ $matches['symbol'] ]['ID']; } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) { $value = $attachment_ids[ $matches['symbol'] ]; } else { continue; } } // Unserialize values after checking for post symbols, so they can be properly referenced. $value = maybe_unserialize( $value ); // Handle header image as special case since setting has a legacy format. if ( 'header_image' === $name ) { $name = 'header_image_data'; $metadata = wp_get_attachment_metadata( $value ); if ( empty( $metadata ) ) { continue; } $value = array( 'attachment_id' => $value, 'url' => wp_get_attachment_url( $value ), 'height' => $metadata['height'], 'width' => $metadata['width'], ); } elseif ( 'background_image' === $name ) { $value = wp_get_attachment_url( $value ); } if ( empty( $changeset_data[ $name ] ) || ! empty( $changeset_data[ $name ]['starter_content'] ) ) { $this->set_post_value( $name, $value ); $this->pending_starter_content_settings_ids[] = $name; } } if ( ! empty( $this->pending_starter_content_settings_ids ) ) { if ( did_action( 'customize_register' ) ) { $this->_save_starter_content_changeset(); } else { add_action( 'customize_register', array( $this, '_save_starter_content_changeset' ), 1000 ); } } } /** * Prepares starter content attachments. * * Ensure that the attachments are valid and that they have slugs and file name/path. * * @since 4.7.0 * * @param array $attachments Attachments. * @return array Prepared attachments. */ protected function prepare_starter_content_attachments( $attachments ) { $prepared_attachments = array(); if ( empty( $attachments ) ) { return $prepared_attachments; } // Such is The WordPress Way. require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; foreach ( $attachments as $symbol => $attachment ) { // A file is required and URLs to files are not currently allowed. if ( empty( $attachment['file'] ) || preg_match( '#^https?://$#', $attachment['file'] ) ) { continue; } $file_path = null; if ( file_exists( $attachment['file'] ) ) { $file_path = $attachment['file']; // Could be absolute path to file in plugin. } elseif ( is_child_theme() && file_exists( get_stylesheet_directory() . '/' . $attachment['file'] ) ) { $file_path = get_stylesheet_directory() . '/' . $attachment['file']; } elseif ( file_exists( get_template_directory() . '/' . $attachment['file'] ) ) { $file_path = get_template_directory() . '/' . $attachment['file']; } else { continue; } $file_name = wp_basename( $attachment['file'] ); // Skip file types that are not recognized. $checked_filetype = wp_check_filetype( $file_name ); if ( empty( $checked_filetype['type'] ) ) { continue; } // Ensure post_name is set since not automatically derived from post_title for new auto-draft posts. if ( empty( $attachment['post_name'] ) ) { if ( ! empty( $attachment['post_title'] ) ) { $attachment['post_name'] = sanitize_title( $attachment['post_title'] ); } else { $attachment['post_name'] = sanitize_title( preg_replace( '/\.\w+$/', '', $file_name ) ); } } $attachment['file_name'] = $file_name; $attachment['file_path'] = $file_path; $prepared_attachments[ $symbol ] = $attachment; } return $prepared_attachments; } /** * Saves starter content changeset. * * @since 4.7.0 */ public function _save_starter_content_changeset() { if ( empty( $this->pending_starter_content_settings_ids ) ) { return; } $this->save_changeset_post( array( 'data' => array_fill_keys( $this->pending_starter_content_settings_ids, array( 'starter_content' => true ) ), 'starter_content' => true, ) ); $this->saved_starter_content_changeset = true; $this->pending_starter_content_settings_ids = array(); } /** * Gets dirty pre-sanitized setting values in the current customized state. * * The returned array consists of a merge of three sources: * 1. If the theme is not currently active, then the base array is any stashed * theme mods that were modified previously but never published. * 2. The values from the current changeset, if it exists. * 3. If the user can customize, the values parsed from the incoming * `$_POST['customized']` JSON data. * 4. Any programmatically-set post values via `WP_Customize_Manager::set_post_value()`. * * The name "unsanitized_post_values" is a carry-over from when the customized * state was exclusively sourced from `$_POST['customized']`. Nevertheless, * the value returned will come from the current changeset post and from the * incoming post data. * * @since 4.1.1 * @since 4.7.0 Added `$args` parameter and merging with changeset values and stashed theme mods. * * @param array $args { * Args. * * @type bool $exclude_changeset Whether the changeset values should also be excluded. Defaults to false. * @type bool $exclude_post_data Whether the post input values should also be excluded. Defaults to false when lacking the customize capability. * } * @return array */ public function unsanitized_post_values( $args = array() ) { $args = array_merge( array( 'exclude_changeset' => false, 'exclude_post_data' => ! current_user_can( 'customize' ), ), $args ); $values = array(); // Let default values be from the stashed theme mods if doing a theme switch and if no changeset is present. if ( ! $this->is_theme_active() ) { $stashed_theme_mods = get_option( 'customize_stashed_theme_mods' ); $stylesheet = $this->get_stylesheet(); if ( isset( $stashed_theme_mods[ $stylesheet ] ) ) { $values = array_merge( $values, wp_list_pluck( $stashed_theme_mods[ $stylesheet ], 'value' ) ); } } if ( ! $args['exclude_changeset'] ) { foreach ( $this->changeset_data() as $setting_id => $setting_params ) { if ( ! array_key_exists( 'value', $setting_params ) ) { continue; } if ( isset( $setting_params['type'] ) && 'theme_mod' === $setting_params['type'] ) { // Ensure that theme mods values are only used if they were saved under the active theme. $namespace_pattern = '/^(?P<stylesheet>.+?)::(?P<setting_id>.+)$/'; if ( preg_match( $namespace_pattern, $setting_id, $matches ) && $this->get_stylesheet() === $matches['stylesheet'] ) { $values[ $matches['setting_id'] ] = $setting_params['value']; } } else { $values[ $setting_id ] = $setting_params['value']; } } } if ( ! $args['exclude_post_data'] ) { if ( ! isset( $this->_post_values ) ) { if ( isset( $_POST['customized'] ) ) { $post_values = json_decode( wp_unslash( $_POST['customized'] ), true ); } else { $post_values = array(); } if ( is_array( $post_values ) ) { $this->_post_values = $post_values; } else { $this->_post_values = array(); } } $values = array_merge( $values, $this->_post_values ); } return $values; } /** * Returns the sanitized value for a given setting from the current customized state. * * The name "post_value" is a carry-over from when the customized state was exclusively * sourced from `$_POST['customized']`. Nevertheless, the value returned will come * from the current changeset post and from the incoming post data. * * @since 3.4.0 * @since 4.1.1 Introduced the `$default_value` parameter. * @since 4.6.0 `$default_value` is now returned early when the setting post value is invalid. * * @see WP_REST_Server::dispatch() * @see WP_REST_Request::sanitize_params() * @see WP_REST_Request::has_valid_params() * * @param WP_Customize_Setting $setting A WP_Customize_Setting derived object. * @param mixed $default_value Value returned if `$setting` has no post value (added in 4.2.0) * or the post value is invalid (added in 4.6.0). * @return string|mixed Sanitized value or the `$default_value` provided. */ public function post_value( $setting, $default_value = null ) { $post_values = $this->unsanitized_post_values(); if ( ! array_key_exists( $setting->id, $post_values ) ) { return $default_value; } $value = $post_values[ $setting->id ]; $valid = $setting->validate( $value ); if ( is_wp_error( $valid ) ) { return $default_value; } $value = $setting->sanitize( $value ); if ( is_null( $value ) || is_wp_error( $value ) ) { return $default_value; } return $value; } /** * Overrides a setting's value in the current customized state. * * The name "post_value" is a carry-over from when the customized state was * exclusively sourced from `$_POST['customized']`. * * @since 4.2.0 * * @param string $setting_id ID for the WP_Customize_Setting instance. * @param mixed $value Post value. */ public function set_post_value( $setting_id, $value ) { $this->unsanitized_post_values(); // Populate _post_values from $_POST['customized']. $this->_post_values[ $setting_id ] = $value; /** * Announces when a specific setting's unsanitized post value has been set. * * Fires when the WP_Customize_Manager::set_post_value() method is called. * * The dynamic portion of the hook name, `$setting_id`, refers to the setting ID. * * @since 4.4.0 * * @param mixed $value Unsanitized setting post value. * @param WP_Customize_Manager $manager WP_Customize_Manager instance. */ do_action( "customize_post_value_set_{$setting_id}", $value, $this ); /** * Announces when any setting's unsanitized post value has been set. * * Fires when the WP_Customize_Manager::set_post_value() method is called. * * This is useful for `WP_Customize_Setting` instances to watch * in order to update a cached previewed value. * * @since 4.4.0 * * @param string $setting_id Setting ID. * @param mixed $value Unsanitized setting post value. * @param WP_Customize_Manager $manager WP_Customize_Manager instance. */ do_action( 'customize_post_value_set', $setting_id, $value, $this ); } /** * Prints JavaScript settings. * * @since 3.4.0 */ public function customize_preview_init() { /* * Now that Customizer previews are loaded into iframes via GET requests * and natural URLs with transaction UUIDs added, we need to ensure that * the responses are never cached by proxies. In practice, this will not * be needed if the user is logged-in anyway. But if anonymous access is * allowed then the auth cookies would not be sent and WordPress would * not send no-cache headers by default. */ if ( ! headers_sent() ) { nocache_headers(); header( 'X-Robots: noindex, nofollow, noarchive' ); } add_filter( 'wp_robots', 'wp_robots_no_robots' ); add_filter( 'wp_headers', array( $this, 'filter_iframe_security_headers' ) ); /* * If preview is being served inside the customizer preview iframe, and * if the user doesn't have customize capability, then it is assumed * that the user's session has expired and they need to re-authenticate. */ if ( $this->messenger_channel && ! current_user_can( 'customize' ) ) { $this->wp_die( -1, sprintf( /* translators: %s: customize_messenger_channel */ __( 'Unauthorized. You may remove the %s param to preview as frontend.' ), '<code>customize_messenger_channel<code>' ) ); return; } $this->prepare_controls(); add_filter( 'wp_redirect', array( $this, 'add_state_query_params' ) ); wp_enqueue_script( 'customize-preview' ); wp_enqueue_style( 'customize-preview' ); add_action( 'wp_head', array( $this, 'customize_preview_loading_style' ) ); add_action( 'wp_head', array( $this, 'remove_frameless_preview_messenger_channel' ) ); add_action( 'wp_footer', array( $this, 'customize_preview_settings' ), 20 ); add_filter( 'get_edit_post_link', '__return_empty_string' ); /** * Fires once the Customizer preview has initialized and JavaScript * settings have been printed. * * @since 3.4.0 * * @param WP_Customize_Manager $manager WP_Customize_Manager instance. */ do_action( 'customize_preview_init', $this ); } /** * Filters the X-Frame-Options and Content-Security-Policy headers to ensure frontend can load in customizer. * * @since 4.7.0 * * @param array $headers Headers. * @return array Headers. */ public function filter_iframe_security_headers( $headers ) { $headers['X-Frame-Options'] = 'SAMEORIGIN'; $headers['Content-Security-Policy'] = "frame-ancestors 'self'"; return $headers; } /** * Adds customize state query params to a given URL if preview is allowed. * * @since 4.7.0 * * @see wp_redirect() * @see WP_Customize_Manager::get_allowed_url() * * @param string $url URL. * @return string URL. */ public function add_state_query_params( $url ) { $parsed_original_url = wp_parse_url( $url ); $is_allowed = false; foreach ( $this->get_allowed_urls() as $allowed_url ) { $parsed_allowed_url = wp_parse_url( $allowed_url ); $is_allowed = ( $parsed_allowed_url['scheme'] === $parsed_original_url['scheme'] && $parsed_allowed_url['host'] === $parsed_original_url['host'] && 0 === strpos( $parsed_original_url['path'], $parsed_allowed_url['path'] ) ); if ( $is_allowed ) { break; } } if ( $is_allowed ) { $query_params = array( 'customize_changeset_uuid' => $this->changeset_uuid(), ); if ( ! $this->is_theme_active() ) { $query_params['customize_theme'] = $this->get_stylesheet(); } if ( $this->messenger_channel ) { $query_params['customize_messenger_channel'] = $this->messenger_channel; } $url = add_query_arg( $query_params, $url ); } return $url; } /** * Prevents sending a 404 status when returning the response for the customize * preview, since it causes the jQuery Ajax to fail. Send 200 instead. * * @since 4.0.0 * @deprecated 4.7.0 */ public function customize_preview_override_404_status() { _deprecated_function( __METHOD__, '4.7.0' ); } /** * Prints base element for preview frame. * * @since 3.4.0 * @deprecated 4.7.0 */ public function customize_preview_base() { _deprecated_function( __METHOD__, '4.7.0' ); } /** * Prints a workaround to handle HTML5 tags in IE < 9. * * @since 3.4.0 * @deprecated 4.7.0 Customizer no longer supports IE8, so all supported browsers recognize HTML5. */ public function customize_preview_html5() { _deprecated_function( __FUNCTION__, '4.7.0' ); } /** * Prints CSS for loading indicators for the Customizer preview. * * @since 4.2.0 */ public function customize_preview_loading_style() { ?> <style> body.wp-customizer-unloading { opacity: 0.25; cursor: progress !important; -webkit-transition: opacity 0.5s; transition: opacity 0.5s; } body.wp-customizer-unloading * { pointer-events: none !important; } form.customize-unpreviewable, form.customize-unpreviewable input, form.customize-unpreviewable select, form.customize-unpreviewable button, a.customize-unpreviewable, area.customize-unpreviewable { cursor: not-allowed !important; } </style> <?php } /** * Removes customize_messenger_channel query parameter from the preview window when it is not in an iframe. * * This ensures that the admin bar will be shown. It also ensures that link navigation will * work as expected since the parent frame is not being sent the URL to navigate to. * * @since 4.7.0 */ public function remove_frameless_preview_messenger_channel() { if ( ! $this->messenger_channel ) { return; } ?> <script> ( function() { var urlParser, oldQueryParams, newQueryParams, i; if ( parent !== window ) { return; } urlParser = document.createElement( 'a' ); urlParser.href = location.href; oldQueryParams = urlParser.search.substr( 1 ).split( /&/ ); newQueryParams = []; for ( i = 0; i < oldQueryParams.length; i += 1 ) { if ( ! /^customize_messenger_channel=/.test( oldQueryParams[ i ] ) ) { newQueryParams.push( oldQueryParams[ i ] ); } } urlParser.search = newQueryParams.join( '&' ); if ( urlParser.search !== location.search ) { location.replace( urlParser.href ); } } )(); </script> <?php } /** * Prints JavaScript settings for preview frame. * * @since 3.4.0 */ public function customize_preview_settings() { $post_values = $this->unsanitized_post_values( array( 'exclude_changeset' => true ) ); $setting_validities = $this->validate_setting_values( $post_values ); $exported_setting_validities = array_map( array( $this, 'prepare_setting_validity_for_js' ), $setting_validities ); // Note that the REQUEST_URI is not passed into home_url() since this breaks subdirectory installations. $self_url = empty( $_SERVER['REQUEST_URI'] ) ? home_url( '/' ) : sanitize_url( wp_unslash( $_SERVER['REQUEST_URI'] ) ); $state_query_params = array( 'customize_theme', 'customize_changeset_uuid', 'customize_messenger_channel', ); $self_url = remove_query_arg( $state_query_params, $self_url ); $allowed_urls = $this->get_allowed_urls(); $allowed_hosts = array(); foreach ( $allowed_urls as $allowed_url ) { $parsed = wp_parse_url( $allowed_url ); if ( empty( $parsed['host'] ) ) { continue; } $host = $parsed['host']; if ( ! empty( $parsed['port'] ) ) { $host .= ':' . $parsed['port']; } $allowed_hosts[] = $host; } $switched_locale = switch_to_locale( get_user_locale() ); $l10n = array( 'shiftClickToEdit' => __( 'Shift-click to edit this element.' ), 'linkUnpreviewable' => __( 'This link is not live-previewable.' ), 'formUnpreviewable' => __( 'This form is not live-previewable.' ), ); if ( $switched_locale ) { restore_previous_locale(); } $settings = array( 'changeset' => array( 'uuid' => $this->changeset_uuid(), 'autosaved' => $this->autosaved(), ), 'timeouts' => array( 'selectiveRefresh' => 250, 'keepAliveSend' => 1000, ), 'theme' => array( 'stylesheet' => $this->get_stylesheet(), 'active' => $this->is_theme_active(), ), 'url' => array( 'self' => $self_url, 'allowed' => array_map( 'sanitize_url', $this->get_allowed_urls() ), 'allowedHosts' => array_unique( $allowed_hosts ), 'isCrossDomain' => $this->is_cross_domain(), ), 'channel' => $this->messenger_channel, 'activePanels' => array(), 'activeSections' => array(), 'activeControls' => array(), 'settingValidities' => $exported_setting_validities, 'nonce' => current_user_can( 'customize' ) ? $this->get_nonces() : array(), 'l10n' => $l10n, '_dirty' => array_keys( $post_values ), ); foreach ( $this->panels as $panel_id => $panel ) { if ( $panel->check_capabilities() ) { $settings['activePanels'][ $panel_id ] = $panel->active(); foreach ( $panel->sections as $section_id => $section ) { if ( $section->check_capabilities() ) { $settings['activeSections'][ $section_id ] = $section->active(); } } } } foreach ( $this->sections as $id => $section ) { if ( $section->check_capabilities() ) { $settings['activeSections'][ $id ] = $section->active(); } } foreach ( $this->controls as $id => $control ) { if ( $control->check_capabilities() ) { $settings['activeControls'][ $id ] = $control->active(); } } ?> <script type="text/javascript"> var _wpCustomizeSettings = <?php echo wp_json_encode( $settings ); ?>; _wpCustomizeSettings.values = {}; (function( v ) { <?php /* * Serialize settings separately from the initial _wpCustomizeSettings * serialization in order to avoid a peak memory usage spike. * @todo We may not even need to export the values at all since the pane syncs them anyway. */ foreach ( $this->settings as $id => $setting ) { if ( $setting->check_capabilities() ) { printf( "v[%s] = %s;\n", wp_json_encode( $id ), wp_json_encode( $setting->js_value() ) ); } } ?> })( _wpCustomizeSettings.values ); </script> <?php } /** * Prints a signature so we can ensure the Customizer was properly executed. * * @since 3.4.0 * @deprecated 4.7.0 */ public function customize_preview_signature() { _deprecated_function( __METHOD__, '4.7.0' ); } /** * Removes the signature in case we experience a case where the Customizer was not properly executed. * * @since 3.4.0 * @deprecated 4.7.0 * * @param callable|null $callback Optional. Value passed through for {@see 'wp_die_handler'} filter. * Default null. * @return callable|null Value passed through for {@see 'wp_die_handler'} filter. */ public function remove_preview_signature( $callback = null ) { _deprecated_function( __METHOD__, '4.7.0' ); return $callback; } /** * Determines whether it is a theme preview or not. * * @since 3.4.0 * * @return bool True if it's a preview, false if not. */ public function is_preview() { return (bool) $this->previewing; } /** * Retrieves the template name of the previewed theme. * * @since 3.4.0 * * @return string Template name. */ public function get_template() { return $this->theme()->get_template(); } /** * Retrieves the stylesheet name of the previewed theme. * * @since 3.4.0 * * @return string Stylesheet name. */ public function get_stylesheet() { return $this->theme()->get_stylesheet(); } /** * Retrieves the template root of the previewed theme. * * @since 3.4.0 * * @return string Theme root. */ public function get_template_root() { return get_raw_theme_root( $this->get_template(), true ); } /** * Retrieves the stylesheet root of the previewed theme. * * @since 3.4.0 * * @return string Theme root. */ public function get_stylesheet_root() { return get_raw_theme_root( $this->get_stylesheet(), true ); } /** * Filters the active theme and return the name of the previewed theme. * * @since 3.4.0 * * @param mixed $current_theme {@internal Parameter is not used} * @return string Theme name. */ public function current_theme( $current_theme ) { return $this->theme()->display( 'Name' ); } /** * Validates setting values. * * Validation is skipped for unregistered settings or for values that are * already null since they will be skipped anyway. Sanitization is applied * to values that pass validation, and values that become null or `WP_Error` * after sanitizing are marked invalid. * * @since 4.6.0 * * @see WP_REST_Request::has_valid_params() * @see WP_Customize_Setting::validate() * * @param array $setting_values Mapping of setting IDs to values to validate and sanitize. * @param array $options { * Options. * * @type bool $validate_existence Whether a setting's existence will be checked. * @type bool $validate_capability Whether the setting capability will be checked. * } * @return array Mapping of setting IDs to return value of validate method calls, either `true` or `WP_Error`. */ public function validate_setting_values( $setting_values, $options = array() ) { $options = wp_parse_args( $options, array( 'validate_capability' => false, 'validate_existence' => false, ) ); $validities = array(); foreach ( $setting_values as $setting_id => $unsanitized_value ) { $setting = $this->get_setting( $setting_id ); if ( ! $setting ) { if ( $options['validate_existence'] ) { $validities[ $setting_id ] = new WP_Error( 'unrecognized', __( 'Setting does not exist or is unrecognized.' ) ); } continue; } if ( $options['validate_capability'] && ! current_user_can( $setting->capability ) ) { $validity = new WP_Error( 'unauthorized', __( 'Unauthorized to modify setting due to capability.' ) ); } else { if ( is_null( $unsanitized_value ) ) { continue; } $validity = $setting->validate( $unsanitized_value ); } if ( ! is_wp_error( $validity ) ) { /** This filter is documented in wp-includes/class-wp-customize-setting.php */ $late_validity = apply_filters( "customize_validate_{$setting->id}", new WP_Error(), $unsanitized_value, $setting ); if ( is_wp_error( $late_validity ) && $late_validity->has_errors() ) { $validity = $late_validity; } } if ( ! is_wp_error( $validity ) ) { $value = $setting->sanitize( $unsanitized_value ); if ( is_null( $value ) ) { $validity = false; } elseif ( is_wp_error( $value ) ) { $validity = $value; } } if ( false === $validity ) { $validity = new WP_Error( 'invalid_value', __( 'Invalid value.' ) ); } $validities[ $setting_id ] = $validity; } return $validities; } /** * Prepares setting validity for exporting to the client (JS). * * Converts `WP_Error` instance into array suitable for passing into the * `wp.customize.Notification` JS model. * * @since 4.6.0 * * @param true|WP_Error $validity Setting validity. * @return true|array If `$validity` was a WP_Error, the error codes will be array-mapped * to their respective `message` and `data` to pass into the * `wp.customize.Notification` JS model. */ public function prepare_setting_validity_for_js( $validity ) { if ( is_wp_error( $validity ) ) { $notification = array(); foreach ( $validity->errors as $error_code => $error_messages ) { $notification[ $error_code ] = array( 'message' => implode( ' ', $error_messages ), 'data' => $validity->get_error_data( $error_code ), ); } return $notification; } else { return true; } } /** * Handles customize_save WP Ajax request to save/update a changeset. * * @since 3.4.0 * @since 4.7.0 The semantics of this method have changed to update a changeset, optionally to also change the status and other attributes. */ public function save() { if ( ! is_user_logged_in() ) { wp_send_json_error( 'unauthenticated' ); } if ( ! $this->is_preview() ) { wp_send_json_error( 'not_preview' ); } $action = 'save-customize_' . $this->get_stylesheet(); if ( ! check_ajax_referer( $action, 'nonce', false ) ) { wp_send_json_error( 'invalid_nonce' ); } $changeset_post_id = $this->changeset_post_id(); $is_new_changeset = empty( $changeset_post_id ); if ( $is_new_changeset ) { if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->create_posts ) ) { wp_send_json_error( 'cannot_create_changeset_post' ); } } else { if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) ) { wp_send_json_error( 'cannot_edit_changeset_post' ); } } if ( ! empty( $_POST['customize_changeset_data'] ) ) { $input_changeset_data = json_decode( wp_unslash( $_POST['customize_changeset_data'] ), true ); if ( ! is_array( $input_changeset_data ) ) { wp_send_json_error( 'invalid_customize_changeset_data' ); } } else { $input_changeset_data = array(); } // Validate title. $changeset_title = null; if ( isset( $_POST['customize_changeset_title'] ) ) { $changeset_title = sanitize_text_field( wp_unslash( $_POST['customize_changeset_title'] ) ); } // Validate changeset status param. $is_publish = null; $changeset_status = null; if ( isset( $_POST['customize_changeset_status'] ) ) { $changeset_status = wp_unslash( $_POST['customize_changeset_status'] ); if ( ! get_post_status_object( $changeset_status ) || ! in_array( $changeset_status, array( 'draft', 'pending', 'publish', 'future' ), true ) ) { wp_send_json_error( 'bad_customize_changeset_status', 400 ); } $is_publish = ( 'publish' === $changeset_status || 'future' === $changeset_status ); if ( $is_publish && ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->publish_posts ) ) { wp_send_json_error( 'changeset_publish_unauthorized', 403 ); } } /* * Validate changeset date param. Date is assumed to be in local time for * the WP if in MySQL format (YYYY-MM-DD HH:MM:SS). Otherwise, the date * is parsed with strtotime() so that ISO date format may be supplied * or a string like "+10 minutes". */ $changeset_date_gmt = null; if ( isset( $_POST['customize_changeset_date'] ) ) { $changeset_date = wp_unslash( $_POST['customize_changeset_date'] ); if ( preg_match( '/^\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d$/', $changeset_date ) ) { $mm = substr( $changeset_date, 5, 2 ); $jj = substr( $changeset_date, 8, 2 ); $aa = substr( $changeset_date, 0, 4 ); $valid_date = wp_checkdate( $mm, $jj, $aa, $changeset_date ); if ( ! $valid_date ) { wp_send_json_error( 'bad_customize_changeset_date', 400 ); } $changeset_date_gmt = get_gmt_from_date( $changeset_date ); } else { $timestamp = strtotime( $changeset_date ); if ( ! $timestamp ) { wp_send_json_error( 'bad_customize_changeset_date', 400 ); } $changeset_date_gmt = gmdate( 'Y-m-d H:i:s', $timestamp ); } } $lock_user_id = null; $autosave = ! empty( $_POST['customize_changeset_autosave'] ); if ( ! $is_new_changeset ) { $lock_user_id = wp_check_post_lock( $this->changeset_post_id() ); } // Force request to autosave when changeset is locked. if ( $lock_user_id && ! $autosave ) { $autosave = true; $changeset_status = null; $changeset_date_gmt = null; } if ( $autosave && ! defined( 'DOING_AUTOSAVE' ) ) { // Back-compat. define( 'DOING_AUTOSAVE', true ); } $autosaved = false; $r = $this->save_changeset_post( array( 'status' => $changeset_status, 'title' => $changeset_title, 'date_gmt' => $changeset_date_gmt, 'data' => $input_changeset_data, 'autosave' => $autosave, ) ); if ( $autosave && ! is_wp_error( $r ) ) { $autosaved = true; } // If the changeset was locked and an autosave request wasn't itself an error, then now explicitly return with a failure. if ( $lock_user_id && ! is_wp_error( $r ) ) { $r = new WP_Error( 'changeset_locked', __( 'Changeset is being edited by other user.' ), array( 'lock_user' => $this->get_lock_user_data( $lock_user_id ), ) ); } if ( is_wp_error( $r ) ) { $response = array( 'message' => $r->get_error_message(), 'code' => $r->get_error_code(), ); if ( is_array( $r->get_error_data() ) ) { $response = array_merge( $response, $r->get_error_data() ); } else { $response['data'] = $r->get_error_data(); } } else { $response = $r; $changeset_post = get_post( $this->changeset_post_id() ); // Dismiss all other auto-draft changeset posts for this user (they serve like autosave revisions), as there should only be one. if ( $is_new_changeset ) { $this->dismiss_user_auto_draft_changesets(); } // Note that if the changeset status was publish, then it will get set to Trash if revisions are not supported. $response['changeset_status'] = $changeset_post->post_status; if ( $is_publish && 'trash' === $response['changeset_status'] ) { $response['changeset_status'] = 'publish'; } if ( 'publish' !== $response['changeset_status'] ) { $this->set_changeset_lock( $changeset_post->ID ); } if ( 'future' === $response['changeset_status'] ) { $response['changeset_date'] = $changeset_post->post_date; } if ( 'publish' === $response['changeset_status'] || 'trash' === $response['changeset_status'] ) { $response['next_changeset_uuid'] = wp_generate_uuid4(); } } if ( $autosave ) { $response['autosaved'] = $autosaved; } if ( isset( $response['setting_validities'] ) ) { $response['setting_validities'] = array_map( array( $this, 'prepare_setting_validity_for_js' ), $response['setting_validities'] ); } /** * Filters response data for a successful customize_save Ajax request. * * This filter does not apply if there was a nonce or authentication failure. * * @since 4.2.0 * * @param array $response Additional information passed back to the 'saved' * event on `wp.customize`. * @param WP_Customize_Manager $manager WP_Customize_Manager instance. */ $response = apply_filters( 'customize_save_response', $response, $this ); if ( is_wp_error( $r ) ) { wp_send_json_error( $response ); } else { wp_send_json_success( $response ); } } /** * Saves the post for the loaded changeset. * * @since 4.7.0 * * @param array $args { * Args for changeset post. * * @type array $data Optional additional changeset data. Values will be merged on top of any existing post values. * @type string $status Post status. Optional. If supplied, the save will be transactional and a post revision will be allowed. * @type string $title Post title. Optional. * @type string $date_gmt Date in GMT. Optional. * @type int $user_id ID for user who is saving the changeset. Optional, defaults to the current user ID. * @type bool $starter_content Whether the data is starter content. If false (default), then $starter_content will be cleared for any $data being saved. * @type bool $autosave Whether this is a request to create an autosave revision. * } * * @return array|WP_Error Returns array on success and WP_Error with array data on error. */ public function save_changeset_post( $args = array() ) { $args = array_merge( array( 'status' => null, 'title' => null, 'data' => array(), 'date_gmt' => null, 'user_id' => get_current_user_id(), 'starter_content' => false, 'autosave' => false, ), $args ); $changeset_post_id = $this->changeset_post_id(); $existing_changeset_data = array(); if ( $changeset_post_id ) { $existing_status = get_post_status( $changeset_post_id ); if ( 'publish' === $existing_status || 'trash' === $existing_status ) { return new WP_Error( 'changeset_already_published', __( 'The previous set of changes has already been published. Please try saving your current set of changes again.' ), array( 'next_changeset_uuid' => wp_generate_uuid4(), ) ); } $existing_changeset_data = $this->get_changeset_post_data( $changeset_post_id ); if ( is_wp_error( $existing_changeset_data ) ) { return $existing_changeset_data; } } // Fail if attempting to publish but publish hook is missing. if ( 'publish' === $args['status'] && false === has_action( 'transition_post_status', '_wp_customize_publish_changeset' ) ) { return new WP_Error( 'missing_publish_callback' ); } // Validate date. $now = gmdate( 'Y-m-d H:i:59' ); if ( $args['date_gmt'] ) { $is_future_dated = ( mysql2date( 'U', $args['date_gmt'], false ) > mysql2date( 'U', $now, false ) ); if ( ! $is_future_dated ) { return new WP_Error( 'not_future_date', __( 'You must supply a future date to schedule.' ) ); // Only future dates are allowed. } if ( ! $this->is_theme_active() && ( 'future' === $args['status'] || $is_future_dated ) ) { return new WP_Error( 'cannot_schedule_theme_switches' ); // This should be allowed in the future, when theme is a regular setting. } $will_remain_auto_draft = ( ! $args['status'] && ( ! $changeset_post_id || 'auto-draft' === get_post_status( $changeset_post_id ) ) ); if ( $will_remain_auto_draft ) { return new WP_Error( 'cannot_supply_date_for_auto_draft_changeset' ); } } elseif ( $changeset_post_id && 'future' === $args['status'] ) { // Fail if the new status is future but the existing post's date is not in the future. $changeset_post = get_post( $changeset_post_id ); if ( mysql2date( 'U', $changeset_post->post_date_gmt, false ) <= mysql2date( 'U', $now, false ) ) { return new WP_Error( 'not_future_date', __( 'You must supply a future date to schedule.' ) ); } } if ( ! empty( $is_future_dated ) && 'publish' === $args['status'] ) { $args['status'] = 'future'; } // Validate autosave param. See _wp_post_revision_fields() for why these fields are disallowed. if ( $args['autosave'] ) { if ( $args['date_gmt'] ) { return new WP_Error( 'illegal_autosave_with_date_gmt' ); } elseif ( $args['status'] ) { return new WP_Error( 'illegal_autosave_with_status' ); } elseif ( $args['user_id'] && get_current_user_id() !== $args['user_id'] ) { return new WP_Error( 'illegal_autosave_with_non_current_user' ); } } // The request was made via wp.customize.previewer.save(). $update_transactionally = (bool) $args['status']; $allow_revision = (bool) $args['status']; // Amend post values with any supplied data. foreach ( $args['data'] as $setting_id => $setting_params ) { if ( is_array( $setting_params ) && array_key_exists( 'value', $setting_params ) ) { $this->set_post_value( $setting_id, $setting_params['value'] ); // Add to post values so that they can be validated and sanitized. } } // Note that in addition to post data, this will include any stashed theme mods. $post_values = $this->unsanitized_post_values( array( 'exclude_changeset' => true, 'exclude_post_data' => false, ) ); $this->add_dynamic_settings( array_keys( $post_values ) ); // Ensure settings get created even if they lack an input value. /* * Get list of IDs for settings that have values different from what is currently * saved in the changeset. By skipping any values that are already the same, the * subset of changed settings can be passed into validate_setting_values to prevent * an underprivileged modifying a single setting for which they have the capability * from being blocked from saving. This also prevents a user from touching of the * previous saved settings and overriding the associated user_id if they made no change. */ $changed_setting_ids = array(); foreach ( $post_values as $setting_id => $setting_value ) { $setting = $this->get_setting( $setting_id ); if ( $setting && 'theme_mod' === $setting->type ) { $prefixed_setting_id = $this->get_stylesheet() . '::' . $setting->id; } else { $prefixed_setting_id = $setting_id; } $is_value_changed = ( ! isset( $existing_changeset_data[ $prefixed_setting_id ] ) || ! array_key_exists( 'value', $existing_changeset_data[ $prefixed_setting_id ] ) || $existing_changeset_data[ $prefixed_setting_id ]['value'] !== $setting_value ); if ( $is_value_changed ) { $changed_setting_ids[] = $setting_id; } } /** * Fires before save validation happens. * * Plugins can add just-in-time {@see 'customize_validate_{$this->ID}'} filters * at this point to catch any settings registered after `customize_register`. * The dynamic portion of the hook name, `$this->ID` refers to the setting ID. * * @since 4.6.0 * * @param WP_Customize_Manager $manager WP_Customize_Manager instance. */ do_action( 'customize_save_validation_before', $this ); // Validate settings. $validated_values = array_merge( array_fill_keys( array_keys( $args['data'] ), null ), // Make sure existence/capability checks are done on value-less setting updates. $post_values ); $setting_validities = $this->validate_setting_values( $validated_values, array( 'validate_capability' => true, 'validate_existence' => true, ) ); $invalid_setting_count = count( array_filter( $setting_validities, 'is_wp_error' ) ); /* * Short-circuit if there are invalid settings the update is transactional. * A changeset update is transactional when a status is supplied in the request. */ if ( $update_transactionally && $invalid_setting_count > 0 ) { $response = array( 'setting_validities' => $setting_validities, /* translators: %s: Number of invalid settings. */ 'message' => sprintf( _n( 'Unable to save due to %s invalid setting.', 'Unable to save due to %s invalid settings.', $invalid_setting_count ), number_format_i18n( $invalid_setting_count ) ), ); return new WP_Error( 'transaction_fail', '', $response ); } // Obtain/merge data for changeset. $original_changeset_data = $this->get_changeset_post_data( $changeset_post_id ); $data = $original_changeset_data; if ( is_wp_error( $data ) ) { $data = array(); } // Ensure that all post values are included in the changeset data. foreach ( $post_values as $setting_id => $post_value ) { if ( ! isset( $args['data'][ $setting_id ] ) ) { $args['data'][ $setting_id ] = array(); } if ( ! isset( $args['data'][ $setting_id ]['value'] ) ) { $args['data'][ $setting_id ]['value'] = $post_value; } } foreach ( $args['data'] as $setting_id => $setting_params ) { $setting = $this->get_setting( $setting_id ); if ( ! $setting || ! $setting->check_capabilities() ) { continue; } // Skip updating changeset for invalid setting values. if ( isset( $setting_validities[ $setting_id ] ) && is_wp_error( $setting_validities[ $setting_id ] ) ) { continue; } $changeset_setting_id = $setting_id; if ( 'theme_mod' === $setting->type ) { $changeset_setting_id = sprintf( '%s::%s', $this->get_stylesheet(), $setting_id ); } if ( null === $setting_params ) { // Remove setting from changeset entirely. unset( $data[ $changeset_setting_id ] ); } else { if ( ! isset( $data[ $changeset_setting_id ] ) ) { $data[ $changeset_setting_id ] = array(); } // Merge any additional setting params that have been supplied with the existing params. $merged_setting_params = array_merge( $data[ $changeset_setting_id ], $setting_params ); // Skip updating setting params if unchanged (ensuring the user_id is not overwritten). if ( $data[ $changeset_setting_id ] === $merged_setting_params ) { continue; } $data[ $changeset_setting_id ] = array_merge( $merged_setting_params, array( 'type' => $setting->type, 'user_id' => $args['user_id'], 'date_modified_gmt' => current_time( 'mysql', true ), ) ); // Clear starter_content flag in data if changeset is not explicitly being updated for starter content. if ( empty( $args['starter_content'] ) ) { unset( $data[ $changeset_setting_id ]['starter_content'] ); } } } $filter_context = array( 'uuid' => $this->changeset_uuid(), 'title' => $args['title'], 'status' => $args['status'], 'date_gmt' => $args['date_gmt'], 'post_id' => $changeset_post_id, 'previous_data' => is_wp_error( $original_changeset_data ) ? array() : $original_changeset_data, 'manager' => $this, ); /** * Filters the settings' data that will be persisted into the changeset. * * Plugins may amend additional data (such as additional meta for settings) into the changeset with this filter. * * @since 4.7.0 * * @param array $data Updated changeset data, mapping setting IDs to arrays containing a $value item and optionally other metadata. * @param array $context { * Filter context. * * @type string $uuid Changeset UUID. * @type string $title Requested title for the changeset post. * @type string $status Requested status for the changeset post. * @type string $date_gmt Requested date for the changeset post in MySQL format and GMT timezone. * @type int|false $post_id Post ID for the changeset, or false if it doesn't exist yet. * @type array $previous_data Previous data contained in the changeset. * @type WP_Customize_Manager $manager Manager instance. * } */ $data = apply_filters( 'customize_changeset_save_data', $data, $filter_context ); // Switch theme if publishing changes now. if ( 'publish' === $args['status'] && ! $this->is_theme_active() ) { // Temporarily stop previewing the theme to allow switch_themes() to operate properly. $this->stop_previewing_theme(); switch_theme( $this->get_stylesheet() ); update_option( 'theme_switched_via_customizer', true ); $this->start_previewing_theme(); } // Gather the data for wp_insert_post()/wp_update_post(). $post_array = array( // JSON_UNESCAPED_SLASHES is only to improve readability as slashes needn't be escaped in storage. 'post_content' => wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT ), ); if ( $args['title'] ) { $post_array['post_title'] = $args['title']; } if ( $changeset_post_id ) { $post_array['ID'] = $changeset_post_id; } else { $post_array['post_type'] = 'customize_changeset'; $post_array['post_name'] = $this->changeset_uuid(); $post_array['post_status'] = 'auto-draft'; } if ( $args['status'] ) { $post_array['post_status'] = $args['status']; } // Reset post date to now if we are publishing, otherwise pass post_date_gmt and translate for post_date. if ( 'publish' === $args['status'] ) { $post_array['post_date_gmt'] = '0000-00-00 00:00:00'; $post_array['post_date'] = '0000-00-00 00:00:00'; } elseif ( $args['date_gmt'] ) { $post_array['post_date_gmt'] = $args['date_gmt']; $post_array['post_date'] = get_date_from_gmt( $args['date_gmt'] ); } elseif ( $changeset_post_id && 'auto-draft' === get_post_status( $changeset_post_id ) ) { /* * Keep bumping the date for the auto-draft whenever it is modified; * this extends its life, preserving it from garbage-collection via * wp_delete_auto_drafts(). */ $post_array['post_date'] = current_time( 'mysql' ); $post_array['post_date_gmt'] = ''; } $this->store_changeset_revision = $allow_revision; add_filter( 'wp_save_post_revision_post_has_changed', array( $this, '_filter_revision_post_has_changed' ), 5, 3 ); /* * Update the changeset post. The publish_customize_changeset action will cause the settings in the * changeset to be saved via WP_Customize_Setting::save(). Updating a post with publish status will * trigger WP_Customize_Manager::publish_changeset_values(). */ add_filter( 'wp_insert_post_data', array( $this, 'preserve_insert_changeset_post_content' ), 5, 3 ); if ( $changeset_post_id ) { if ( $args['autosave'] && 'auto-draft' !== get_post_status( $changeset_post_id ) ) { // See _wp_translate_postdata() for why this is required as it will use the edit_post meta capability. add_filter( 'map_meta_cap', array( $this, 'grant_edit_post_capability_for_changeset' ), 10, 4 ); $post_array['post_ID'] = $post_array['ID']; $post_array['post_type'] = 'customize_changeset'; $r = wp_create_post_autosave( wp_slash( $post_array ) ); remove_filter( 'map_meta_cap', array( $this, 'grant_edit_post_capability_for_changeset' ), 10 ); } else { $post_array['edit_date'] = true; // Prevent date clearing. $r = wp_update_post( wp_slash( $post_array ), true ); // Delete autosave revision for user when the changeset is updated. if ( ! empty( $args['user_id'] ) ) { $autosave_draft = wp_get_post_autosave( $changeset_post_id, $args['user_id'] ); if ( $autosave_draft ) { wp_delete_post( $autosave_draft->ID, true ); } } } } else { $r = wp_insert_post( wp_slash( $post_array ), true ); if ( ! is_wp_error( $r ) ) { $this->_changeset_post_id = $r; // Update cached post ID for the loaded changeset. } } remove_filter( 'wp_insert_post_data', array( $this, 'preserve_insert_changeset_post_content' ), 5 ); $this->_changeset_data = null; // Reset so WP_Customize_Manager::changeset_data() will re-populate with updated contents. remove_filter( 'wp_save_post_revision_post_has_changed', array( $this, '_filter_revision_post_has_changed' ) ); $response = array( 'setting_validities' => $setting_validities, ); if ( is_wp_error( $r ) ) { $response['changeset_post_save_failure'] = $r->get_error_code(); return new WP_Error( 'changeset_post_save_failure', '', $response ); } return $response; } /** * Preserves the initial JSON post_content passed to save into the post. * * This is needed to prevent KSES and other {@see 'content_save_pre'} filters * from corrupting JSON data. * * Note that WP_Customize_Manager::validate_setting_values() have already * run on the setting values being serialized as JSON into the post content * so it is pre-sanitized. * * Also, the sanitization logic is re-run through the respective * WP_Customize_Setting::sanitize() method when being read out of the * changeset, via WP_Customize_Manager::post_value(), and this sanitized * value will also be sent into WP_Customize_Setting::update() for * persisting to the DB. * * Multiple users can collaborate on a single changeset, where one user may * have the unfiltered_html capability but another may not. A user with * unfiltered_html may add a script tag to some field which needs to be kept * intact even when another user updates the changeset to modify another field * when they do not have unfiltered_html. * * @since 5.4.1 * * @param array $data An array of slashed and processed post data. * @param array $postarr An array of sanitized (and slashed) but otherwise unmodified post data. * @param array $unsanitized_postarr An array of slashed yet *unsanitized* and unprocessed post data as originally passed to wp_insert_post(). * @return array Filtered post data. */ public function preserve_insert_changeset_post_content( $data, $postarr, $unsanitized_postarr ) { if ( isset( $data['post_type'] ) && isset( $unsanitized_postarr['post_content'] ) && 'customize_changeset' === $data['post_type'] || ( 'revision' === $data['post_type'] && ! empty( $data['post_parent'] ) && 'customize_changeset' === get_post_type( $data['post_parent'] ) ) ) { $data['post_content'] = $unsanitized_postarr['post_content']; } return $data; } /** * Trashes or deletes a changeset post. * * The following re-formulates the logic from `wp_trash_post()` as done in * `wp_publish_post()`. The reason for bypassing `wp_trash_post()` is that it * will mutate the the `post_content` and the `post_name` when they should be * untouched. * * @since 4.9.0 * * @see wp_trash_post() * @global wpdb $wpdb WordPress database abstraction object. * * @param int|WP_Post $post The changeset post. * @return mixed A WP_Post object for the trashed post or an empty value on failure. */ public function trash_changeset_post( $post ) { global $wpdb; $post = get_post( $post ); if ( ! ( $post instanceof WP_Post ) ) { return $post; } $post_id = $post->ID; if ( ! EMPTY_TRASH_DAYS ) { return wp_delete_post( $post_id, true ); } if ( 'trash' === get_post_status( $post ) ) { return false; } /** This filter is documented in wp-includes/post.php */ $check = apply_filters( 'pre_trash_post', null, $post ); if ( null !== $check ) { return $check; } /** This action is documented in wp-includes/post.php */ do_action( 'wp_trash_post', $post_id ); add_post_meta( $post_id, '_wp_trash_meta_status', $post->post_status ); add_post_meta( $post_id, '_wp_trash_meta_time', time() ); $old_status = $post->post_status; $new_status = 'trash'; $wpdb->update( $wpdb->posts, array( 'post_status' => $new_status ), array( 'ID' => $post->ID ) ); clean_post_cache( $post->ID ); $post->post_status = $new_status; wp_transition_post_status( $new_status, $old_status, $post ); /** This action is documented in wp-includes/post.php */ do_action( "edit_post_{$post->post_type}", $post->ID, $post ); /** This action is documented in wp-includes/post.php */ do_action( 'edit_post', $post->ID, $post ); /** This action is documented in wp-includes/post.php */ do_action( "save_post_{$post->post_type}", $post->ID, $post, true ); /** This action is documented in wp-includes/post.php */ do_action( 'save_post', $post->ID, $post, true ); /** This action is documented in wp-includes/post.php */ do_action( 'wp_insert_post', $post->ID, $post, true ); wp_after_insert_post( get_post( $post_id ), true, $post ); wp_trash_post_comments( $post_id ); /** This action is documented in wp-includes/post.php */ do_action( 'trashed_post', $post_id ); return $post; } /** * Handles request to trash a changeset. * * @since 4.9.0 */ public function handle_changeset_trash_request() { if ( ! is_user_logged_in() ) { wp_send_json_error( 'unauthenticated' ); } if ( ! $this->is_preview() ) { wp_send_json_error( 'not_preview' ); } if ( ! check_ajax_referer( 'trash_customize_changeset', 'nonce', false ) ) { wp_send_json_error( array( 'code' => 'invalid_nonce', 'message' => __( 'There was an authentication problem. Please reload and try again.' ), ) ); } $changeset_post_id = $this->changeset_post_id(); if ( ! $changeset_post_id ) { wp_send_json_error( array( 'message' => __( 'No changes saved yet, so there is nothing to trash.' ), 'code' => 'non_existent_changeset', ) ); return; } if ( $changeset_post_id ) { if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->delete_post, $changeset_post_id ) ) { wp_send_json_error( array( 'code' => 'changeset_trash_unauthorized', 'message' => __( 'Unable to trash changes.' ), ) ); } $lock_user = (int) wp_check_post_lock( $changeset_post_id ); if ( $lock_user && get_current_user_id() !== $lock_user ) { wp_send_json_error( array( 'code' => 'changeset_locked', 'message' => __( 'Changeset is being edited by other user.' ), 'lockUser' => $this->get_lock_user_data( $lock_user ), ) ); } } if ( 'trash' === get_post_status( $changeset_post_id ) ) { wp_send_json_error( array( 'message' => __( 'Changes have already been trashed.' ), 'code' => 'changeset_already_trashed', ) ); return; } $r = $this->trash_changeset_post( $changeset_post_id ); if ( ! ( $r instanceof WP_Post ) ) { wp_send_json_error( array( 'code' => 'changeset_trash_failure', 'message' => __( 'Unable to trash changes.' ), ) ); } wp_send_json_success( array( 'message' => __( 'Changes trashed successfully.' ), ) ); } /** * Re-maps 'edit_post' meta cap for a customize_changeset post to be the same as 'customize' maps. * * There is essentially a "meta meta" cap in play here, where 'edit_post' meta cap maps to * the 'customize' meta cap which then maps to 'edit_theme_options'. This is currently * required in core for `wp_create_post_autosave()` because it will call * `_wp_translate_postdata()` which in turn will check if a user can 'edit_post', but the * the caps for the customize_changeset post type are all mapping to the meta capability. * This should be able to be removed once #40922 is addressed in core. * * @since 4.9.0 * * @link https://core.trac.wordpress.org/ticket/40922 * @see WP_Customize_Manager::save_changeset_post() * @see _wp_translate_postdata() * * @param string[] $caps Array of the user's capabilities. * @param string $cap Capability name. * @param int $user_id The user ID. * @param array $args Adds the context to the cap. Typically the object ID. * @return array Capabilities. */ public function grant_edit_post_capability_for_changeset( $caps, $cap, $user_id, $args ) { if ( 'edit_post' === $cap && ! empty( $args[0] ) && 'customize_changeset' === get_post_type( $args[0] ) ) { $post_type_obj = get_post_type_object( 'customize_changeset' ); $caps = map_meta_cap( $post_type_obj->cap->$cap, $user_id ); } return $caps; } /** * Marks the changeset post as being currently edited by the current user. * * @since 4.9.0 * * @param int $changeset_post_id Changeset post ID. * @param bool $take_over Whether to take over the changeset. Default false. */ public function set_changeset_lock( $changeset_post_id, $take_over = false ) { if ( $changeset_post_id ) { $can_override = ! (bool) get_post_meta( $changeset_post_id, '_edit_lock', true ); if ( $take_over ) { $can_override = true; } if ( $can_override ) { $lock = sprintf( '%s:%s', time(), get_current_user_id() ); update_post_meta( $changeset_post_id, '_edit_lock', $lock ); } else { $this->refresh_changeset_lock( $changeset_post_id ); } } } /** * Refreshes changeset lock with the current time if current user edited the changeset before. * * @since 4.9.0 * * @param int $changeset_post_id Changeset post ID. */ public function refresh_changeset_lock( $changeset_post_id ) { if ( ! $changeset_post_id ) { return; } $lock = get_post_meta( $changeset_post_id, '_edit_lock', true ); $lock = explode( ':', $lock ); if ( $lock && ! empty( $lock[1] ) ) { $user_id = (int) $lock[1]; $current_user_id = get_current_user_id(); if ( $user_id === $current_user_id ) { $lock = sprintf( '%s:%s', time(), $user_id ); update_post_meta( $changeset_post_id, '_edit_lock', $lock ); } } } /** * Filters heartbeat settings for the Customizer. * * @since 4.9.0 * * @global string $pagenow The filename of the current screen. * * @param array $settings Current settings to filter. * @return array Heartbeat settings. */ public function add_customize_screen_to_heartbeat_settings( $settings ) { global $pagenow; if ( 'customize.php' === $pagenow ) { $settings['screenId'] = 'customize'; } return $settings; } /** * Gets lock user data. * * @since 4.9.0 * * @param int $user_id User ID. * @return array|null User data formatted for client. */ protected function get_lock_user_data( $user_id ) { if ( ! $user_id ) { return null; } $lock_user = get_userdata( $user_id ); if ( ! $lock_user ) { return null; } return array( 'id' => $lock_user->ID, 'name' => $lock_user->display_name, 'avatar' => get_avatar_url( $lock_user->ID, array( 'size' => 128 ) ), ); } /** * Checks locked changeset with heartbeat API. * * @since 4.9.0 * * @param array $response The Heartbeat response. * @param array $data The $_POST data sent. * @param string $screen_id The screen id. * @return array The Heartbeat response. */ public function check_changeset_lock_with_heartbeat( $response, $data, $screen_id ) { if ( isset( $data['changeset_uuid'] ) ) { $changeset_post_id = $this->find_changeset_post_id( $data['changeset_uuid'] ); } else { $changeset_post_id = $this->changeset_post_id(); } if ( array_key_exists( 'check_changeset_lock', $data ) && 'customize' === $screen_id && $changeset_post_id && current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) ) { $lock_user_id = wp_check_post_lock( $changeset_post_id ); if ( $lock_user_id ) { $response['customize_changeset_lock_user'] = $this->get_lock_user_data( $lock_user_id ); } else { // Refreshing time will ensure that the user is sitting on customizer and has not closed the customizer tab. $this->refresh_changeset_lock( $changeset_post_id ); } } return $response; } /** * Removes changeset lock when take over request is sent via Ajax. * * @since 4.9.0 */ public function handle_override_changeset_lock_request() { if ( ! $this->is_preview() ) { wp_send_json_error( 'not_preview', 400 ); } if ( ! check_ajax_referer( 'customize_override_changeset_lock', 'nonce', false ) ) { wp_send_json_error( array( 'code' => 'invalid_nonce', 'message' => __( 'Security check failed.' ), ) ); } $changeset_post_id = $this->changeset_post_id(); if ( empty( $changeset_post_id ) ) { wp_send_json_error( array( 'code' => 'no_changeset_found_to_take_over', 'message' => __( 'No changeset found to take over' ), ) ); } if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) ) { wp_send_json_error( array( 'code' => 'cannot_remove_changeset_lock', 'message' => __( 'Sorry, you are not allowed to take over.' ), ) ); } $this->set_changeset_lock( $changeset_post_id, true ); wp_send_json_success( 'changeset_taken_over' ); } /** * Determines whether a changeset revision should be made. * * @since 4.7.0 * @var bool */ protected $store_changeset_revision; /** * Filters whether a changeset has changed to create a new revision. * * Note that this will not be called while a changeset post remains in auto-draft status. * * @since 4.7.0 * * @param bool $post_has_changed Whether the post has changed. * @param WP_Post $latest_revision The latest revision post object. * @param WP_Post $post The post object. * @return bool Whether a revision should be made. */ public function _filter_revision_post_has_changed( $post_has_changed, $latest_revision, $post ) { unset( $latest_revision ); if ( 'customize_changeset' === $post->post_type ) { $post_has_changed = $this->store_changeset_revision; } return $post_has_changed; } /** * Publishes the values of a changeset. * * This will publish the values contained in a changeset, even changesets that do not * correspond to current manager instance. This is called by * `_wp_customize_publish_changeset()` when a customize_changeset post is * transitioned to the `publish` status. As such, this method should not be * called directly and instead `wp_publish_post()` should be used. * * Please note that if the settings in the changeset are for a non-activated * theme, the theme must first be switched to (via `switch_theme()`) before * invoking this method. * * @since 4.7.0 * * @see _wp_customize_publish_changeset() * @global wpdb $wpdb WordPress database abstraction object. * * @param int $changeset_post_id ID for customize_changeset post. Defaults to the changeset for the current manager instance. * @return true|WP_Error True or error info. */ public function _publish_changeset_values( $changeset_post_id ) { global $wpdb; $publishing_changeset_data = $this->get_changeset_post_data( $changeset_post_id ); if ( is_wp_error( $publishing_changeset_data ) ) { return $publishing_changeset_data; } $changeset_post = get_post( $changeset_post_id ); /* * Temporarily override the changeset context so that it will be read * in calls to unsanitized_post_values() and so that it will be available * on the $wp_customize object passed to hooks during the save logic. */ $previous_changeset_post_id = $this->_changeset_post_id; $this->_changeset_post_id = $changeset_post_id; $previous_changeset_uuid = $this->_changeset_uuid; $this->_changeset_uuid = $changeset_post->post_name; $previous_changeset_data = $this->_changeset_data; $this->_changeset_data = $publishing_changeset_data; // Parse changeset data to identify theme mod settings and user IDs associated with settings to be saved. $setting_user_ids = array(); $theme_mod_settings = array(); $namespace_pattern = '/^(?P<stylesheet>.+?)::(?P<setting_id>.+)$/'; $matches = array(); foreach ( $this->_changeset_data as $raw_setting_id => $setting_params ) { $actual_setting_id = null; $is_theme_mod_setting = ( isset( $setting_params['value'] ) && isset( $setting_params['type'] ) && 'theme_mod' === $setting_params['type'] && preg_match( $namespace_pattern, $raw_setting_id, $matches ) ); if ( $is_theme_mod_setting ) { if ( ! isset( $theme_mod_settings[ $matches['stylesheet'] ] ) ) { $theme_mod_settings[ $matches['stylesheet'] ] = array(); } $theme_mod_settings[ $matches['stylesheet'] ][ $matches['setting_id'] ] = $setting_params; if ( $this->get_stylesheet() === $matches['stylesheet'] ) { $actual_setting_id = $matches['setting_id']; } } else { $actual_setting_id = $raw_setting_id; } // Keep track of the user IDs for settings actually for this theme. if ( $actual_setting_id && isset( $setting_params['user_id'] ) ) { $setting_user_ids[ $actual_setting_id ] = $setting_params['user_id']; } } $changeset_setting_values = $this->unsanitized_post_values( array( 'exclude_post_data' => true, 'exclude_changeset' => false, ) ); $changeset_setting_ids = array_keys( $changeset_setting_values ); $this->add_dynamic_settings( $changeset_setting_ids ); /** * Fires once the theme has switched in the Customizer, but before settings * have been saved. * * @since 3.4.0 * * @param WP_Customize_Manager $manager WP_Customize_Manager instance. */ do_action( 'customize_save', $this ); /* * Ensure that all settings will allow themselves to be saved. Note that * this is safe because the setting would have checked the capability * when the setting value was written into the changeset. So this is why * an additional capability check is not required here. */ $original_setting_capabilities = array(); foreach ( $changeset_setting_ids as $setting_id ) { $setting = $this->get_setting( $setting_id ); if ( $setting && ! isset( $setting_user_ids[ $setting_id ] ) ) { $original_setting_capabilities[ $setting->id ] = $setting->capability; $setting->capability = 'exist'; } } $original_user_id = get_current_user_id(); foreach ( $changeset_setting_ids as $setting_id ) { $setting = $this->get_setting( $setting_id ); if ( $setting ) { /* * Set the current user to match the user who saved the value into * the changeset so that any filters that apply during the save * process will respect the original user's capabilities. This * will ensure, for example, that KSES won't strip unsafe HTML * when a scheduled changeset publishes via WP Cron. */ if ( isset( $setting_user_ids[ $setting_id ] ) ) { wp_set_current_user( $setting_user_ids[ $setting_id ] ); } else { wp_set_current_user( $original_user_id ); } $setting->save(); } } wp_set_current_user( $original_user_id ); // Update the stashed theme mod settings, removing the active theme's stashed settings, if activated. if ( did_action( 'switch_theme' ) ) { $other_theme_mod_settings = $theme_mod_settings; unset( $other_theme_mod_settings[ $this->get_stylesheet() ] ); $this->update_stashed_theme_mod_settings( $other_theme_mod_settings ); } /** * Fires after Customize settings have been saved. * * @since 3.6.0 * * @param WP_Customize_Manager $manager WP_Customize_Manager instance. */ do_action( 'customize_save_after', $this ); // Restore original capabilities. foreach ( $original_setting_capabilities as $setting_id => $capability ) { $setting = $this->get_setting( $setting_id ); if ( $setting ) { $setting->capability = $capability; } } // Restore original changeset data. $this->_changeset_data = $previous_changeset_data; $this->_changeset_post_id = $previous_changeset_post_id; $this->_changeset_uuid = $previous_changeset_uuid; /* * Convert all autosave revisions into their own auto-drafts so that users can be prompted to * restore them when a changeset is published, but they had been locked out from including * their changes in the changeset. */ $revisions = wp_get_post_revisions( $changeset_post_id, array( 'check_enabled' => false ) ); foreach ( $revisions as $revision ) { if ( false !== strpos( $revision->post_name, "{$changeset_post_id}-autosave" ) ) { $wpdb->update( $wpdb->posts, array( 'post_status' => 'auto-draft', 'post_type' => 'customize_changeset', 'post_name' => wp_generate_uuid4(), 'post_parent' => 0, ), array( 'ID' => $revision->ID, ) ); clean_post_cache( $revision->ID ); } } return true; } /** * Updates stashed theme mod settings. * * @since 4.7.0 * * @param array $inactive_theme_mod_settings Mapping of stylesheet to arrays of theme mod settings. * @return array|false Returns array of updated stashed theme mods or false if the update failed or there were no changes. */ protected function update_stashed_theme_mod_settings( $inactive_theme_mod_settings ) { $stashed_theme_mod_settings = get_option( 'customize_stashed_theme_mods' ); if ( empty( $stashed_theme_mod_settings ) ) { $stashed_theme_mod_settings = array(); } // Delete any stashed theme mods for the active theme since they would have been loaded and saved upon activation. unset( $stashed_theme_mod_settings[ $this->get_stylesheet() ] ); // Merge inactive theme mods with the stashed theme mod settings. foreach ( $inactive_theme_mod_settings as $stylesheet => $theme_mod_settings ) { if ( ! isset( $stashed_theme_mod_settings[ $stylesheet ] ) ) { $stashed_theme_mod_settings[ $stylesheet ] = array(); } $stashed_theme_mod_settings[ $stylesheet ] = array_merge( $stashed_theme_mod_settings[ $stylesheet ], $theme_mod_settings ); } $autoload = false; $result = update_option( 'customize_stashed_theme_mods', $stashed_theme_mod_settings, $autoload ); if ( ! $result ) { return false; } return $stashed_theme_mod_settings; } /** * Refreshes nonces for the current preview. * * @since 4.2.0 */ public function refresh_nonces() { if ( ! $this->is_preview() ) { wp_send_json_error( 'not_preview' ); } wp_send_json_success( $this->get_nonces() ); } /** * Deletes a given auto-draft changeset or the autosave revision for a given changeset or delete changeset lock. * * @since 4.9.0 */ public function handle_dismiss_autosave_or_lock_request() { // Calls to dismiss_user_auto_draft_changesets() and wp_get_post_autosave() require non-zero get_current_user_id(). if ( ! is_user_logged_in() ) { wp_send_json_error( 'unauthenticated', 401 ); } if ( ! $this->is_preview() ) { wp_send_json_error( 'not_preview', 400 ); } if ( ! check_ajax_referer( 'customize_dismiss_autosave_or_lock', 'nonce', false ) ) { wp_send_json_error( 'invalid_nonce', 403 ); } $changeset_post_id = $this->changeset_post_id(); $dismiss_lock = ! empty( $_POST['dismiss_lock'] ); $dismiss_autosave = ! empty( $_POST['dismiss_autosave'] ); if ( $dismiss_lock ) { if ( empty( $changeset_post_id ) && ! $dismiss_autosave ) { wp_send_json_error( 'no_changeset_to_dismiss_lock', 404 ); } if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) && ! $dismiss_autosave ) { wp_send_json_error( 'cannot_remove_changeset_lock', 403 ); } delete_post_meta( $changeset_post_id, '_edit_lock' ); if ( ! $dismiss_autosave ) { wp_send_json_success( 'changeset_lock_dismissed' ); } } if ( $dismiss_autosave ) { if ( empty( $changeset_post_id ) || 'auto-draft' === get_post_status( $changeset_post_id ) ) { $dismissed = $this->dismiss_user_auto_draft_changesets(); if ( $dismissed > 0 ) { wp_send_json_success( 'auto_draft_dismissed' ); } else { wp_send_json_error( 'no_auto_draft_to_delete', 404 ); } } else { $revision = wp_get_post_autosave( $changeset_post_id, get_current_user_id() ); if ( $revision ) { if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->delete_post, $changeset_post_id ) ) { wp_send_json_error( 'cannot_delete_autosave_revision', 403 ); } if ( ! wp_delete_post( $revision->ID, true ) ) { wp_send_json_error( 'autosave_revision_deletion_failure', 500 ); } else { wp_send_json_success( 'autosave_revision_deleted' ); } } else { wp_send_json_error( 'no_autosave_revision_to_delete', 404 ); } } } wp_send_json_error( 'unknown_error', 500 ); } /** * Adds a customize setting. * * @since 3.4.0 * @since 4.5.0 Return added WP_Customize_Setting instance. * * @see WP_Customize_Setting::__construct() * @link https://developer.wordpress.org/themes/customize-api * * @param WP_Customize_Setting|string $id Customize Setting object, or ID. * @param array $args Optional. Array of properties for the new Setting object. * See WP_Customize_Setting::__construct() for information * on accepted arguments. Default empty array. * @return WP_Customize_Setting The instance of the setting that was added. */ public function add_setting( $id, $args = array() ) { if ( $id instanceof WP_Customize_Setting ) { $setting = $id; } else { $class = 'WP_Customize_Setting'; /** This filter is documented in wp-includes/class-wp-customize-manager.php */ $args = apply_filters( 'customize_dynamic_setting_args', $args, $id ); /** This filter is documented in wp-includes/class-wp-customize-manager.php */ $class = apply_filters( 'customize_dynamic_setting_class', $class, $id, $args ); $setting = new $class( $this, $id, $args ); } $this->settings[ $setting->id ] = $setting; return $setting; } /** * Registers any dynamically-created settings, such as those from $_POST['customized'] * that have no corresponding setting created. * * This is a mechanism to "wake up" settings that have been dynamically created * on the front end and have been sent to WordPress in `$_POST['customized']`. When WP * loads, the dynamically-created settings then will get created and previewed * even though they are not directly created statically with code. * * @since 4.2.0 * * @param array $setting_ids The setting IDs to add. * @return array The WP_Customize_Setting objects added. */ public function add_dynamic_settings( $setting_ids ) { $new_settings = array(); foreach ( $setting_ids as $setting_id ) { // Skip settings already created. if ( $this->get_setting( $setting_id ) ) { continue; } $setting_args = false; $setting_class = 'WP_Customize_Setting'; /** * Filters a dynamic setting's constructor args. * * For a dynamic setting to be registered, this filter must be employed * to override the default false value with an array of args to pass to * the WP_Customize_Setting constructor. * * @since 4.2.0 * * @param false|array $setting_args The arguments to the WP_Customize_Setting constructor. * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`. */ $setting_args = apply_filters( 'customize_dynamic_setting_args', $setting_args, $setting_id ); if ( false === $setting_args ) { continue; } /** * Allow non-statically created settings to be constructed with custom WP_Customize_Setting subclass. * * @since 4.2.0 * * @param string $setting_class WP_Customize_Setting or a subclass. * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`. * @param array $setting_args WP_Customize_Setting or a subclass. */ $setting_class = apply_filters( 'customize_dynamic_setting_class', $setting_class, $setting_id, $setting_args ); $setting = new $setting_class( $this, $setting_id, $setting_args ); $this->add_setting( $setting ); $new_settings[] = $setting; } return $new_settings; } /** * Retrieves a customize setting. * * @since 3.4.0 * * @param string $id Customize Setting ID. * @return WP_Customize_Setting|void The setting, if set. */ public function get_setting( $id ) { if ( isset( $this->settings[ $id ] ) ) { return $this->settings[ $id ]; } } /** * Removes a customize setting. * * Note that removing the setting doesn't destroy the WP_Customize_Setting instance or remove its filters. * * @since 3.4.0 * * @param string $id Customize Setting ID. */ public function remove_setting( $id ) { unset( $this->settings[ $id ] ); } /** * Adds a customize panel. * * @since 4.0.0 * @since 4.5.0 Return added WP_Customize_Panel instance. * * @see WP_Customize_Panel::__construct() * * @param WP_Customize_Panel|string $id Customize Panel object, or ID. * @param array $args Optional. Array of properties for the new Panel object. * See WP_Customize_Panel::__construct() for information * on accepted arguments. Default empty array. * @return WP_Customize_Panel The instance of the panel that was added. */ public function add_panel( $id, $args = array() ) { if ( $id instanceof WP_Customize_Panel ) { $panel = $id; } else { $panel = new WP_Customize_Panel( $this, $id, $args ); } $this->panels[ $panel->id ] = $panel; return $panel; } /** * Retrieves a customize panel. * * @since 4.0.0 * * @param string $id Panel ID to get. * @return WP_Customize_Panel|void Requested panel instance, if set. */ public function get_panel( $id ) { if ( isset( $this->panels[ $id ] ) ) { return $this->panels[ $id ]; } } /** * Removes a customize panel. * * Note that removing the panel doesn't destroy the WP_Customize_Panel instance or remove its filters. * * @since 4.0.0 * * @param string $id Panel ID to remove. */ public function remove_panel( $id ) { // Removing core components this way is _doing_it_wrong(). if ( in_array( $id, $this->components, true ) ) { _doing_it_wrong( __METHOD__, sprintf( /* translators: 1: Panel ID, 2: Link to 'customize_loaded_components' filter reference. */ __( 'Removing %1$s manually will cause PHP warnings. Use the %2$s filter instead.' ), $id, sprintf( '<a href="%1$s">%2$s</a>', esc_url( 'https://developer.wordpress.org/reference/hooks/customize_loaded_components/' ), '<code>customize_loaded_components</code>' ) ), '4.5.0' ); } unset( $this->panels[ $id ] ); } /** * Registers a customize panel type. * * Registered types are eligible to be rendered via JS and created dynamically. * * @since 4.3.0 * * @see WP_Customize_Panel * * @param string $panel Name of a custom panel which is a subclass of WP_Customize_Panel. */ public function register_panel_type( $panel ) { $this->registered_panel_types[] = $panel; } /** * Renders JS templates for all registered panel types. * * @since 4.3.0 */ public function render_panel_templates() { foreach ( $this->registered_panel_types as $panel_type ) { $panel = new $panel_type( $this, 'temp', array() ); $panel->print_template(); } } /** * Adds a customize section. * * @since 3.4.0 * @since 4.5.0 Return added WP_Customize_Section instance. * * @see WP_Customize_Section::__construct() * * @param WP_Customize_Section|string $id Customize Section object, or ID. * @param array $args Optional. Array of properties for the new Section object. * See WP_Customize_Section::__construct() for information * on accepted arguments. Default empty array. * @return WP_Customize_Section The instance of the section that was added. */ public function add_section( $id, $args = array() ) { if ( $id instanceof WP_Customize_Section ) { $section = $id; } else { $section = new WP_Customize_Section( $this, $id, $args ); } $this->sections[ $section->id ] = $section; return $section; } /** * Retrieves a customize section. * * @since 3.4.0 * * @param string $id Section ID. * @return WP_Customize_Section|void The section, if set. */ public function get_section( $id ) { if ( isset( $this->sections[ $id ] ) ) { return $this->sections[ $id ]; } } /** * Removes a customize section. * * Note that removing the section doesn't destroy the WP_Customize_Section instance or remove its filters. * * @since 3.4.0 * * @param string $id Section ID. */ public function remove_section( $id ) { unset( $this->sections[ $id ] ); } /** * Registers a customize section type. * * Registered types are eligible to be rendered via JS and created dynamically. * * @since 4.3.0 * * @see WP_Customize_Section * * @param string $section Name of a custom section which is a subclass of WP_Customize_Section. */ public function register_section_type( $section ) { $this->registered_section_types[] = $section; } /** * Renders JS templates for all registered section types. * * @since 4.3.0 */ public function render_section_templates() { foreach ( $this->registered_section_types as $section_type ) { $section = new $section_type( $this, 'temp', array() ); $section->print_template(); } } /** * Adds a customize control. * * @since 3.4.0 * @since 4.5.0 Return added WP_Customize_Control instance. * * @see WP_Customize_Control::__construct() * * @param WP_Customize_Control|string $id Customize Control object, or ID. * @param array $args Optional. Array of properties for the new Control object. * See WP_Customize_Control::__construct() for information * on accepted arguments. Default empty array. * @return WP_Customize_Control The instance of the control that was added. */ public function add_control( $id, $args = array() ) { if ( $id instanceof WP_Customize_Control ) { $control = $id; } else { $control = new WP_Customize_Control( $this, $id, $args ); } $this->controls[ $control->id ] = $control; return $control; } /** * Retrieves a customize control. * * @since 3.4.0 * * @param string $id ID of the control. * @return WP_Customize_Control|void The control object, if set. */ public function get_control( $id ) { if ( isset( $this->controls[ $id ] ) ) { return $this->controls[ $id ]; } } /** * Removes a customize control. * * Note that removing the control doesn't destroy the WP_Customize_Control instance or remove its filters. * * @since 3.4.0 * * @param string $id ID of the control. */ public function remove_control( $id ) { unset( $this->controls[ $id ] ); } /** * Registers a customize control type. * * Registered types are eligible to be rendered via JS and created dynamically. * * @since 4.1.0 * * @param string $control Name of a custom control which is a subclass of * WP_Customize_Control. */ public function register_control_type( $control ) { $this->registered_control_types[] = $control; } /** * Renders JS templates for all registered control types. * * @since 4.1.0 */ public function render_control_templates() { if ( $this->branching() ) { $l10n = array( /* translators: %s: User who is customizing the changeset in customizer. */ 'locked' => __( '%s is already customizing this changeset. Please wait until they are done to try customizing. Your latest changes have been autosaved.' ), /* translators: %s: User who is customizing the changeset in customizer. */ 'locked_allow_override' => __( '%s is already customizing this changeset. Do you want to take over?' ), ); } else { $l10n = array( /* translators: %s: User who is customizing the changeset in customizer. */ 'locked' => __( '%s is already customizing this site. Please wait until they are done to try customizing. Your latest changes have been autosaved.' ), /* translators: %s: User who is customizing the changeset in customizer. */ 'locked_allow_override' => __( '%s is already customizing this site. Do you want to take over?' ), ); } foreach ( $this->registered_control_types as $control_type ) { $control = new $control_type( $this, 'temp', array( 'settings' => array(), ) ); $control->print_template(); } ?> <script type="text/html" id="tmpl-customize-control-default-content"> <# var inputId = _.uniqueId( 'customize-control-default-input-' ); var descriptionId = _.uniqueId( 'customize-control-default-description-' ); var describedByAttr = data.description ? ' aria-describedby="' + descriptionId + '" ' : ''; #> <# switch ( data.type ) { case 'checkbox': #> <span class="customize-inside-control-row"> <input id="{{ inputId }}" {{{ describedByAttr }}} type="checkbox" value="{{ data.value }}" data-customize-setting-key-link="default" > <label for="{{ inputId }}"> {{ data.label }} </label> <# if ( data.description ) { #> <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span> <# } #> </span> <# break; case 'radio': if ( ! data.choices ) { return; } #> <# if ( data.label ) { #> <label for="{{ inputId }}" class="customize-control-title"> {{ data.label }} </label> <# } #> <# if ( data.description ) { #> <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span> <# } #> <# _.each( data.choices, function( val, key ) { #> <span class="customize-inside-control-row"> <# var value, text; if ( _.isObject( val ) ) { value = val.value; text = val.text; } else { value = key; text = val; } #> <input id="{{ inputId + '-' + value }}" type="radio" value="{{ value }}" name="{{ inputId }}" data-customize-setting-key-link="default" {{{ describedByAttr }}} > <label for="{{ inputId + '-' + value }}">{{ text }}</label> </span> <# } ); #> <# break; default: #> <# if ( data.label ) { #> <label for="{{ inputId }}" class="customize-control-title"> {{ data.label }} </label> <# } #> <# if ( data.description ) { #> <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span> <# } #> <# var inputAttrs = { id: inputId, 'data-customize-setting-key-link': 'default' }; if ( 'textarea' === data.type ) { inputAttrs.rows = '5'; } else if ( 'button' === data.type ) { inputAttrs['class'] = 'button button-secondary'; inputAttrs.type = 'button'; } else { inputAttrs.type = data.type; } if ( data.description ) { inputAttrs['aria-describedby'] = descriptionId; } _.extend( inputAttrs, data.input_attrs ); #> <# if ( 'button' === data.type ) { #> <button <# _.each( _.extend( inputAttrs ), function( value, key ) { #> {{{ key }}}="{{ value }}" <# } ); #> >{{ inputAttrs.value }}</button> <# } else if ( 'textarea' === data.type ) { #> <textarea <# _.each( _.extend( inputAttrs ), function( value, key ) { #> {{{ key }}}="{{ value }}" <# }); #> >{{ inputAttrs.value }}</textarea> <# } else if ( 'select' === data.type ) { #> <# delete inputAttrs.type; #> <select <# _.each( _.extend( inputAttrs ), function( value, key ) { #> {{{ key }}}="{{ value }}" <# }); #> > <# _.each( data.choices, function( val, key ) { #> <# var value, text; if ( _.isObject( val ) ) { value = val.value; text = val.text; } else { value = key; text = val; } #> <option value="{{ value }}">{{ text }}</option> <# } ); #> </select> <# } else { #> <input <# _.each( _.extend( inputAttrs ), function( value, key ) { #> {{{ key }}}="{{ value }}" <# }); #> > <# } #> <# } #> </script> <script type="text/html" id="tmpl-customize-notification"> <li class="notice notice-{{ data.type || 'info' }} {{ data.alt ? 'notice-alt' : '' }} {{ data.dismissible ? 'is-dismissible' : '' }} {{ data.containerClasses || '' }}" data-code="{{ data.code }}" data-type="{{ data.type }}"> <div class="notification-message">{{{ data.message || data.code }}}</div> <# if ( data.dismissible ) { #> <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php _e( 'Dismiss' ); ?></span></button> <# } #> </li> </script> <script type="text/html" id="tmpl-customize-changeset-locked-notification"> <li class="notice notice-{{ data.type || 'info' }} {{ data.containerClasses || '' }}" data-code="{{ data.code }}" data-type="{{ data.type }}"> <div class="notification-message customize-changeset-locked-message"> <img class="customize-changeset-locked-avatar" src="{{ data.lockUser.avatar }}" alt="{{ data.lockUser.name }}" /> <p class="currently-editing"> <# if ( data.message ) { #> {{{ data.message }}} <# } else if ( data.allowOverride ) { #> <?php echo esc_html( sprintf( $l10n['locked_allow_override'], '{{ data.lockUser.name }}' ) ); ?> <# } else { #> <?php echo esc_html( sprintf( $l10n['locked'], '{{ data.lockUser.name }}' ) ); ?> <# } #> </p> <p class="notice notice-error notice-alt" hidden></p> <p class="action-buttons"> <# if ( data.returnUrl !== data.previewUrl ) { #> <a class="button customize-notice-go-back-button" href="{{ data.returnUrl }}"><?php _e( 'Go back' ); ?></a> <# } #> <a class="button customize-notice-preview-button" href="{{ data.frontendPreviewUrl }}"><?php _e( 'Preview' ); ?></a> <# if ( data.allowOverride ) { #> <button class="button button-primary wp-tab-last customize-notice-take-over-button"><?php _e( 'Take over' ); ?></button> <# } #> </p> </div> </li> </script> <script type="text/html" id="tmpl-customize-code-editor-lint-error-notification"> <li class="notice notice-{{ data.type || 'info' }} {{ data.alt ? 'notice-alt' : '' }} {{ data.dismissible ? 'is-dismissible' : '' }} {{ data.containerClasses || '' }}" data-code="{{ data.code }}" data-type="{{ data.type }}"> <div class="notification-message">{{{ data.message || data.code }}}</div> <p> <# var elementId = 'el-' + String( Math.random() ); #> <input id="{{ elementId }}" type="checkbox"> <label for="{{ elementId }}"><?php _e( 'Update anyway, even though it might break your site?' ); ?></label> </p> </li> </script> <?php /* The following template is obsolete in core but retained for plugins. */ ?> <script type="text/html" id="tmpl-customize-control-notifications"> <ul> <# _.each( data.notifications, function( notification ) { #> <li class="notice notice-{{ notification.type || 'info' }} {{ data.altNotice ? 'notice-alt' : '' }}" data-code="{{ notification.code }}" data-type="{{ notification.type }}">{{{ notification.message || notification.code }}}</li> <# } ); #> </ul> </script> <script type="text/html" id="tmpl-customize-preview-link-control" > <# var elementPrefix = _.uniqueId( 'el' ) + '-' #> <p class="customize-control-title"> <?php esc_html_e( 'Share Preview Link' ); ?> </p> <p class="description customize-control-description"><?php esc_html_e( 'See how changes would look live on your website, and share the preview with people who can\'t access the Customizer.' ); ?></p> <div class="customize-control-notifications-container"></div> <div class="preview-link-wrapper"> <label for="{{ elementPrefix }}customize-preview-link-input" class="screen-reader-text"><?php esc_html_e( 'Preview Link' ); ?></label> <a href="" target=""> <span class="preview-control-element" data-component="url"></span> <span class="screen-reader-text"><?php _e( '(opens in a new tab)' ); ?></span> </a> <input id="{{ elementPrefix }}customize-preview-link-input" readonly tabindex="-1" class="preview-control-element" data-component="input"> <button class="customize-copy-preview-link preview-control-element button button-secondary" data-component="button" data-copy-text="<?php esc_attr_e( 'Copy' ); ?>" data-copied-text="<?php esc_attr_e( 'Copied' ); ?>" ><?php esc_html_e( 'Copy' ); ?></button> </div> </script> <script type="text/html" id="tmpl-customize-selected-changeset-status-control"> <# var inputId = _.uniqueId( 'customize-selected-changeset-status-control-input-' ); #> <# var descriptionId = _.uniqueId( 'customize-selected-changeset-status-control-description-' ); #> <# if ( data.label ) { #> <label for="{{ inputId }}" class="customize-control-title">{{ data.label }}</label> <# } #> <# if ( data.description ) { #> <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span> <# } #> <# _.each( data.choices, function( choice ) { #> <# var choiceId = inputId + '-' + choice.status; #> <span class="customize-inside-control-row"> <input id="{{ choiceId }}" type="radio" value="{{ choice.status }}" name="{{ inputId }}" data-customize-setting-key-link="default"> <label for="{{ choiceId }}">{{ choice.label }}</label> </span> <# } ); #> </script> <?php } /** * Helper function to compare two objects by priority, ensuring sort stability via instance_number. * * @since 3.4.0 * @deprecated 4.7.0 Use wp_list_sort() * * @param WP_Customize_Panel|WP_Customize_Section|WP_Customize_Control $a Object A. * @param WP_Customize_Panel|WP_Customize_Section|WP_Customize_Control $b Object B. * @return int */ protected function _cmp_priority( $a, $b ) { _deprecated_function( __METHOD__, '4.7.0', 'wp_list_sort' ); if ( $a->priority === $b->priority ) { return $a->instance_number - $b->instance_number; } else { return $a->priority - $b->priority; } } /** * Prepares panels, sections, and controls. * * For each, check if required related components exist, * whether the user has the necessary capabilities, * and sort by priority. * * @since 3.4.0 */ public function prepare_controls() { $controls = array(); $this->controls = wp_list_sort( $this->controls, array( 'priority' => 'ASC', 'instance_number' => 'ASC', ), 'ASC', true ); foreach ( $this->controls as $id => $control ) { if ( ! isset( $this->sections[ $control->section ] ) || ! $control->check_capabilities() ) { continue; } $this->sections[ $control->section ]->controls[] = $control; $controls[ $id ] = $control; } $this->controls = $controls; // Prepare sections. $this->sections = wp_list_sort( $this->sections, array( 'priority' => 'ASC', 'instance_number' => 'ASC', ), 'ASC', true ); $sections = array(); foreach ( $this->sections as $section ) { if ( ! $section->check_capabilities() ) { continue; } $section->controls = wp_list_sort( $section->controls, array( 'priority' => 'ASC', 'instance_number' => 'ASC', ) ); if ( ! $section->panel ) { // Top-level section. $sections[ $section->id ] = $section; } else { // This section belongs to a panel. if ( isset( $this->panels [ $section->panel ] ) ) { $this->panels[ $section->panel ]->sections[ $section->id ] = $section; } } } $this->sections = $sections; // Prepare panels. $this->panels = wp_list_sort( $this->panels, array( 'priority' => 'ASC', 'instance_number' => 'ASC', ), 'ASC', true ); $panels = array(); foreach ( $this->panels as $panel ) { if ( ! $panel->check_capabilities() ) { continue; } $panel->sections = wp_list_sort( $panel->sections, array( 'priority' => 'ASC', 'instance_number' => 'ASC', ), 'ASC', true ); $panels[ $panel->id ] = $panel; } $this->panels = $panels; // Sort panels and top-level sections together. $this->containers = array_merge( $this->panels, $this->sections ); $this->containers = wp_list_sort( $this->containers, array( 'priority' => 'ASC', 'instance_number' => 'ASC', ), 'ASC', true ); } /** * Enqueues scripts for customize controls. * * @since 3.4.0 */ public function enqueue_control_scripts() { foreach ( $this->controls as $control ) { $control->enqueue(); } if ( ! is_multisite() && ( current_user_can( 'install_themes' ) || current_user_can( 'update_themes' ) || current_user_can( 'delete_themes' ) ) ) { wp_enqueue_script( 'updates' ); wp_localize_script( 'updates', '_wpUpdatesItemCounts', array( 'totals' => wp_get_update_data(), ) ); } } /** * Determines whether the user agent is iOS. * * @since 4.4.0 * * @return bool Whether the user agent is iOS. */ public function is_ios() { return wp_is_mobile() && preg_match( '/iPad|iPod|iPhone/', $_SERVER['HTTP_USER_AGENT'] ); } /** * Gets the template string for the Customizer pane document title. * * @since 4.4.0 * * @return string The template string for the document title. */ public function get_document_title_template() { if ( $this->is_theme_active() ) { /* translators: %s: Document title from the preview. */ $document_title_tmpl = __( 'Customize: %s' ); } else { /* translators: %s: Document title from the preview. */ $document_title_tmpl = __( 'Live Preview: %s' ); } $document_title_tmpl = html_entity_decode( $document_title_tmpl, ENT_QUOTES, 'UTF-8' ); // Because exported to JS and assigned to document.title. return $document_title_tmpl; } /** * Sets the initial URL to be previewed. * * URL is validated. * * @since 4.4.0 * * @param string $preview_url URL to be previewed. */ public function set_preview_url( $preview_url ) { $preview_url = sanitize_url( $preview_url ); $this->preview_url = wp_validate_redirect( $preview_url, home_url( '/' ) ); } /** * Gets the initial URL to be previewed. * * @since 4.4.0 * * @return string URL being previewed. */ public function get_preview_url() { if ( empty( $this->preview_url ) ) { $preview_url = home_url( '/' ); } else { $preview_url = $this->preview_url; } return $preview_url; } /** * Determines whether the admin and the frontend are on different domains. * * @since 4.7.0 * * @return bool Whether cross-domain. */ public function is_cross_domain() { $admin_origin = wp_parse_url( admin_url() ); $home_origin = wp_parse_url( home_url() ); $cross_domain = ( strtolower( $admin_origin['host'] ) !== strtolower( $home_origin['host'] ) ); return $cross_domain; } /** * Gets URLs allowed to be previewed. * * If the front end and the admin are served from the same domain, load the * preview over ssl if the Customizer is being loaded over ssl. This avoids * insecure content warnings. This is not attempted if the admin and front end * are on different domains to avoid the case where the front end doesn't have * ssl certs. Domain mapping plugins can allow other urls in these conditions * using the customize_allowed_urls filter. * * @since 4.7.0 * * @return array Allowed URLs. */ public function get_allowed_urls() { $allowed_urls = array( home_url( '/' ) ); if ( is_ssl() && ! $this->is_cross_domain() ) { $allowed_urls[] = home_url( '/', 'https' ); } /** * Filters the list of URLs allowed to be clicked and followed in the Customizer preview. * * @since 3.4.0 * * @param string[] $allowed_urls An array of allowed URLs. */ $allowed_urls = array_unique( apply_filters( 'customize_allowed_urls', $allowed_urls ) ); return $allowed_urls; } /** * Gets messenger channel. * * @since 4.7.0 * * @return string Messenger channel. */ public function get_messenger_channel() { return $this->messenger_channel; } /** * Sets URL to link the user to when closing the Customizer. * * URL is validated. * * @since 4.4.0 * * @param string $return_url URL for return link. */ public function set_return_url( $return_url ) { $return_url = sanitize_url( $return_url ); $return_url = remove_query_arg( wp_removable_query_args(), $return_url ); $return_url = wp_validate_redirect( $return_url ); $this->return_url = $return_url; } /** * Gets URL to link the user to when closing the Customizer. * * @since 4.4.0 * * @global array $_registered_pages * * @return string URL for link to close Customizer. */ public function get_return_url() { global $_registered_pages; $referer = wp_get_referer(); $excluded_referer_basenames = array( 'customize.php', 'wp-login.php' ); if ( $this->return_url ) { $return_url = $this->return_url; $return_url_basename = wp_basename( parse_url( $this->return_url, PHP_URL_PATH ) ); $return_url_query = parse_url( $this->return_url, PHP_URL_QUERY ); if ( 'themes.php' === $return_url_basename && $return_url_query ) { parse_str( $return_url_query, $query_vars ); /* * If the return URL is a page added by a theme to the Appearance menu via add_submenu_page(), * verify that it belongs to the active theme, otherwise fall back to the Themes screen. */ if ( isset( $query_vars['page'] ) && ! isset( $_registered_pages[ "appearance_page_{$query_vars['page']}" ] ) ) { $return_url = admin_url( 'themes.php' ); } } } elseif ( $referer && ! in_array( wp_basename( parse_url( $referer, PHP_URL_PATH ) ), $excluded_referer_basenames, true ) ) { $return_url = $referer; } elseif ( $this->preview_url ) { $return_url = $this->preview_url; } else { $return_url = home_url( '/' ); } return $return_url; } /** * Sets the autofocused constructs. * * @since 4.4.0 * * @param array $autofocus { * Mapping of 'panel', 'section', 'control' to the ID which should be autofocused. * * @type string $control ID for control to be autofocused. * @type string $section ID for section to be autofocused. * @type string $panel ID for panel to be autofocused. * } */ public function set_autofocus( $autofocus ) { $this->autofocus = array_filter( wp_array_slice_assoc( $autofocus, array( 'panel', 'section', 'control' ) ), 'is_string' ); } /** * Gets the autofocused constructs. * * @since 4.4.0 * * @return string[] { * Mapping of 'panel', 'section', 'control' to the ID which should be autofocused. * * @type string $control ID for control to be autofocused. * @type string $section ID for section to be autofocused. * @type string $panel ID for panel to be autofocused. * } */ public function get_autofocus() { return $this->autofocus; } /** * Gets nonces for the Customizer. * * @since 4.5.0 * * @return array Nonces. */ public function get_nonces() { $nonces = array( 'save' => wp_create_nonce( 'save-customize_' . $this->get_stylesheet() ), 'preview' => wp_create_nonce( 'preview-customize_' . $this->get_stylesheet() ), 'switch_themes' => wp_create_nonce( 'switch_themes' ), 'dismiss_autosave_or_lock' => wp_create_nonce( 'customize_dismiss_autosave_or_lock' ), 'override_lock' => wp_create_nonce( 'customize_override_changeset_lock' ), 'trash' => wp_create_nonce( 'trash_customize_changeset' ), ); /** * Filters nonces for Customizer. * * @since 4.2.0 * * @param string[] $nonces Array of refreshed nonces for save and * preview actions. * @param WP_Customize_Manager $manager WP_Customize_Manager instance. */ $nonces = apply_filters( 'customize_refresh_nonces', $nonces, $this ); return $nonces; } /** * Prints JavaScript settings for parent window. * * @since 4.4.0 */ public function customize_pane_settings() { $login_url = add_query_arg( array( 'interim-login' => 1, 'customize-login' => 1, ), wp_login_url() ); // Ensure dirty flags are set for modified settings. foreach ( array_keys( $this->unsanitized_post_values() ) as $setting_id ) { $setting = $this->get_setting( $setting_id ); if ( $setting ) { $setting->dirty = true; } } $autosave_revision_post = null; $autosave_autodraft_post = null; $changeset_post_id = $this->changeset_post_id(); if ( ! $this->saved_starter_content_changeset && ! $this->autosaved() ) { if ( $changeset_post_id ) { if ( is_user_logged_in() ) { $autosave_revision_post = wp_get_post_autosave( $changeset_post_id, get_current_user_id() ); } } else { $autosave_autodraft_posts = $this->get_changeset_posts( array( 'posts_per_page' => 1, 'post_status' => 'auto-draft', 'exclude_restore_dismissed' => true, ) ); if ( ! empty( $autosave_autodraft_posts ) ) { $autosave_autodraft_post = array_shift( $autosave_autodraft_posts ); } } } $current_user_can_publish = current_user_can( get_post_type_object( 'customize_changeset' )->cap->publish_posts ); // @todo Include all of the status labels here from script-loader.php, and then allow it to be filtered. $status_choices = array(); if ( $current_user_can_publish ) { $status_choices[] = array( 'status' => 'publish', 'label' => __( 'Publish' ), ); } $status_choices[] = array( 'status' => 'draft', 'label' => __( 'Save Draft' ), ); if ( $current_user_can_publish ) { $status_choices[] = array( 'status' => 'future', 'label' => _x( 'Schedule', 'customizer changeset action/button label' ), ); } // Prepare Customizer settings to pass to JavaScript. $changeset_post = null; if ( $changeset_post_id ) { $changeset_post = get_post( $changeset_post_id ); } // Determine initial date to be at present or future, not past. $current_time = current_time( 'mysql', false ); $initial_date = $current_time; if ( $changeset_post ) { $initial_date = get_the_time( 'Y-m-d H:i:s', $changeset_post->ID ); if ( $initial_date < $current_time ) { $initial_date = $current_time; } } $lock_user_id = false; if ( $this->changeset_post_id() ) { $lock_user_id = wp_check_post_lock( $this->changeset_post_id() ); } $settings = array( 'changeset' => array( 'uuid' => $this->changeset_uuid(), 'branching' => $this->branching(), 'autosaved' => $this->autosaved(), 'hasAutosaveRevision' => ! empty( $autosave_revision_post ), 'latestAutoDraftUuid' => $autosave_autodraft_post ? $autosave_autodraft_post->post_name : null, 'status' => $changeset_post ? $changeset_post->post_status : '', 'currentUserCanPublish' => $current_user_can_publish, 'publishDate' => $initial_date, 'statusChoices' => $status_choices, 'lockUser' => $lock_user_id ? $this->get_lock_user_data( $lock_user_id ) : null, ), 'initialServerDate' => $current_time, 'dateFormat' => get_option( 'date_format' ), 'timeFormat' => get_option( 'time_format' ), 'initialServerTimestamp' => floor( microtime( true ) * 1000 ), 'initialClientTimestamp' => -1, // To be set with JS below. 'timeouts' => array( 'windowRefresh' => 250, 'changesetAutoSave' => AUTOSAVE_INTERVAL * 1000, 'keepAliveCheck' => 2500, 'reflowPaneContents' => 100, 'previewFrameSensitivity' => 2000, ), 'theme' => array( 'stylesheet' => $this->get_stylesheet(), 'active' => $this->is_theme_active(), '_canInstall' => current_user_can( 'install_themes' ), ), 'url' => array( 'preview' => sanitize_url( $this->get_preview_url() ), 'return' => sanitize_url( $this->get_return_url() ), 'parent' => sanitize_url( admin_url() ), 'activated' => sanitize_url( home_url( '/' ) ), 'ajax' => sanitize_url( admin_url( 'admin-ajax.php', 'relative' ) ), 'allowed' => array_map( 'sanitize_url', $this->get_allowed_urls() ), 'isCrossDomain' => $this->is_cross_domain(), 'home' => sanitize_url( home_url( '/' ) ), 'login' => sanitize_url( $login_url ), ), 'browser' => array( 'mobile' => wp_is_mobile(), 'ios' => $this->is_ios(), ), 'panels' => array(), 'sections' => array(), 'nonce' => $this->get_nonces(), 'autofocus' => $this->get_autofocus(), 'documentTitleTmpl' => $this->get_document_title_template(), 'previewableDevices' => $this->get_previewable_devices(), 'l10n' => array( 'confirmDeleteTheme' => __( 'Are you sure you want to delete this theme?' ), /* translators: %d: Number of theme search results, which cannot currently consider singular vs. plural forms. */ 'themeSearchResults' => __( '%d themes found' ), /* translators: %d: Number of themes being displayed, which cannot currently consider singular vs. plural forms. */ 'announceThemeCount' => __( 'Displaying %d themes' ), /* translators: %s: Theme name. */ 'announceThemeDetails' => __( 'Showing details for theme: %s' ), ), ); // Temporarily disable installation in Customizer. See #42184. $filesystem_method = get_filesystem_method(); ob_start(); $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() ); ob_end_clean(); if ( 'direct' !== $filesystem_method && ! $filesystem_credentials_are_stored ) { $settings['theme']['_filesystemCredentialsNeeded'] = true; } // Prepare Customize Section objects to pass to JavaScript. foreach ( $this->sections() as $id => $section ) { if ( $section->check_capabilities() ) { $settings['sections'][ $id ] = $section->json(); } } // Prepare Customize Panel objects to pass to JavaScript. foreach ( $this->panels() as $panel_id => $panel ) { if ( $panel->check_capabilities() ) { $settings['panels'][ $panel_id ] = $panel->json(); foreach ( $panel->sections as $section_id => $section ) { if ( $section->check_capabilities() ) { $settings['sections'][ $section_id ] = $section->json(); } } } } ?> <script type="text/javascript"> var _wpCustomizeSettings = <?php echo wp_json_encode( $settings ); ?>; _wpCustomizeSettings.initialClientTimestamp = _.now(); _wpCustomizeSettings.controls = {}; _wpCustomizeSettings.settings = {}; <?php // Serialize settings one by one to improve memory usage. echo "(function ( s ){\n"; foreach ( $this->settings() as $setting ) { if ( $setting->check_capabilities() ) { printf( "s[%s] = %s;\n", wp_json_encode( $setting->id ), wp_json_encode( $setting->json() ) ); } } echo "})( _wpCustomizeSettings.settings );\n"; // Serialize controls one by one to improve memory usage. echo "(function ( c ){\n"; foreach ( $this->controls() as $control ) { if ( $control->check_capabilities() ) { printf( "c[%s] = %s;\n", wp_json_encode( $control->id ), wp_json_encode( $control->json() ) ); } } echo "})( _wpCustomizeSettings.controls );\n"; ?> </script> <?php } /** * Returns a list of devices to allow previewing. * * @since 4.5.0 * * @return array List of devices with labels and default setting. */ public function get_previewable_devices() { $devices = array( 'desktop' => array( 'label' => __( 'Enter desktop preview mode' ), 'default' => true, ), 'tablet' => array( 'label' => __( 'Enter tablet preview mode' ), ), 'mobile' => array( 'label' => __( 'Enter mobile preview mode' ), ), ); /** * Filters the available devices to allow previewing in the Customizer. * * @since 4.5.0 * * @see WP_Customize_Manager::get_previewable_devices() * * @param array $devices List of devices with labels and default setting. */ $devices = apply_filters( 'customize_previewable_devices', $devices ); return $devices; } /** * Registers some default controls. * * @since 3.4.0 */ public function register_controls() { /* Themes (controls are loaded via ajax) */ $this->add_panel( new WP_Customize_Themes_Panel( $this, 'themes', array( 'title' => $this->theme()->display( 'Name' ), 'description' => ( '<p>' . __( 'Looking for a theme? You can search or browse the WordPress.org theme directory, install and preview themes, then activate them right here.' ) . '</p>' . '<p>' . __( 'While previewing a new theme, you can continue to tailor things like widgets and menus, and explore theme-specific options.' ) . '</p>' ), 'capability' => 'switch_themes', 'priority' => 0, ) ) ); $this->add_section( new WP_Customize_Themes_Section( $this, 'installed_themes', array( 'title' => __( 'Installed themes' ), 'action' => 'installed', 'capability' => 'switch_themes', 'panel' => 'themes', 'priority' => 0, ) ) ); if ( ! is_multisite() ) { $this->add_section( new WP_Customize_Themes_Section( $this, 'wporg_themes', array( 'title' => __( 'WordPress.org themes' ), 'action' => 'wporg', 'filter_type' => 'remote', 'capability' => 'install_themes', 'panel' => 'themes', 'priority' => 5, ) ) ); } // Themes Setting (unused - the theme is considerably more fundamental to the Customizer experience). $this->add_setting( new WP_Customize_Filter_Setting( $this, 'active_theme', array( 'capability' => 'switch_themes', ) ) ); /* Site Identity */ $this->add_section( 'title_tagline', array( 'title' => __( 'Site Identity' ), 'priority' => 20, ) ); $this->add_setting( 'blogname', array( 'default' => get_option( 'blogname' ), 'type' => 'option', 'capability' => 'manage_options', ) ); $this->add_control( 'blogname', array( 'label' => __( 'Site Title' ), 'section' => 'title_tagline', ) ); $this->add_setting( 'blogdescription', array( 'default' => get_option( 'blogdescription' ), 'type' => 'option', 'capability' => 'manage_options', ) ); $this->add_control( 'blogdescription', array( 'label' => __( 'Tagline' ), 'section' => 'title_tagline', ) ); // Add a setting to hide header text if the theme doesn't support custom headers. if ( ! current_theme_supports( 'custom-header', 'header-text' ) ) { $this->add_setting( 'header_text', array( 'theme_supports' => array( 'custom-logo', 'header-text' ), 'default' => 1, 'sanitize_callback' => 'absint', ) ); $this->add_control( 'header_text', array( 'label' => __( 'Display Site Title and Tagline' ), 'section' => 'title_tagline', 'settings' => 'header_text', 'type' => 'checkbox', ) ); } $this->add_setting( 'site_icon', array( 'type' => 'option', 'capability' => 'manage_options', 'transport' => 'postMessage', // Previewed with JS in the Customizer controls window. ) ); $this->add_control( new WP_Customize_Site_Icon_Control( $this, 'site_icon', array( 'label' => __( 'Site Icon' ), 'description' => sprintf( '<p>' . __( 'Site Icons are what you see in browser tabs, bookmark bars, and within the WordPress mobile apps. Upload one here!' ) . '</p>' . /* translators: %s: Site icon size in pixels. */ '<p>' . __( 'Site Icons should be square and at least %s pixels.' ) . '</p>', '<strong>512 &times; 512</strong>' ), 'section' => 'title_tagline', 'priority' => 60, 'height' => 512, 'width' => 512, ) ) ); $this->add_setting( 'custom_logo', array( 'theme_supports' => array( 'custom-logo' ), 'transport' => 'postMessage', ) ); $custom_logo_args = get_theme_support( 'custom-logo' ); $this->add_control( new WP_Customize_Cropped_Image_Control( $this, 'custom_logo', array( 'label' => __( 'Logo' ), 'section' => 'title_tagline', 'priority' => 8, 'height' => isset( $custom_logo_args[0]['height'] ) ? $custom_logo_args[0]['height'] : null, 'width' => isset( $custom_logo_args[0]['width'] ) ? $custom_logo_args[0]['width'] : null, 'flex_height' => isset( $custom_logo_args[0]['flex-height'] ) ? $custom_logo_args[0]['flex-height'] : null, 'flex_width' => isset( $custom_logo_args[0]['flex-width'] ) ? $custom_logo_args[0]['flex-width'] : null, 'button_labels' => array( 'select' => __( 'Select logo' ), 'change' => __( 'Change logo' ), 'remove' => __( 'Remove' ), 'default' => __( 'Default' ), 'placeholder' => __( 'No logo selected' ), 'frame_title' => __( 'Select logo' ), 'frame_button' => __( 'Choose logo' ), ), ) ) ); $this->selective_refresh->add_partial( 'custom_logo', array( 'settings' => array( 'custom_logo' ), 'selector' => '.custom-logo-link', 'render_callback' => array( $this, '_render_custom_logo_partial' ), 'container_inclusive' => true, ) ); /* Colors */ $this->add_section( 'colors', array( 'title' => __( 'Colors' ), 'priority' => 40, ) ); $this->add_setting( 'header_textcolor', array( 'theme_supports' => array( 'custom-header', 'header-text' ), 'default' => get_theme_support( 'custom-header', 'default-text-color' ), 'sanitize_callback' => array( $this, '_sanitize_header_textcolor' ), 'sanitize_js_callback' => 'maybe_hash_hex_color', ) ); // Input type: checkbox. // With custom value. $this->add_control( 'display_header_text', array( 'settings' => 'header_textcolor', 'label' => __( 'Display Site Title and Tagline' ), 'section' => 'title_tagline', 'type' => 'checkbox', 'priority' => 40, ) ); $this->add_control( new WP_Customize_Color_Control( $this, 'header_textcolor', array( 'label' => __( 'Header Text Color' ), 'section' => 'colors', ) ) ); // Input type: color. // With sanitize_callback. $this->add_setting( 'background_color', array( 'default' => get_theme_support( 'custom-background', 'default-color' ), 'theme_supports' => 'custom-background', 'sanitize_callback' => 'sanitize_hex_color_no_hash', 'sanitize_js_callback' => 'maybe_hash_hex_color', ) ); $this->add_control( new WP_Customize_Color_Control( $this, 'background_color', array( 'label' => __( 'Background Color' ), 'section' => 'colors', ) ) ); /* Custom Header */ if ( current_theme_supports( 'custom-header', 'video' ) ) { $title = __( 'Header Media' ); $description = '<p>' . __( 'If you add a video, the image will be used as a fallback while the video loads.' ) . '</p>'; $width = absint( get_theme_support( 'custom-header', 'width' ) ); $height = absint( get_theme_support( 'custom-header', 'height' ) ); if ( $width && $height ) { $control_description = sprintf( /* translators: 1: .mp4, 2: Header size in pixels. */ __( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends dimensions of %2$s pixels.' ), '<code>.mp4</code>', sprintf( '<strong>%s &times; %s</strong>', $width, $height ) ); } elseif ( $width ) { $control_description = sprintf( /* translators: 1: .mp4, 2: Header width in pixels. */ __( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends a width of %2$s pixels.' ), '<code>.mp4</code>', sprintf( '<strong>%s</strong>', $width ) ); } else { $control_description = sprintf( /* translators: 1: .mp4, 2: Header height in pixels. */ __( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends a height of %2$s pixels.' ), '<code>.mp4</code>', sprintf( '<strong>%s</strong>', $height ) ); } } else { $title = __( 'Header Image' ); $description = ''; $control_description = ''; } $this->add_section( 'header_image', array( 'title' => $title, 'description' => $description, 'theme_supports' => 'custom-header', 'priority' => 60, ) ); $this->add_setting( 'header_video', array( 'theme_supports' => array( 'custom-header', 'video' ), 'transport' => 'postMessage', 'sanitize_callback' => 'absint', 'validate_callback' => array( $this, '_validate_header_video' ), ) ); $this->add_setting( 'external_header_video', array( 'theme_supports' => array( 'custom-header', 'video' ), 'transport' => 'postMessage', 'sanitize_callback' => array( $this, '_sanitize_external_header_video' ), 'validate_callback' => array( $this, '_validate_external_header_video' ), ) ); $this->add_setting( new WP_Customize_Filter_Setting( $this, 'header_image', array( 'default' => sprintf( get_theme_support( 'custom-header', 'default-image' ), get_template_directory_uri(), get_stylesheet_directory_uri() ), 'theme_supports' => 'custom-header', ) ) ); $this->add_setting( new WP_Customize_Header_Image_Setting( $this, 'header_image_data', array( 'theme_supports' => 'custom-header', ) ) ); /* * Switch image settings to postMessage when video support is enabled since * it entails that the_custom_header_markup() will be used, and thus selective * refresh can be utilized. */ if ( current_theme_supports( 'custom-header', 'video' ) ) { $this->get_setting( 'header_image' )->transport = 'postMessage'; $this->get_setting( 'header_image_data' )->transport = 'postMessage'; } $this->add_control( new WP_Customize_Media_Control( $this, 'header_video', array( 'theme_supports' => array( 'custom-header', 'video' ), 'label' => __( 'Header Video' ), 'description' => $control_description, 'section' => 'header_image', 'mime_type' => 'video', 'active_callback' => 'is_header_video_active', ) ) ); $this->add_control( 'external_header_video', array( 'theme_supports' => array( 'custom-header', 'video' ), 'type' => 'url', 'description' => __( 'Or, enter a YouTube URL:' ), 'section' => 'header_image', 'active_callback' => 'is_header_video_active', ) ); $this->add_control( new WP_Customize_Header_Image_Control( $this ) ); $this->selective_refresh->add_partial( 'custom_header', array( 'selector' => '#wp-custom-header', 'render_callback' => 'the_custom_header_markup', 'settings' => array( 'header_video', 'external_header_video', 'header_image' ), // The image is used as a video fallback here. 'container_inclusive' => true, ) ); /* Custom Background */ $this->add_section( 'background_image', array( 'title' => __( 'Background Image' ), 'theme_supports' => 'custom-background', 'priority' => 80, ) ); $this->add_setting( 'background_image', array( 'default' => get_theme_support( 'custom-background', 'default-image' ), 'theme_supports' => 'custom-background', 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), ) ); $this->add_setting( new WP_Customize_Background_Image_Setting( $this, 'background_image_thumb', array( 'theme_supports' => 'custom-background', 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), ) ) ); $this->add_control( new WP_Customize_Background_Image_Control( $this ) ); $this->add_setting( 'background_preset', array( 'default' => get_theme_support( 'custom-background', 'default-preset' ), 'theme_supports' => 'custom-background', 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), ) ); $this->add_control( 'background_preset', array( 'label' => _x( 'Preset', 'Background Preset' ), 'section' => 'background_image', 'type' => 'select', 'choices' => array( 'default' => _x( 'Default', 'Default Preset' ), 'fill' => __( 'Fill Screen' ), 'fit' => __( 'Fit to Screen' ), 'repeat' => _x( 'Repeat', 'Repeat Image' ), 'custom' => _x( 'Custom', 'Custom Preset' ), ), ) ); $this->add_setting( 'background_position_x', array( 'default' => get_theme_support( 'custom-background', 'default-position-x' ), 'theme_supports' => 'custom-background', 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), ) ); $this->add_setting( 'background_position_y', array( 'default' => get_theme_support( 'custom-background', 'default-position-y' ), 'theme_supports' => 'custom-background', 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), ) ); $this->add_control( new WP_Customize_Background_Position_Control( $this, 'background_position', array( 'label' => __( 'Image Position' ), 'section' => 'background_image', 'settings' => array( 'x' => 'background_position_x', 'y' => 'background_position_y', ), ) ) ); $this->add_setting( 'background_size', array( 'default' => get_theme_support( 'custom-background', 'default-size' ), 'theme_supports' => 'custom-background', 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), ) ); $this->add_control( 'background_size', array( 'label' => __( 'Image Size' ), 'section' => 'background_image', 'type' => 'select', 'choices' => array( 'auto' => _x( 'Original', 'Original Size' ), 'contain' => __( 'Fit to Screen' ), 'cover' => __( 'Fill Screen' ), ), ) ); $this->add_setting( 'background_repeat', array( 'default' => get_theme_support( 'custom-background', 'default-repeat' ), 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), 'theme_supports' => 'custom-background', ) ); $this->add_control( 'background_repeat', array( 'label' => __( 'Repeat Background Image' ), 'section' => 'background_image', 'type' => 'checkbox', ) ); $this->add_setting( 'background_attachment', array( 'default' => get_theme_support( 'custom-background', 'default-attachment' ), 'sanitize_callback' => array( $this, '_sanitize_background_setting' ), 'theme_supports' => 'custom-background', ) ); $this->add_control( 'background_attachment', array( 'label' => __( 'Scroll with Page' ), 'section' => 'background_image', 'type' => 'checkbox', ) ); // If the theme is using the default background callback, we can update // the background CSS using postMessage. if ( get_theme_support( 'custom-background', 'wp-head-callback' ) === '_custom_background_cb' ) { foreach ( array( 'color', 'image', 'preset', 'position_x', 'position_y', 'size', 'repeat', 'attachment' ) as $prop ) { $this->get_setting( 'background_' . $prop )->transport = 'postMessage'; } } /* * Static Front Page * See also https://core.trac.wordpress.org/ticket/19627 which introduces the static-front-page theme_support. * The following replicates behavior from options-reading.php. */ $this->add_section( 'static_front_page', array( 'title' => __( 'Homepage Settings' ), 'priority' => 120, 'description' => __( 'You can choose what&#8217;s displayed on the homepage of your site. It can be posts in reverse chronological order (classic blog), or a fixed/static page. To set a static homepage, you first need to create two Pages. One will become the homepage, and the other will be where your posts are displayed.' ), 'active_callback' => array( $this, 'has_published_pages' ), ) ); $this->add_setting( 'show_on_front', array( 'default' => get_option( 'show_on_front' ), 'capability' => 'manage_options', 'type' => 'option', ) ); $this->add_control( 'show_on_front', array( 'label' => __( 'Your homepage displays' ), 'section' => 'static_front_page', 'type' => 'radio', 'choices' => array( 'posts' => __( 'Your latest posts' ), 'page' => __( 'A static page' ), ), ) ); $this->add_setting( 'page_on_front', array( 'type' => 'option', 'capability' => 'manage_options', ) ); $this->add_control( 'page_on_front', array( 'label' => __( 'Homepage' ), 'section' => 'static_front_page', 'type' => 'dropdown-pages', 'allow_addition' => true, ) ); $this->add_setting( 'page_for_posts', array( 'type' => 'option', 'capability' => 'manage_options', ) ); $this->add_control( 'page_for_posts', array( 'label' => __( 'Posts page' ), 'section' => 'static_front_page', 'type' => 'dropdown-pages', 'allow_addition' => true, ) ); /* Custom CSS */ $section_description = '<p>'; $section_description .= __( 'Add your own CSS code here to customize the appearance and layout of your site.' ); $section_description .= sprintf( ' <a href="%1$s" class="external-link" target="_blank">%2$s<span class="screen-reader-text"> %3$s</span></a>', esc_url( __( 'https://wordpress.org/support/article/css/' ) ), __( 'Learn more about CSS' ), /* translators: Accessibility text. */ __( '(opens in a new tab)' ) ); $section_description .= '</p>'; $section_description .= '<p id="editor-keyboard-trap-help-1">' . __( 'When using a keyboard to navigate:' ) . '</p>'; $section_description .= '<ul>'; $section_description .= '<li id="editor-keyboard-trap-help-2">' . __( 'In the editing area, the Tab key enters a tab character.' ) . '</li>'; $section_description .= '<li id="editor-keyboard-trap-help-3">' . __( 'To move away from this area, press the Esc key followed by the Tab key.' ) . '</li>'; $section_description .= '<li id="editor-keyboard-trap-help-4">' . __( 'Screen reader users: when in forms mode, you may need to press the Esc key twice.' ) . '</li>'; $section_description .= '</ul>'; if ( 'false' !== wp_get_current_user()->syntax_highlighting ) { $section_description .= '<p>'; $section_description .= 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)' ) ) ); $section_description .= '</p>'; } $section_description .= '<p class="section-description-buttons">'; $section_description .= '<button type="button" class="button-link section-description-close">' . __( 'Close' ) . '</button>'; $section_description .= '</p>'; $this->add_section( 'custom_css', array( 'title' => __( 'Additional CSS' ), 'priority' => 200, 'description_hidden' => true, 'description' => $section_description, ) ); $custom_css_setting = new WP_Customize_Custom_CSS_Setting( $this, sprintf( 'custom_css[%s]', get_stylesheet() ), array( 'capability' => 'edit_css', 'default' => '', ) ); $this->add_setting( $custom_css_setting ); $this->add_control( new WP_Customize_Code_Editor_Control( $this, 'custom_css', array( 'label' => __( 'CSS code' ), 'section' => 'custom_css', 'settings' => array( 'default' => $custom_css_setting->id ), 'code_type' => 'text/css', 'input_attrs' => array( 'aria-describedby' => 'editor-keyboard-trap-help-1 editor-keyboard-trap-help-2 editor-keyboard-trap-help-3 editor-keyboard-trap-help-4', ), ) ) ); } /** * Returns whether there are published pages. * * Used as active callback for static front page section and controls. * * @since 4.7.0 * * @return bool Whether there are published (or to be published) pages. */ public function has_published_pages() { $setting = $this->get_setting( 'nav_menus_created_posts' ); if ( $setting ) { foreach ( $setting->value() as $post_id ) { if ( 'page' === get_post_type( $post_id ) ) { return true; } } } return 0 !== count( get_pages( array( 'number' => 1 ) ) ); } /** * Adds settings from the POST data that were not added with code, e.g. dynamically-created settings for Widgets * * @since 4.2.0 * * @see add_dynamic_settings() */ public function register_dynamic_settings() { $setting_ids = array_keys( $this->unsanitized_post_values() ); $this->add_dynamic_settings( $setting_ids ); } /** * Loads themes into the theme browsing/installation UI. * * @since 4.9.0 */ public function handle_load_themes_request() { check_ajax_referer( 'switch_themes', 'nonce' ); if ( ! current_user_can( 'switch_themes' ) ) { wp_die( -1 ); } if ( empty( $_POST['theme_action'] ) ) { wp_send_json_error( 'missing_theme_action' ); } $theme_action = sanitize_key( $_POST['theme_action'] ); $themes = array(); $args = array(); // Define query filters based on user input. if ( ! array_key_exists( 'search', $_POST ) ) { $args['search'] = ''; } else { $args['search'] = sanitize_text_field( wp_unslash( $_POST['search'] ) ); } if ( ! array_key_exists( 'tags', $_POST ) ) { $args['tag'] = ''; } else { $args['tag'] = array_map( 'sanitize_text_field', wp_unslash( (array) $_POST['tags'] ) ); } if ( ! array_key_exists( 'page', $_POST ) ) { $args['page'] = 1; } else { $args['page'] = absint( $_POST['page'] ); } require_once ABSPATH . 'wp-admin/includes/theme.php'; if ( 'installed' === $theme_action ) { // Load all installed themes from wp_prepare_themes_for_js(). $themes = array( 'themes' => array() ); foreach ( wp_prepare_themes_for_js() as $theme ) { $theme['type'] = 'installed'; $theme['active'] = ( isset( $_POST['customized_theme'] ) && $_POST['customized_theme'] === $theme['id'] ); $themes['themes'][] = $theme; } } elseif ( 'wporg' === $theme_action ) { // Load WordPress.org themes from the .org API and normalize data to match installed theme objects. if ( ! current_user_can( 'install_themes' ) ) { wp_die( -1 ); } // Arguments for all queries. $wporg_args = array( 'per_page' => 100, 'fields' => array( 'reviews_url' => true, // Explicitly request the reviews URL to be linked from the customizer. ), ); $args = array_merge( $wporg_args, $args ); if ( '' === $args['search'] && '' === $args['tag'] ) { $args['browse'] = 'new'; // Sort by latest themes by default. } // Load themes from the .org API. $themes = themes_api( 'query_themes', $args ); if ( is_wp_error( $themes ) ) { wp_send_json_error(); } // This list matches the allowed tags in wp-admin/includes/theme-install.php. $themes_allowedtags = array_fill_keys( array( 'a', 'abbr', 'acronym', 'code', 'pre', 'em', 'strong', 'div', 'p', 'ul', 'ol', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'img' ), array() ); $themes_allowedtags['a'] = array_fill_keys( array( 'href', 'title', 'target' ), true ); $themes_allowedtags['acronym']['title'] = true; $themes_allowedtags['abbr']['title'] = true; $themes_allowedtags['img'] = array_fill_keys( array( 'src', 'class', 'alt' ), true ); // Prepare a list of installed themes to check against before the loop. $installed_themes = array(); $wp_themes = wp_get_themes(); foreach ( $wp_themes as $theme ) { $installed_themes[] = $theme->get_stylesheet(); } $update_php = network_admin_url( 'update.php?action=install-theme' ); // Set up properties for themes available on WordPress.org. foreach ( $themes->themes as &$theme ) { $theme->install_url = add_query_arg( array( 'theme' => $theme->slug, '_wpnonce' => wp_create_nonce( 'install-theme_' . $theme->slug ), ), $update_php ); $theme->name = wp_kses( $theme->name, $themes_allowedtags ); $theme->version = wp_kses( $theme->version, $themes_allowedtags ); $theme->description = wp_kses( $theme->description, $themes_allowedtags ); $theme->stars = wp_star_rating( array( 'rating' => $theme->rating, 'type' => 'percent', 'number' => $theme->num_ratings, 'echo' => false, ) ); $theme->num_ratings = number_format_i18n( $theme->num_ratings ); $theme->preview_url = set_url_scheme( $theme->preview_url ); // Handle themes that are already installed as installed themes. if ( in_array( $theme->slug, $installed_themes, true ) ) { $theme->type = 'installed'; } else { $theme->type = $theme_action; } // Set active based on customized theme. $theme->active = ( isset( $_POST['customized_theme'] ) && $_POST['customized_theme'] === $theme->slug ); // Map available theme properties to installed theme properties. $theme->id = $theme->slug; $theme->screenshot = array( $theme->screenshot_url ); $theme->authorAndUri = wp_kses( $theme->author['display_name'], $themes_allowedtags ); $theme->compatibleWP = is_wp_version_compatible( $theme->requires ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName $theme->compatiblePHP = is_php_version_compatible( $theme->requires_php ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName if ( isset( $theme->parent ) ) { $theme->parent = $theme->parent['slug']; } else { $theme->parent = false; } unset( $theme->slug ); unset( $theme->screenshot_url ); unset( $theme->author ); } // End foreach(). } // End if(). /** * Filters the theme data loaded in the customizer. * * This allows theme data to be loading from an external source, * or modification of data loaded from `wp_prepare_themes_for_js()` * or WordPress.org via `themes_api()`. * * @since 4.9.0 * * @see wp_prepare_themes_for_js() * @see themes_api() * @see WP_Customize_Manager::__construct() * * @param array|stdClass $themes Nested array or object of theme data. * @param array $args List of arguments, such as page, search term, and tags to query for. * @param WP_Customize_Manager $manager Instance of Customize manager. */ $themes = apply_filters( 'customize_load_themes', $themes, $args, $this ); wp_send_json_success( $themes ); } /** * Callback for validating the header_textcolor value. * * Accepts 'blank', and otherwise uses sanitize_hex_color_no_hash(). * Returns default text color if hex color is empty. * * @since 3.4.0 * * @param string $color * @return mixed */ public function _sanitize_header_textcolor( $color ) { if ( 'blank' === $color ) { return 'blank'; } $color = sanitize_hex_color_no_hash( $color ); if ( empty( $color ) ) { $color = get_theme_support( 'custom-header', 'default-text-color' ); } return $color; } /** * Callback for validating a background setting value. * * @since 4.7.0 * * @param string $value Repeat value. * @param WP_Customize_Setting $setting Setting. * @return string|WP_Error Background value or validation error. */ public function _sanitize_background_setting( $value, $setting ) { if ( 'background_repeat' === $setting->id ) { if ( ! in_array( $value, array( 'repeat-x', 'repeat-y', 'repeat', 'no-repeat' ), true ) ) { return new WP_Error( 'invalid_value', __( 'Invalid value for background repeat.' ) ); } } elseif ( 'background_attachment' === $setting->id ) { if ( ! in_array( $value, array( 'fixed', 'scroll' ), true ) ) { return new WP_Error( 'invalid_value', __( 'Invalid value for background attachment.' ) ); } } elseif ( 'background_position_x' === $setting->id ) { if ( ! in_array( $value, array( 'left', 'center', 'right' ), true ) ) { return new WP_Error( 'invalid_value', __( 'Invalid value for background position X.' ) ); } } elseif ( 'background_position_y' === $setting->id ) { if ( ! in_array( $value, array( 'top', 'center', 'bottom' ), true ) ) { return new WP_Error( 'invalid_value', __( 'Invalid value for background position Y.' ) ); } } elseif ( 'background_size' === $setting->id ) { if ( ! in_array( $value, array( 'auto', 'contain', 'cover' ), true ) ) { return new WP_Error( 'invalid_value', __( 'Invalid value for background size.' ) ); } } elseif ( 'background_preset' === $setting->id ) { if ( ! in_array( $value, array( 'default', 'fill', 'fit', 'repeat', 'custom' ), true ) ) { return new WP_Error( 'invalid_value', __( 'Invalid value for background size.' ) ); } } elseif ( 'background_image' === $setting->id || 'background_image_thumb' === $setting->id ) { $value = empty( $value ) ? '' : sanitize_url( $value ); } else { return new WP_Error( 'unrecognized_setting', __( 'Unrecognized background setting.' ) ); } return $value; } /** * Exports header video settings to facilitate selective refresh. * * @since 4.7.0 * * @param array $response Response. * @param WP_Customize_Selective_Refresh $selective_refresh Selective refresh component. * @param array $partials Array of partials. * @return array */ public function export_header_video_settings( $response, $selective_refresh, $partials ) { if ( isset( $partials['custom_header'] ) ) { $response['custom_header_settings'] = get_header_video_settings(); } return $response; } /** * Callback for validating the header_video value. * * Ensures that the selected video is less than 8MB and provides an error message. * * @since 4.7.0 * * @param WP_Error $validity * @param mixed $value * @return mixed */ public function _validate_header_video( $validity, $value ) { $video = get_attached_file( absint( $value ) ); if ( $video ) { $size = filesize( $video ); if ( $size > 8 * MB_IN_BYTES ) { $validity->add( 'size_too_large', __( 'This video file is too large to use as a header video. Try a shorter video or optimize the compression settings and re-upload a file that is less than 8MB. Or, upload your video to YouTube and link it with the option below.' ) ); } if ( '.mp4' !== substr( $video, -4 ) && '.mov' !== substr( $video, -4 ) ) { // Check for .mp4 or .mov format, which (assuming h.264 encoding) are the only cross-browser-supported formats. $validity->add( 'invalid_file_type', sprintf( /* translators: 1: .mp4, 2: .mov */ __( 'Only %1$s or %2$s files may be used for header video. Please convert your video file and try again, or, upload your video to YouTube and link it with the option below.' ), '<code>.mp4</code>', '<code>.mov</code>' ) ); } } return $validity; } /** * Callback for validating the external_header_video value. * * Ensures that the provided URL is supported. * * @since 4.7.0 * * @param WP_Error $validity * @param mixed $value * @return mixed */ public function _validate_external_header_video( $validity, $value ) { $video = sanitize_url( $value ); if ( $video ) { if ( ! preg_match( '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#', $video ) ) { $validity->add( 'invalid_url', __( 'Please enter a valid YouTube URL.' ) ); } } return $validity; } /** * Callback for sanitizing the external_header_video value. * * @since 4.7.1 * * @param string $value URL. * @return string Sanitized URL. */ public function _sanitize_external_header_video( $value ) { return sanitize_url( trim( $value ) ); } /** * Callback for rendering the custom logo, used in the custom_logo partial. * * This method exists because the partial object and context data are passed * into a partial's render_callback so we cannot use get_custom_logo() as * the render_callback directly since it expects a blog ID as the first * argument. When WP no longer supports PHP 5.3, this method can be removed * in favor of an anonymous function. * * @see WP_Customize_Manager::register_controls() * * @since 4.5.0 * * @return string Custom logo. */ public function _render_custom_logo_partial() { return get_custom_logo(); } } ``` | Version | Description | | --- | --- | | [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
programming_docs
wordpress class IXR_Message {} class IXR\_Message {} ===================== IXR\_MESSAGE * [\_\_construct](ixr_message/__construct) β€” PHP5 constructor. * [cdata](ixr_message/cdata) * [IXR\_Message](ixr_message/ixr_message) β€” PHP4 constructor. * [parse](ixr_message/parse) * [tag\_close](ixr_message/tag_close) * [tag\_open](ixr_message/tag_open) File: `wp-includes/IXR/class-IXR-message.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-message.php/) ``` class IXR_Message { var $message = false; var $messageType = false; // methodCall / methodResponse / fault var $faultCode = false; var $faultString = false; var $methodName = ''; var $params = array(); // Current variable stacks var $_arraystructs = array(); // The stack used to keep track of the current array/struct var $_arraystructstypes = array(); // Stack keeping track of if things are structs or array var $_currentStructName = array(); // A stack as well var $_param; var $_value; var $_currentTag; var $_currentTagContents; // The XML parser var $_parser; /** * PHP5 constructor. */ function __construct( $message ) { $this->message =& $message; } /** * PHP4 constructor. */ public function IXR_Message( $message ) { self::__construct( $message ); } function parse() { if ( ! function_exists( 'xml_parser_create' ) ) { trigger_error( __( "PHP's XML extension is not available. Please contact your hosting provider to enable PHP's XML extension." ) ); return false; } // first remove the XML declaration // merged from WP #10698 - this method avoids the RAM usage of preg_replace on very large messages $header = preg_replace( '/<\?xml.*?\?'.'>/s', '', substr( $this->message, 0, 100 ), 1 ); $this->message = trim( substr_replace( $this->message, $header, 0, 100 ) ); if ( '' == $this->message ) { return false; } // Then remove the DOCTYPE $header = preg_replace( '/^<!DOCTYPE[^>]*+>/i', '', substr( $this->message, 0, 200 ), 1 ); $this->message = trim( substr_replace( $this->message, $header, 0, 200 ) ); if ( '' == $this->message ) { return false; } // Check that the root tag is valid $root_tag = substr( $this->message, 0, strcspn( substr( $this->message, 0, 20 ), "> \t\r\n" ) ); if ( '<!DOCTYPE' === strtoupper( $root_tag ) ) { return false; } if ( ! in_array( $root_tag, array( '<methodCall', '<methodResponse', '<fault' ) ) ) { return false; } // Bail if there are too many elements to parse $element_limit = 30000; if ( function_exists( 'apply_filters' ) ) { /** * Filters the number of elements to parse in an XML-RPC response. * * @since 4.0.0 * * @param int $element_limit Default elements limit. */ $element_limit = apply_filters( 'xmlrpc_element_limit', $element_limit ); } if ( $element_limit && 2 * $element_limit < substr_count( $this->message, '<' ) ) { return false; } $this->_parser = xml_parser_create(); // Set XML parser to take the case of tags in to account xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false); // Set XML parser callback functions xml_set_object($this->_parser, $this); xml_set_element_handler($this->_parser, 'tag_open', 'tag_close'); xml_set_character_data_handler($this->_parser, 'cdata'); // 256Kb, parse in chunks to avoid the RAM usage on very large messages $chunk_size = 262144; /** * Filters the chunk size that can be used to parse an XML-RPC response message. * * @since 4.4.0 * * @param int $chunk_size Chunk size to parse in bytes. */ $chunk_size = apply_filters( 'xmlrpc_chunk_parsing_size', $chunk_size ); $final = false; do { if (strlen($this->message) <= $chunk_size) { $final = true; } $part = substr($this->message, 0, $chunk_size); $this->message = substr($this->message, $chunk_size); if (!xml_parse($this->_parser, $part, $final)) { xml_parser_free($this->_parser); unset($this->_parser); return false; } if ($final) { break; } } while (true); xml_parser_free($this->_parser); unset($this->_parser); // Grab the error messages, if any if ($this->messageType == 'fault') { $this->faultCode = $this->params[0]['faultCode']; $this->faultString = $this->params[0]['faultString']; } return true; } function tag_open($parser, $tag, $attr) { $this->_currentTagContents = ''; $this->currentTag = $tag; switch($tag) { case 'methodCall': case 'methodResponse': case 'fault': $this->messageType = $tag; break; /* Deal with stacks of arrays and structs */ case 'data': // data is to all intents and puposes more interesting than array $this->_arraystructstypes[] = 'array'; $this->_arraystructs[] = array(); break; case 'struct': $this->_arraystructstypes[] = 'struct'; $this->_arraystructs[] = array(); break; } } function cdata($parser, $cdata) { $this->_currentTagContents .= $cdata; } function tag_close($parser, $tag) { $valueFlag = false; switch($tag) { case 'int': case 'i4': $value = (int)trim($this->_currentTagContents); $valueFlag = true; break; case 'double': $value = (double)trim($this->_currentTagContents); $valueFlag = true; break; case 'string': $value = (string)trim($this->_currentTagContents); $valueFlag = true; break; case 'dateTime.iso8601': $value = new IXR_Date(trim($this->_currentTagContents)); $valueFlag = true; break; case 'value': // "If no type is indicated, the type is string." if (trim($this->_currentTagContents) != '') { $value = (string)$this->_currentTagContents; $valueFlag = true; } break; case 'boolean': $value = (boolean)trim($this->_currentTagContents); $valueFlag = true; break; case 'base64': $value = base64_decode($this->_currentTagContents); $valueFlag = true; break; /* Deal with stacks of arrays and structs */ case 'data': case 'struct': $value = array_pop($this->_arraystructs); array_pop($this->_arraystructstypes); $valueFlag = true; break; case 'member': array_pop($this->_currentStructName); break; case 'name': $this->_currentStructName[] = trim($this->_currentTagContents); break; case 'methodName': $this->methodName = trim($this->_currentTagContents); break; } if ($valueFlag) { if (count($this->_arraystructs) > 0) { // Add value to struct or array if ($this->_arraystructstypes[count($this->_arraystructstypes)-1] == 'struct') { // Add to struct $this->_arraystructs[count($this->_arraystructs)-1][$this->_currentStructName[count($this->_currentStructName)-1]] = $value; } else { // Add to array $this->_arraystructs[count($this->_arraystructs)-1][] = $value; } } else { // Just add as a parameter $this->params[] = $value; } } $this->_currentTagContents = ''; } } ``` | Version | Description | | --- | --- | | [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. | wordpress class WP_Customize_Image_Control {} class WP\_Customize\_Image\_Control {} ====================================== Customize Image Control class. * [WP\_Customize\_Upload\_Control](wp_customize_upload_control) * [add\_tab](wp_customize_image_control/add_tab) β€” deprecated * [prepare\_control](wp_customize_image_control/prepare_control) β€” deprecated * [print\_tab\_image](wp_customize_image_control/print_tab_image) β€” deprecated * [remove\_tab](wp_customize_image_control/remove_tab) β€” deprecated File: `wp-includes/customize/class-wp-customize-image-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-image-control.php/) ``` class WP_Customize_Image_Control extends WP_Customize_Upload_Control { /** * Control type. * * @since 3.4.0 * @var string */ public $type = 'image'; /** * Media control mime type. * * @since 4.1.0 * @var string */ public $mime_type = 'image'; /** * @since 3.4.2 * @deprecated 4.1.0 */ public function prepare_control() {} /** * @since 3.4.0 * @deprecated 4.1.0 * * @param string $id * @param string $label * @param mixed $callback */ public function add_tab( $id, $label, $callback ) { _deprecated_function( __METHOD__, '4.1.0' ); } /** * @since 3.4.0 * @deprecated 4.1.0 * * @param string $id */ public function remove_tab( $id ) { _deprecated_function( __METHOD__, '4.1.0' ); } /** * @since 3.4.0 * @deprecated 4.1.0 * * @param string $url * @param string $thumbnail_url */ public function print_tab_image( $url, $thumbnail_url = null ) { _deprecated_function( __METHOD__, '4.1.0' ); } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Upload\_Control](wp_customize_upload_control) wp-includes/customize/class-wp-customize-upload-control.php | Customize Upload Control Class. | | Used By | Description | | --- | --- | | [WP\_Customize\_Cropped\_Image\_Control](wp_customize_cropped_image_control) wp-includes/customize/class-wp-customize-cropped-image-control.php | Customize Cropped Image Control class. | | [WP\_Customize\_Background\_Image\_Control](wp_customize_background_image_control) wp-includes/customize/class-wp-customize-background-image-control.php | Customize Background Image Control class. | | [WP\_Customize\_Header\_Image\_Control](wp_customize_header_image_control) wp-includes/customize/class-wp-customize-header-image-control.php | Customize Header Image Control class. | | Version | Description | | --- | --- | | [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. | wordpress class WP_Recovery_Mode_Link_Service {} class WP\_Recovery\_Mode\_Link\_Service {} ========================================== Core class used to generate and handle recovery mode links. * [\_\_construct](wp_recovery_mode_link_service/__construct) β€” WP\_Recovery\_Mode\_Link\_Service constructor. * [generate\_url](wp_recovery_mode_link_service/generate_url) β€” Generates a URL to begin recovery mode. * [get\_recovery\_mode\_begin\_url](wp_recovery_mode_link_service/get_recovery_mode_begin_url) β€” Gets a URL to begin recovery mode. * [handle\_begin\_link](wp_recovery_mode_link_service/handle_begin_link) β€” Enters recovery mode when the user hits wp-login.php with a valid recovery mode link. File: `wp-includes/class-wp-recovery-mode-link-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-link-service.php/) ``` class WP_Recovery_Mode_Link_Service { const LOGIN_ACTION_ENTER = 'enter_recovery_mode'; const LOGIN_ACTION_ENTERED = 'entered_recovery_mode'; /** * Service to generate and validate recovery mode keys. * * @since 5.2.0 * @var WP_Recovery_Mode_Key_Service */ private $key_service; /** * Service to handle cookies. * * @since 5.2.0 * @var WP_Recovery_Mode_Cookie_Service */ private $cookie_service; /** * WP_Recovery_Mode_Link_Service constructor. * * @since 5.2.0 * * @param WP_Recovery_Mode_Cookie_Service $cookie_service Service to handle setting the recovery mode cookie. * @param WP_Recovery_Mode_Key_Service $key_service Service to handle generating recovery mode keys. */ public function __construct( WP_Recovery_Mode_Cookie_Service $cookie_service, WP_Recovery_Mode_Key_Service $key_service ) { $this->cookie_service = $cookie_service; $this->key_service = $key_service; } /** * Generates a URL to begin recovery mode. * * Only one recovery mode URL can may be valid at the same time. * * @since 5.2.0 * * @return string Generated URL. */ public function generate_url() { $token = $this->key_service->generate_recovery_mode_token(); $key = $this->key_service->generate_and_store_recovery_mode_key( $token ); return $this->get_recovery_mode_begin_url( $token, $key ); } /** * Enters recovery mode when the user hits wp-login.php with a valid recovery mode link. * * @since 5.2.0 * * @global string $pagenow The filename of the current screen. * * @param int $ttl Number of seconds the link should be valid for. */ public function handle_begin_link( $ttl ) { if ( ! isset( $GLOBALS['pagenow'] ) || 'wp-login.php' !== $GLOBALS['pagenow'] ) { return; } if ( ! isset( $_GET['action'], $_GET['rm_token'], $_GET['rm_key'] ) || self::LOGIN_ACTION_ENTER !== $_GET['action'] ) { return; } if ( ! function_exists( 'wp_generate_password' ) ) { require_once ABSPATH . WPINC . '/pluggable.php'; } $validated = $this->key_service->validate_recovery_mode_key( $_GET['rm_token'], $_GET['rm_key'], $ttl ); if ( is_wp_error( $validated ) ) { wp_die( $validated, '' ); } $this->cookie_service->set_cookie(); $url = add_query_arg( 'action', self::LOGIN_ACTION_ENTERED, wp_login_url() ); wp_redirect( $url ); die; } /** * Gets a URL to begin recovery mode. * * @since 5.2.0 * * @param string $token Recovery Mode token created by {@see generate_recovery_mode_token()}. * @param string $key Recovery Mode key created by {@see generate_and_store_recovery_mode_key()}. * @return string Recovery mode begin URL. */ private function get_recovery_mode_begin_url( $token, $key ) { $url = add_query_arg( array( 'action' => self::LOGIN_ACTION_ENTER, 'rm_token' => $token, 'rm_key' => $key, ), wp_login_url() ); /** * Filters the URL to begin recovery mode. * * @since 5.2.0 * * @param string $url The generated recovery mode begin URL. * @param string $token The token used to identify the key. * @param string $key The recovery mode key. */ return apply_filters( 'recovery_mode_begin_url', $url, $token, $key ); } } ``` | Version | Description | | --- | --- | | [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. | wordpress class WP_User_Search {} class WP\_User\_Search {} ========================= This class has been deprecated. Use [WP\_User\_Query](wp_user_query) instead. WordPress User Search class. * [\_\_construct](wp_user_search/__construct) β€” PHP5 Constructor - Sets up the object properties. * [do\_paging](wp_user_search/do_paging) β€” Handles paging for the user search query. * [get\_results](wp_user_search/get_results) β€” Retrieves the user search query results. * [is\_search](wp_user_search/is_search) β€” Whether there are search terms. * [page\_links](wp_user_search/page_links) β€” Displaying paging text. * [prepare\_query](wp_user_search/prepare_query) β€” Prepares the user search query (legacy). * [prepare\_vars\_for\_template\_usage](wp_user_search/prepare_vars_for_template_usage) β€” Prepares variables for use in templates. * [query](wp_user_search/query) β€” Executes the user search query. * [results\_are\_paged](wp_user_search/results_are_paged) β€” Whether paging is enabled. * [WP\_User\_Search](wp_user_search/wp_user_search) β€” PHP4 Constructor - Sets up the object properties. File: `wp-admin/includes/deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/deprecated.php/) ``` class WP_User_Search { /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var mixed */ var $results; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var string */ var $search_term; /** * Page number. * * @since 2.1.0 * @access private * @var int */ var $page; /** * Role name that users have. * * @since 2.5.0 * @access private * @var string */ var $role; /** * Raw page number. * * @since 2.1.0 * @access private * @var int|bool */ var $raw_page; /** * Amount of users to display per page. * * @since 2.1.0 * @access public * @var int */ var $users_per_page = 50; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var int */ var $first_user; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var int */ var $last_user; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var string */ var $query_limit; /** * {@internal Missing Description}} * * @since 3.0.0 * @access private * @var string */ var $query_orderby; /** * {@internal Missing Description}} * * @since 3.0.0 * @access private * @var string */ var $query_from; /** * {@internal Missing Description}} * * @since 3.0.0 * @access private * @var string */ var $query_where; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var int */ var $total_users_for_query = 0; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var bool */ var $too_many_total_users = false; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var WP_Error */ var $search_errors; /** * {@internal Missing Description}} * * @since 2.7.0 * @access private * @var string */ var $paging_text; /** * PHP5 Constructor - Sets up the object properties. * * @since 2.1.0 * * @param string $search_term Search terms string. * @param int $page Optional. Page ID. * @param string $role Role name. * @return WP_User_Search */ function __construct( $search_term = '', $page = '', $role = '' ) { _deprecated_function( __FUNCTION__, '3.1.0', 'WP_User_Query' ); $this->search_term = wp_unslash( $search_term ); $this->raw_page = ( '' == $page ) ? false : (int) $page; $this->page = ( '' == $page ) ? 1 : (int) $page; $this->role = $role; $this->prepare_query(); $this->query(); $this->do_paging(); } /** * PHP4 Constructor - Sets up the object properties. * * @since 2.1.0 * * @param string $search_term Search terms string. * @param int $page Optional. Page ID. * @param string $role Role name. * @return WP_User_Search */ public function WP_User_Search( $search_term = '', $page = '', $role = '' ) { self::__construct( $search_term, $page, $role ); } /** * Prepares the user search query (legacy). * * @since 2.1.0 * @access public */ public function prepare_query() { global $wpdb; $this->first_user = ($this->page - 1) * $this->users_per_page; $this->query_limit = $wpdb->prepare(" LIMIT %d, %d", $this->first_user, $this->users_per_page); $this->query_orderby = ' ORDER BY user_login'; $search_sql = ''; if ( $this->search_term ) { $searches = array(); $search_sql = 'AND ('; foreach ( array('user_login', 'user_nicename', 'user_email', 'user_url', 'display_name') as $col ) $searches[] = $wpdb->prepare( $col . ' LIKE %s', '%' . like_escape($this->search_term) . '%' ); $search_sql .= implode(' OR ', $searches); $search_sql .= ')'; } $this->query_from = " FROM $wpdb->users"; $this->query_where = " WHERE 1=1 $search_sql"; if ( $this->role ) { $this->query_from .= " INNER JOIN $wpdb->usermeta ON $wpdb->users.ID = $wpdb->usermeta.user_id"; $this->query_where .= $wpdb->prepare(" AND $wpdb->usermeta.meta_key = '{$wpdb->prefix}capabilities' AND $wpdb->usermeta.meta_value LIKE %s", '%' . $this->role . '%'); } elseif ( is_multisite() ) { $level_key = $wpdb->prefix . 'capabilities'; // WPMU site admins don't have user_levels. $this->query_from .= ", $wpdb->usermeta"; $this->query_where .= " AND $wpdb->users.ID = $wpdb->usermeta.user_id AND meta_key = '{$level_key}'"; } do_action_ref_array( 'pre_user_search', array( &$this ) ); } /** * Executes the user search query. * * @since 2.1.0 * @access public */ public function query() { global $wpdb; $this->results = $wpdb->get_col("SELECT DISTINCT($wpdb->users.ID)" . $this->query_from . $this->query_where . $this->query_orderby . $this->query_limit); if ( $this->results ) $this->total_users_for_query = $wpdb->get_var("SELECT COUNT(DISTINCT($wpdb->users.ID))" . $this->query_from . $this->query_where); // No limit. else $this->search_errors = new WP_Error('no_matching_users_found', __('No users found.')); } /** * Prepares variables for use in templates. * * @since 2.1.0 * @access public */ function prepare_vars_for_template_usage() {} /** * Handles paging for the user search query. * * @since 2.1.0 * @access public */ public function do_paging() { if ( $this->total_users_for_query > $this->users_per_page ) { // Have to page the results. $args = array(); if ( ! empty($this->search_term) ) $args['usersearch'] = urlencode($this->search_term); if ( ! empty($this->role) ) $args['role'] = urlencode($this->role); $this->paging_text = paginate_links( array( 'total' => ceil($this->total_users_for_query / $this->users_per_page), 'current' => $this->page, 'base' => 'users.php?%_%', 'format' => 'userspage=%#%', 'add_args' => $args ) ); if ( $this->paging_text ) { $this->paging_text = sprintf( /* translators: 1: Starting number of users on the current page, 2: Ending number of users, 3: Total number of users. */ '<span class="displaying-num">' . __( 'Displaying %1$s&#8211;%2$s of %3$s' ) . '</span>%s', number_format_i18n( ( $this->page - 1 ) * $this->users_per_page + 1 ), number_format_i18n( min( $this->page * $this->users_per_page, $this->total_users_for_query ) ), number_format_i18n( $this->total_users_for_query ), $this->paging_text ); } } } /** * Retrieves the user search query results. * * @since 2.1.0 * @access public * * @return array */ public function get_results() { return (array) $this->results; } /** * Displaying paging text. * * @see do_paging() Builds paging text. * * @since 2.1.0 * @access public */ function page_links() { echo $this->paging_text; } /** * Whether paging is enabled. * * @see do_paging() Builds paging text. * * @since 2.1.0 * @access public * * @return bool */ function results_are_paged() { if ( $this->paging_text ) return true; return false; } /** * Whether there are search terms. * * @since 2.1.0 * @access public * * @return bool */ function is_search() { if ( $this->search_term ) return true; return false; } } ``` | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Use [WP\_User\_Query](wp_user_query) | | [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
programming_docs
wordpress class WP_Widget_Media {} class WP\_Widget\_Media {} ========================== Core class that implements a media widget. * [WP\_Widget](wp_widget) * [\_\_construct](wp_widget_media/__construct) β€” Constructor. * [\_register\_one](wp_widget_media/_register_one) β€” Add hooks while registering all widget instances of this widget class. * [display\_media\_state](wp_widget_media/display_media_state) β€” Filters the default media display states for items in the Media list table. * [enqueue\_admin\_scripts](wp_widget_media/enqueue_admin_scripts) β€” Loads the required scripts and styles for the widget control. * [enqueue\_preview\_scripts](wp_widget_media/enqueue_preview_scripts) β€” Enqueue preview scripts. * [form](wp_widget_media/form) β€” Outputs the settings update form. * [get\_default\_description](wp_widget_media/get_default_description) β€” Returns the default description of the widget. * [get\_instance\_schema](wp_widget_media/get_instance_schema) β€” Get schema for properties of a widget instance (item). * [get\_l10n\_defaults](wp_widget_media/get_l10n_defaults) β€” Returns the default localized strings used by the widget. * [has\_content](wp_widget_media/has_content) β€” Whether the widget has content to show. * [is\_attachment\_with\_mime\_type](wp_widget_media/is_attachment_with_mime_type) β€” Determine if the supplied attachment is for a valid attachment post with the specified MIME type. * [render\_control\_template\_scripts](wp_widget_media/render_control_template_scripts) β€” Render form template scripts. * [render\_media](wp_widget_media/render_media) β€” Render the media on the frontend. * [reset\_default\_labels](wp_widget_media/reset_default_labels) β€” Resets the cache for the default labels. * [sanitize\_token\_list](wp_widget_media/sanitize_token_list) β€” Sanitize a token list string, such as used in HTML rel and class attributes. * [update](wp_widget_media/update) β€” Sanitizes the widget form values as they are saved. * [widget](wp_widget_media/widget) β€” Displays the widget on the front-end. 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 class WP_Widget_Media extends WP_Widget { /** * Translation labels. * * @since 4.8.0 * @var array */ public $l10n = array( 'add_to_widget' => '', 'replace_media' => '', 'edit_media' => '', 'media_library_state_multi' => '', 'media_library_state_single' => '', 'missing_attachment' => '', 'no_media_selected' => '', 'add_media' => '', ); /** * Whether or not the widget has been registered yet. * * @since 4.8.1 * @var bool */ protected $registered = false; /** * The default widget description. * * @since 6.0.0 * @var string */ protected static $default_description = ''; /** * The default localized strings used by the widget. * * @since 6.0.0 * @var string[] */ protected static $l10n_defaults = array(); /** * Constructor. * * @since 4.8.0 * * @param string $id_base Base ID for the widget, lowercase and unique. * @param string $name Name for the widget displayed on the configuration page. * @param array $widget_options Optional. Widget options. See wp_register_sidebar_widget() for * information on accepted arguments. Default empty array. * @param array $control_options Optional. Widget control options. See wp_register_widget_control() * for information on accepted arguments. Default empty array. */ 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 ); } /** * Add hooks while registering all widget instances of this widget class. * * @since 4.8.0 * * @param int $number Optional. The unique order number of this widget instance * compared to other instances of the same class. Default -1. */ 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 ); } /** * Get schema for properties of a widget instance (item). * * @since 4.8.0 * * @see WP_REST_Controller::get_item_schema() * @see WP_REST_Controller::get_additional_fields() * @link https://core.trac.wordpress.org/ticket/35574 * * @return array Schema for properties. */ 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; } /** * Determine if the supplied attachment is for a valid attachment post with the specified MIME type. * * @since 4.8.0 * * @param int|WP_Post $attachment Attachment post ID or object. * @param string $mime_type MIME type. * @return bool Is matching MIME type. */ 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 ); } /** * Sanitize a token list string, such as used in HTML rel and class attributes. * * @since 4.8.0 * * @link http://w3c.github.io/html/infrastructure.html#space-separated-tokens * @link https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList * @param string|array $tokens List of tokens separated by spaces, or an array of tokens. * @return string Sanitized token string list. */ 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 ); } /** * Displays the widget on the front-end. * * @since 4.8.0 * * @see WP_Widget::widget() * * @param array $args Display arguments including before_title, after_title, before_widget, and after_widget. * @param array $instance Saved setting from the database. */ 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']; } /** * Sanitizes the widget form values as they are saved. * * @since 4.8.0 * @since 5.9.0 Renamed `$instance` to `$old_instance` to match parent class * for PHP 8 named parameter support. * * @see WP_Widget::update() * @see WP_REST_Request::has_valid_params() * @see WP_REST_Request::sanitize_params() * * @param array $new_instance Values just sent to be saved. * @param array $old_instance Previously saved values from database. * @return array Updated safe values to be saved. */ 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; } /** * Render the media on the frontend. * * @since 4.8.0 * * @param array $instance Widget instance props. */ abstract public function render_media( $instance ); /** * Outputs the settings update form. * * Note that the widget UI itself is rendered with JavaScript via `MediaWidgetControl#render()`. * * @since 4.8.0 * * @see \WP_Widget_Media::render_control_template_scripts() Where the JS template is located. * * @param array $instance Current settings. */ 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; } /** * Filters the default media display states for items in the Media list table. * * @since 4.8.0 * * @param array $states An array of media states. * @param WP_Post $post The current attachment object. * @return array */ 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; } /** * 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. * * @since 4.8.0 */ public function enqueue_preview_scripts() {} /** * Loads the required scripts and styles for the widget control. * * @since 4.8.0 */ public function enqueue_admin_scripts() { wp_enqueue_media(); wp_enqueue_script( 'media-widgets' ); } /** * Render form template scripts. * * @since 4.8.0 */ 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 } /** * Resets the cache for the default labels. * * @since 6.0.0 */ public static function reset_default_labels() { self::$default_description = ''; self::$l10n_defaults = array(); } /** * Whether the widget has content to show. * * @since 4.8.0 * * @param array $instance Widget instance props. * @return bool Whether widget has content. */ protected function has_content( $instance ) { return ( $instance['attachment_id'] && 'attachment' === get_post_type( $instance['attachment_id'] ) ) || $instance['url']; } /** * Returns the default description of the widget. * * @since 6.0.0 * * @return string */ protected static function get_default_description() { if ( self::$default_description ) { return self::$default_description; } self::$default_description = __( 'A media item.' ); return self::$default_description; } /** * Returns the default localized strings used by the widget. * * @since 6.0.0 * * @return (string|array)[] */ 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 | | --- | --- | | [WP\_Widget](wp_widget) wp-includes/class-wp-widget.php | Core base class extended to register widgets. | | Used By | Description | | --- | --- | | [WP\_Widget\_Media\_Gallery](wp_widget_media_gallery) wp-includes/widgets/class-wp-widget-media-gallery.php | Core class that implements a gallery widget. | | [WP\_Widget\_Media\_Audio](wp_widget_media_audio) wp-includes/widgets/class-wp-widget-media-audio.php | Core class that implements an audio widget. | | [WP\_Widget\_Media\_Video](wp_widget_media_video) wp-includes/widgets/class-wp-widget-media-video.php | Core class that implements a video widget. | | [WP\_Widget\_Media\_Image](wp_widget_media_image) wp-includes/widgets/class-wp-widget-media-image.php | Core class that implements an image widget. | | Version | Description | | --- | --- | | [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. | wordpress class WP_Post_Comments_List_Table {} class WP\_Post\_Comments\_List\_Table {} ======================================== Core class used to implement displaying post comments in a list table. * [WP\_Comments\_List\_Table](wp_comments_list_table) * [display](wp_post_comments_list_table/display) * [get\_column\_info](wp_post_comments_list_table/get_column_info) * [get\_per\_page](wp_post_comments_list_table/get_per_page) * [get\_table\_classes](wp_post_comments_list_table/get_table_classes) File: `wp-admin/includes/class-wp-post-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-post-comments-list-table.php/) ``` class WP_Post_Comments_List_Table extends WP_Comments_List_Table { /** * @return array */ protected function get_column_info() { return array( array( 'author' => __( 'Author' ), 'comment' => _x( 'Comment', 'column name' ), ), array(), array(), 'comment', ); } /** * @return array */ protected function get_table_classes() { $classes = parent::get_table_classes(); $classes[] = 'wp-list-table'; $classes[] = 'comments-box'; return $classes; } /** * @param bool $output_empty */ public function display( $output_empty = false ) { $singular = $this->_args['singular']; wp_nonce_field( 'fetch-list-' . get_class( $this ), '_ajax_fetch_list_nonce' ); ?> <table class="<?php echo implode( ' ', $this->get_table_classes() ); ?>" style="display:none;"> <tbody id="the-comment-list" <?php if ( $singular ) { echo " data-wp-lists='list:$singular'"; } ?> > <?php if ( ! $output_empty ) { $this->display_rows_or_placeholder(); } ?> </tbody> </table> <?php } /** * @param bool $comment_status * @return int */ public function get_per_page( $comment_status = false ) { return 10; } } ``` | Uses | Description | | --- | --- | | [WP\_Comments\_List\_Table](wp_comments_list_table) wp-admin/includes/class-wp-comments-list-table.php | Core class used to implement displaying comments in a list table. | | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
programming_docs
wordpress class File_Upload_Upgrader {} class File\_Upload\_Upgrader {} =============================== Core class used for handling file uploads. This class handles the upload process and passes it as if it’s a local file to the Upgrade/Installer functions. * [\_\_construct](file_upload_upgrader/__construct) β€” Construct the upgrader for a form. * [cleanup](file_upload_upgrader/cleanup) β€” Delete the attachment/uploaded file. File: `wp-admin/includes/class-file-upload-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-file-upload-upgrader.php/) ``` class File_Upload_Upgrader { /** * The full path to the file package. * * @since 2.8.0 * @var string $package */ public $package; /** * The name of the file. * * @since 2.8.0 * @var string $filename */ public $filename; /** * The ID of the attachment post for this file. * * @since 3.3.0 * @var int $id */ public $id = 0; /** * Construct the upgrader for a form. * * @since 2.8.0 * * @param string $form The name of the form the file was uploaded from. * @param string $urlholder The name of the `GET` parameter that holds the filename. */ public function __construct( $form, $urlholder ) { if ( empty( $_FILES[ $form ]['name'] ) && empty( $_GET[ $urlholder ] ) ) { wp_die( __( 'Please select a file' ) ); } // Handle a newly uploaded file. Else, assume it's already been uploaded. if ( ! empty( $_FILES ) ) { $overrides = array( 'test_form' => false, 'test_type' => false, ); $file = wp_handle_upload( $_FILES[ $form ], $overrides ); if ( isset( $file['error'] ) ) { wp_die( $file['error'] ); } $this->filename = $_FILES[ $form ]['name']; $this->package = $file['file']; // Construct the attachment array. $attachment = array( 'post_title' => $this->filename, 'post_content' => $file['url'], 'post_mime_type' => $file['type'], 'guid' => $file['url'], 'context' => 'upgrader', 'post_status' => 'private', ); // Save the data. $this->id = wp_insert_attachment( $attachment, $file['file'] ); // Schedule a cleanup for 2 hours from now in case of failed installation. wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $this->id ) ); } elseif ( is_numeric( $_GET[ $urlholder ] ) ) { // Numeric Package = previously uploaded file, see above. $this->id = (int) $_GET[ $urlholder ]; $attachment = get_post( $this->id ); if ( empty( $attachment ) ) { wp_die( __( 'Please select a file' ) ); } $this->filename = $attachment->post_title; $this->package = get_attached_file( $attachment->ID ); } else { // Else, It's set to something, Back compat for plugins using the old (pre-3.3) File_Uploader handler. $uploads = wp_upload_dir(); if ( ! ( $uploads && false === $uploads['error'] ) ) { wp_die( $uploads['error'] ); } $this->filename = sanitize_file_name( $_GET[ $urlholder ] ); $this->package = $uploads['basedir'] . '/' . $this->filename; if ( 0 !== strpos( realpath( $this->package ), realpath( $uploads['basedir'] ) ) ) { wp_die( __( 'Please select a file' ) ); } } } /** * Delete the attachment/uploaded file. * * @since 3.2.2 * * @return bool Whether the cleanup was successful. */ public function cleanup() { if ( $this->id ) { wp_delete_attachment( $this->id ); } elseif ( file_exists( $this->package ) ) { return @unlink( $this->package ); } return true; } } ``` | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Moved to its own file from wp-admin/includes/class-wp-upgrader.php. | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. | wordpress class WP_Customize_Nav_Menu_Locations_Control {} class WP\_Customize\_Nav\_Menu\_Locations\_Control {} ===================================================== Customize Nav Menu Locations Control Class. * [WP\_Customize\_Control](wp_customize_control) * [content\_template](wp_customize_nav_menu_locations_control/content_template) β€” JS/Underscore template for the control UI. * [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/) ``` class WP_Customize_Nav_Menu_Locations_Control extends WP_Customize_Control { /** * Control type. * * @since 4.9.0 * @var string */ public $type = 'nav_menu_locations'; /** * Don't render the control's content - it uses a JS template instead. * * @since 4.9.0 */ public function render_content() {} /** * JS/Underscore template for the control UI. * * @since 4.9.0 */ 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&#8217;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 | | --- | --- | | [WP\_Customize\_Control](wp_customize_control) wp-includes/class-wp-customize-control.php | Customize Control class. | | Version | Description | | --- | --- | | [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. | wordpress class WP_Customize_Cropped_Image_Control {} class WP\_Customize\_Cropped\_Image\_Control {} =============================================== Customize Cropped Image Control class. * [WP\_Customize\_Image\_Control](wp_customize_image_control) * [enqueue](wp_customize_cropped_image_control/enqueue) β€” Enqueue control related scripts/styles. * [to\_json](wp_customize_cropped_image_control/to_json) β€” Refresh the parameters passed to the JavaScript via 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/) ``` class WP_Customize_Cropped_Image_Control extends WP_Customize_Image_Control { /** * Control type. * * @since 4.3.0 * @var string */ public $type = 'cropped_image'; /** * Suggested width for cropped image. * * @since 4.3.0 * @var int */ public $width = 150; /** * Suggested height for cropped image. * * @since 4.3.0 * @var int */ public $height = 150; /** * Whether the width is flexible. * * @since 4.3.0 * @var bool */ public $flex_width = false; /** * Whether the height is flexible. * * @since 4.3.0 * @var bool */ public $flex_height = false; /** * Enqueue control related scripts/styles. * * @since 4.3.0 */ public function enqueue() { wp_enqueue_script( 'customize-views' ); parent::enqueue(); } /** * Refresh the parameters passed to the JavaScript via JSON. * * @since 4.3.0 * * @see WP_Customize_Control::to_json() */ 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 | | --- | --- | | [WP\_Customize\_Image\_Control](wp_customize_image_control) wp-includes/customize/class-wp-customize-image-control.php | Customize Image Control class. | | Used By | Description | | --- | --- | | [WP\_Customize\_Site\_Icon\_Control](wp_customize_site_icon_control) wp-includes/customize/class-wp-customize-site-icon-control.php | Customize Site Icon control class. | | Version | Description | | --- | --- | | [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. | wordpress class Requests {} class Requests {} ================= Requests for PHP Inspired by Requests for Python. Based on concepts from SimplePie\_File, RequestCore and [WP\_Http](wp_http). * [\_\_construct](requests/__construct) β€” This is a static class, do not instantiate it * [add\_transport](requests/add_transport) β€” Register a transport * [autoloader](requests/autoloader) β€” Autoloader for Requests * [compatible\_gzinflate](requests/compatible_gzinflate) β€” Decompression of deflated string while staying compatible with the majority of servers. * [decode\_chunked](requests/decode_chunked) β€” Decoded a chunked body as per RFC 2616 * [decompress](requests/decompress) β€” Decompress an encoded body * [delete](requests/delete) β€” Send a DELETE request * [flatten](requests/flatten) β€” Convert a key => value array to a 'key: value' array for headers * [flattern](requests/flattern) β€” Convert a key => value array to a 'key: value' array for headers β€” deprecated * [get](requests/get) β€” Send a GET request * [get\_certificate\_path](requests/get_certificate_path) β€” Get default certificate path. * [get\_default\_options](requests/get_default_options) β€” Get the default options * [get\_transport](requests/get_transport) β€” Get a working transport * [head](requests/head) β€” Send a HEAD request * [match\_domain](requests/match_domain) * [options](requests/options) β€” Send an OPTIONS request * [parse\_multiple](requests/parse_multiple) β€” Callback for `transport.internal.parse\_response` * [parse\_response](requests/parse_response) β€” HTTP response parser * [patch](requests/patch) β€” Send a PATCH request * [post](requests/post) β€” Send a POST request * [put](requests/put) β€” Send a PUT request * [register\_autoloader](requests/register_autoloader) β€” Register the built-in autoloader * [request](requests/request) β€” Main interface for HTTP requests * [request\_multiple](requests/request_multiple) β€” Send multiple HTTP requests simultaneously * [set\_certificate\_path](requests/set_certificate_path) β€” Set default certificate path. * [set\_defaults](requests/set_defaults) β€” Set the default values * [trace](requests/trace) β€” Send a TRACE request File: `wp-includes/class-requests.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-requests.php/) ``` class Requests { /** * POST method * * @var string */ const POST = 'POST'; /** * PUT method * * @var string */ const PUT = 'PUT'; /** * GET method * * @var string */ const GET = 'GET'; /** * HEAD method * * @var string */ const HEAD = 'HEAD'; /** * DELETE method * * @var string */ const DELETE = 'DELETE'; /** * OPTIONS method * * @var string */ const OPTIONS = 'OPTIONS'; /** * TRACE method * * @var string */ const TRACE = 'TRACE'; /** * PATCH method * * @link https://tools.ietf.org/html/rfc5789 * @var string */ const PATCH = 'PATCH'; /** * Default size of buffer size to read streams * * @var integer */ const BUFFER_SIZE = 1160; /** * Current version of Requests * * @var string */ const VERSION = '1.8.1'; /** * Registered transport classes * * @var array */ protected static $transports = array(); /** * Selected transport name * * Use {@see get_transport()} instead * * @var array */ public static $transport = array(); /** * Default certificate path. * * @see Requests::get_certificate_path() * @see Requests::set_certificate_path() * * @var string */ protected static $certificate_path; /** * This is a static class, do not instantiate it * * @codeCoverageIgnore */ private function __construct() {} /** * Autoloader for Requests * * Register this with {@see 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.) * * @codeCoverageIgnore * * @param string $class Class name to load */ 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'; } } /** * Register the built-in autoloader * * @codeCoverageIgnore */ public static function register_autoloader() { spl_autoload_register(array('Requests', 'autoloader')); } /** * Register a transport * * @param string $transport Transport class to add, must support the Requests_Transport interface */ 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)); } /** * Get a working transport * * @throws Requests_Exception If no valid transport is found (`notransport`) * @return Requests_Transport */ 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(); } /**#@+ * @see request() * @param string $url * @param array $headers * @param array $options * @return Requests_Response */ /** * Send a GET request */ public static function get($url, $headers = array(), $options = array()) { return self::request($url, $headers, null, self::GET, $options); } /** * Send a HEAD request */ public static function head($url, $headers = array(), $options = array()) { return self::request($url, $headers, null, self::HEAD, $options); } /** * Send a DELETE request */ public static function delete($url, $headers = array(), $options = array()) { return self::request($url, $headers, null, self::DELETE, $options); } /** * Send a TRACE request */ public static function trace($url, $headers = array(), $options = array()) { return self::request($url, $headers, null, self::TRACE, $options); } /**#@-*/ /**#@+ * @see request() * @param string $url * @param array $headers * @param array $data * @param array $options * @return Requests_Response */ /** * Send a POST request */ public static function post($url, $headers = array(), $data = array(), $options = array()) { return self::request($url, $headers, $data, self::POST, $options); } /** * Send a PUT request */ public static function put($url, $headers = array(), $data = array(), $options = array()) { return self::request($url, $headers, $data, self::PUT, $options); } /** * Send an OPTIONS request */ public static function options($url, $headers = array(), $data = array(), $options = array()) { return self::request($url, $headers, $data, self::OPTIONS, $options); } /** * Send a PATCH request * * Note: Unlike {@see post} and {@see put}, `$headers` is required, as the * specification recommends that should send an ETag * * @link https://tools.ietf.org/html/rfc5789 */ public static function patch($url, $headers, $data = array(), $options = array()) { return self::request($url, $headers, $data, self::PATCH, $options); } /**#@-*/ /** * 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 * {@see getTransport()} * (string|Requests_Transport, default: {@see getTransport()}) * - `hooks`: Hooks handler. * (Requests_Hooker, default: new 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) * * @throws Requests_Exception On invalid URLs (`nonhttp`) * * @param string $url URL to request * @param array $headers Extra headers to send with the request * @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests * @param string $type HTTP request type (use Requests constants) * @param array $options Options for the request (see description for more information) * @return Requests_Response */ 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); } /** * 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 * {@see Requests::request} * (string, required) * - `headers`: Associative array of header fields. Same as the `$headers` * parameter to {@see Requests::request} * (array, default: `array()`) * - `data`: Associative array of data fields or a string. Same as the * `$data` parameter to {@see Requests::request} * (array|string, default: `array()`) * - `type`: HTTP request type (use Requests constants). Same as the `$type` * parameter to {@see Requests::request} * (string, default: `Requests::GET`) * - `cookies`: Associative array of cookie name to value, or cookie jar. * (array|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_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) * * @param array $requests Requests data (see description for more information) * @param array $options Global and default options (see {@see Requests::request}) * @return array Responses (either Requests_Response or a Requests_Exception object) */ 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; } /** * Get the default options * * @see Requests::request() for values returned by this method * @param boolean $multirequest Is this a multirequest? * @return array Default option values */ 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; } /** * Get default certificate path. * * @return string Default certificate path. */ public static function get_certificate_path() { if (!empty(self::$certificate_path)) { return self::$certificate_path; } return dirname(__FILE__) . '/Requests/Transport/cacert.pem'; } /** * Set default certificate path. * * @param string $path Certificate path, pointing to a PEM file. */ public static function set_certificate_path($path) { self::$certificate_path = $path; } /** * Set the default values * * @param string $url URL to request * @param array $headers Extra headers to send with the request * @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests * @param string $type HTTP request type * @param array $options Options for the request * @return array $options */ 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'; } } } /** * HTTP response parser * * @throws Requests_Exception On missing head/body separator (`requests.no_crlf_separator`) * @throws Requests_Exception On missing head/body separator (`noversion`) * @throws Requests_Exception On missing head/body separator (`toomanyredirects`) * * @param string $headers Full response text including headers and body * @param string $url Original request URL * @param array $req_headers Original $headers array passed to {@link request()}, in case we need to follow redirects * @param array $req_data Original $data array passed to {@link request()}, in case we need to follow redirects * @param array $options Original $options array passed to {@link request()}, in case we need to follow redirects * @return Requests_Response */ 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; } /** * Callback for `transport.internal.parse_response` * * Internal use only. Converts a raw HTTP response to a Requests_Response * while still executing a multiple request. * * @param string $response Full response text including headers and body (will be overwritten with Response instance) * @param array $request Request data as passed into {@see Requests::request_multiple()} * @return null `$response` is either set to a Requests_Response instance, or a Requests_Exception object */ 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; } } /** * Decoded a chunked body as per RFC 2616 * * @see https://tools.ietf.org/html/rfc2616#section-3.6.1 * @param string $data Chunked body * @return string Decoded body */ 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 } // @codeCoverageIgnoreEnd /** * Convert a key => value array to a 'key: value' array for headers * * @param array $array Dictionary of header values * @return array List of headers */ public static function flatten($array) { $return = array(); foreach ($array as $key => $value) { $return[] = sprintf('%s: %s', $key, $value); } return $return; } /** * Convert a key => value array to a 'key: value' array for headers * * @codeCoverageIgnore * @deprecated Misspelling of {@see Requests::flatten} * @param array $array Dictionary of header values * @return array List of headers */ public static function flattern($array) { return self::flatten($array); } /** * Decompress an encoded body * * Implements gzip, compress and deflate. Guesses which it is by attempting * to decode. * * @param string $data Compressed data in one of the above formats * @return string Decompressed string */ 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; } /** * 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 * * @since 2.8.1 * @link https://core.trac.wordpress.org/ticket/18273 * @link https://secure.php.net/manual/en/function.gzinflate.php#70875 * @link https://secure.php.net/manual/en/function.gzinflate.php#77336 * * @param string $gz_data String to decompress. * @return string|bool False on failure. */ 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; } 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; } } ```
programming_docs
wordpress class WP_Widget_Categories {} class WP\_Widget\_Categories {} =============================== Core class used to implement a Categories widget. * [WP\_Widget](wp_widget) * [\_\_construct](wp_widget_categories/__construct) β€” Sets up a new Categories widget instance. * [form](wp_widget_categories/form) β€” Outputs the settings form for the Categories widget. * [update](wp_widget_categories/update) β€” Handles updating settings for the current Categories widget instance. * [widget](wp_widget_categories/widget) β€” Outputs the content for the current Categories widget instance. File: `wp-includes/widgets/class-wp-widget-categories.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-categories.php/) ``` class WP_Widget_Categories extends WP_Widget { /** * Sets up a new Categories widget instance. * * @since 2.8.0 */ public function __construct() { $widget_ops = array( 'classname' => 'widget_categories', 'description' => __( 'A list or dropdown of categories.' ), 'customize_selective_refresh' => true, 'show_instance_in_rest' => true, ); parent::__construct( 'categories', __( 'Categories' ), $widget_ops ); } /** * Outputs the content for the current Categories widget instance. * * @since 2.8.0 * @since 4.2.0 Creates a unique HTML ID for the `<select>` element * if more than one instance is displayed on the page. * * @param array $args Display arguments including 'before_title', 'after_title', * 'before_widget', and 'after_widget'. * @param array $instance Settings for the current Categories widget instance. */ public function widget( $args, $instance ) { static $first_dropdown = true; $default_title = __( 'Categories' ); $title = ! empty( $instance['title'] ) ? $instance['title'] : $default_title; /** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */ $title = apply_filters( 'widget_title', $title, $instance, $this->id_base ); $count = ! empty( $instance['count'] ) ? '1' : '0'; $hierarchical = ! empty( $instance['hierarchical'] ) ? '1' : '0'; $dropdown = ! empty( $instance['dropdown'] ) ? '1' : '0'; echo $args['before_widget']; if ( $title ) { echo $args['before_title'] . $title . $args['after_title']; } $cat_args = array( 'orderby' => 'name', 'show_count' => $count, 'hierarchical' => $hierarchical, ); if ( $dropdown ) { printf( '<form action="%s" method="get">', esc_url( home_url() ) ); $dropdown_id = ( $first_dropdown ) ? 'cat' : "{$this->id_base}-dropdown-{$this->number}"; $first_dropdown = false; echo '<label class="screen-reader-text" for="' . esc_attr( $dropdown_id ) . '">' . $title . '</label>'; $cat_args['show_option_none'] = __( 'Select Category' ); $cat_args['id'] = $dropdown_id; /** * Filters the arguments for the Categories widget drop-down. * * @since 2.8.0 * @since 4.9.0 Added the `$instance` parameter. * * @see wp_dropdown_categories() * * @param array $cat_args An array of Categories widget drop-down arguments. * @param array $instance Array of settings for the current widget. */ wp_dropdown_categories( apply_filters( 'widget_categories_dropdown_args', $cat_args, $instance ) ); echo '</form>'; $type_attr = current_theme_supports( 'html5', 'script' ) ? '' : ' type="text/javascript"'; ?> <script<?php echo $type_attr; ?>> /* <![CDATA[ */ (function() { var dropdown = document.getElementById( "<?php echo esc_js( $dropdown_id ); ?>" ); function onCatChange() { if ( dropdown.options[ dropdown.selectedIndex ].value > 0 ) { dropdown.parentNode.submit(); } } dropdown.onchange = onCatChange; })(); /* ]]> */ </script> <?php } else { $format = current_theme_supports( 'html5', 'navigation-widgets' ) ? 'html5' : 'xhtml'; /** This filter is documented in wp-includes/widgets/class-wp-nav-menu-widget.php */ $format = apply_filters( 'navigation_widgets_format', $format ); if ( 'html5' === $format ) { // The title may be filtered: Strip out HTML and make sure the aria-label is never empty. $title = trim( strip_tags( $title ) ); $aria_label = $title ? $title : $default_title; echo '<nav aria-label="' . esc_attr( $aria_label ) . '">'; } ?> <ul> <?php $cat_args['title_li'] = ''; /** * Filters the arguments for the Categories widget. * * @since 2.8.0 * @since 4.9.0 Added the `$instance` parameter. * * @param array $cat_args An array of Categories widget options. * @param array $instance Array of settings for the current widget. */ wp_list_categories( apply_filters( 'widget_categories_args', $cat_args, $instance ) ); ?> </ul> <?php if ( 'html5' === $format ) { echo '</nav>'; } } echo $args['after_widget']; } /** * Handles updating settings for the current Categories widget instance. * * @since 2.8.0 * * @param array $new_instance New settings for this instance as input by the user via * WP_Widget::form(). * @param array $old_instance Old settings for this instance. * @return array Updated settings to save. */ public function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = sanitize_text_field( $new_instance['title'] ); $instance['count'] = ! empty( $new_instance['count'] ) ? 1 : 0; $instance['hierarchical'] = ! empty( $new_instance['hierarchical'] ) ? 1 : 0; $instance['dropdown'] = ! empty( $new_instance['dropdown'] ) ? 1 : 0; return $instance; } /** * Outputs the settings form for the Categories widget. * * @since 2.8.0 * * @param array $instance Current settings. */ public function form( $instance ) { // Defaults. $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) ); $count = isset( $instance['count'] ) ? (bool) $instance['count'] : false; $hierarchical = isset( $instance['hierarchical'] ) ? (bool) $instance['hierarchical'] : false; $dropdown = isset( $instance['dropdown'] ) ? (bool) $instance['dropdown'] : false; ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $instance['title'] ); ?>" /> </p> <p> <input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'dropdown' ); ?>" name="<?php echo $this->get_field_name( 'dropdown' ); ?>"<?php checked( $dropdown ); ?> /> <label for="<?php echo $this->get_field_id( 'dropdown' ); ?>"><?php _e( 'Display as dropdown' ); ?></label> <br /> <input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>"<?php checked( $count ); ?> /> <label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php _e( 'Show post counts' ); ?></label> <br /> <input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'hierarchical' ); ?>" name="<?php echo $this->get_field_name( 'hierarchical' ); ?>"<?php checked( $hierarchical ); ?> /> <label for="<?php echo $this->get_field_id( 'hierarchical' ); ?>"><?php _e( 'Show hierarchy' ); ?></label> </p> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Widget](wp_widget) wp-includes/class-wp-widget.php | Core base class extended to register widgets. | | Version | Description | | --- | --- | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. | wordpress class WP_Filesystem_Direct {} class WP\_Filesystem\_Direct {} =============================== WordPress Filesystem Class for direct PHP file and folder manipulation. * [WP\_Filesystem\_Base](wp_filesystem_base) * [\_\_construct](wp_filesystem_direct/__construct) β€” Constructor. * [atime](wp_filesystem_direct/atime) β€” Gets the file's last access time. * [chdir](wp_filesystem_direct/chdir) β€” Changes current directory. * [chgrp](wp_filesystem_direct/chgrp) β€” Changes the file group. * [chmod](wp_filesystem_direct/chmod) β€” Changes filesystem permissions. * [chown](wp_filesystem_direct/chown) β€” Changes the owner of a file or directory. * [copy](wp_filesystem_direct/copy) β€” Copies a file. * [cwd](wp_filesystem_direct/cwd) β€” Gets the current working directory. * [delete](wp_filesystem_direct/delete) β€” Deletes a file or directory. * [dirlist](wp_filesystem_direct/dirlist) β€” Gets details for files in a directory or a specific file. * [exists](wp_filesystem_direct/exists) β€” Checks if a file or directory exists. * [get\_contents](wp_filesystem_direct/get_contents) β€” Reads entire file into a string. * [get\_contents\_array](wp_filesystem_direct/get_contents_array) β€” Reads entire file into an array. * [getchmod](wp_filesystem_direct/getchmod) β€” Gets the permissions of the specified file or filepath in their octal format. * [group](wp_filesystem_direct/group) β€” Gets the file's group. * [is\_dir](wp_filesystem_direct/is_dir) β€” Checks if resource is a directory. * [is\_file](wp_filesystem_direct/is_file) β€” Checks if resource is a file. * [is\_readable](wp_filesystem_direct/is_readable) β€” Checks if a file is readable. * [is\_writable](wp_filesystem_direct/is_writable) β€” Checks if a file or directory is writable. * [mkdir](wp_filesystem_direct/mkdir) β€” Creates a directory. * [move](wp_filesystem_direct/move) β€” Moves a file. * [mtime](wp_filesystem_direct/mtime) β€” Gets the file modification time. * [owner](wp_filesystem_direct/owner) β€” Gets the file owner. * [put\_contents](wp_filesystem_direct/put_contents) β€” Writes a string to a file. * [rmdir](wp_filesystem_direct/rmdir) β€” Deletes a directory. * [size](wp_filesystem_direct/size) β€” Gets the file size (in bytes). * [touch](wp_filesystem_direct/touch) β€” Sets the access and modification times of a file. File: `wp-admin/includes/class-wp-filesystem-direct.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-direct.php/) ``` class WP_Filesystem_Direct extends WP_Filesystem_Base { /** * Constructor. * * @since 2.5.0 * * @param mixed $arg Not used. */ public function __construct( $arg ) { $this->method = 'direct'; $this->errors = new WP_Error(); } /** * Reads entire file into a string. * * @since 2.5.0 * * @param string $file Name of the file to read. * @return string|false Read data on success, false on failure. */ public function get_contents( $file ) { return @file_get_contents( $file ); } /** * Reads entire file into an array. * * @since 2.5.0 * * @param string $file Path to the file. * @return array|false File contents in an array on success, false on failure. */ public function get_contents_array( $file ) { return @file( $file ); } /** * Writes a string to a file. * * @since 2.5.0 * * @param string $file Remote path to the file where to write the data. * @param string $contents The data to write. * @param int|false $mode Optional. The file permissions as octal number, usually 0644. * Default false. * @return bool True on success, false on failure. */ public function put_contents( $file, $contents, $mode = false ) { $fp = @fopen( $file, 'wb' ); if ( ! $fp ) { return false; } mbstring_binary_safe_encoding(); $data_length = strlen( $contents ); $bytes_written = fwrite( $fp, $contents ); reset_mbstring_encoding(); fclose( $fp ); if ( $data_length !== $bytes_written ) { return false; } $this->chmod( $file, $mode ); return true; } /** * Gets the current working directory. * * @since 2.5.0 * * @return string|false The current working directory on success, false on failure. */ public function cwd() { return getcwd(); } /** * Changes current directory. * * @since 2.5.0 * * @param string $dir The new current directory. * @return bool True on success, false on failure. */ public function chdir( $dir ) { return @chdir( $dir ); } /** * Changes the file group. * * @since 2.5.0 * * @param string $file Path to the file. * @param string|int $group A group name or number. * @param bool $recursive Optional. If set to true, changes file group recursively. * Default false. * @return bool True on success, false on failure. */ public function chgrp( $file, $group, $recursive = false ) { if ( ! $this->exists( $file ) ) { return false; } if ( ! $recursive ) { return chgrp( $file, $group ); } if ( ! $this->is_dir( $file ) ) { return chgrp( $file, $group ); } // Is a directory, and we want recursive. $file = trailingslashit( $file ); $filelist = $this->dirlist( $file ); foreach ( $filelist as $filename ) { $this->chgrp( $file . $filename, $group, $recursive ); } return true; } /** * Changes filesystem permissions. * * @since 2.5.0 * * @param string $file Path to the file. * @param int|false $mode Optional. The permissions as octal number, usually 0644 for files, * 0755 for directories. Default false. * @param bool $recursive Optional. If set to true, changes file permissions recursively. * Default false. * @return bool True on success, false on failure. */ public function chmod( $file, $mode = false, $recursive = false ) { if ( ! $mode ) { if ( $this->is_file( $file ) ) { $mode = FS_CHMOD_FILE; } elseif ( $this->is_dir( $file ) ) { $mode = FS_CHMOD_DIR; } else { return false; } } if ( ! $recursive || ! $this->is_dir( $file ) ) { return chmod( $file, $mode ); } // Is a directory, and we want recursive. $file = trailingslashit( $file ); $filelist = $this->dirlist( $file ); foreach ( (array) $filelist as $filename => $filemeta ) { $this->chmod( $file . $filename, $mode, $recursive ); } return true; } /** * Changes the owner of a file or directory. * * @since 2.5.0 * * @param string $file Path to the file or directory. * @param string|int $owner A user name or number. * @param bool $recursive Optional. If set to true, changes file owner recursively. * Default false. * @return bool True on success, false on failure. */ public function chown( $file, $owner, $recursive = false ) { if ( ! $this->exists( $file ) ) { return false; } if ( ! $recursive ) { return chown( $file, $owner ); } if ( ! $this->is_dir( $file ) ) { return chown( $file, $owner ); } // Is a directory, and we want recursive. $filelist = $this->dirlist( $file ); foreach ( $filelist as $filename ) { $this->chown( $file . '/' . $filename, $owner, $recursive ); } return true; } /** * Gets the file owner. * * @since 2.5.0 * * @param string $file Path to the file. * @return string|false Username of the owner on success, false on failure. */ public function owner( $file ) { $owneruid = @fileowner( $file ); if ( ! $owneruid ) { return false; } if ( ! function_exists( 'posix_getpwuid' ) ) { return $owneruid; } $ownerarray = posix_getpwuid( $owneruid ); if ( ! $ownerarray ) { return false; } return $ownerarray['name']; } /** * Gets the permissions of the specified file or filepath in their octal format. * * FIXME does not handle errors in fileperms() * * @since 2.5.0 * * @param string $file Path to the file. * @return string Mode of the file (the last 3 digits). */ public function getchmod( $file ) { return substr( decoct( @fileperms( $file ) ), -3 ); } /** * Gets the file's group. * * @since 2.5.0 * * @param string $file Path to the file. * @return string|false The group on success, false on failure. */ public function group( $file ) { $gid = @filegroup( $file ); if ( ! $gid ) { return false; } if ( ! function_exists( 'posix_getgrgid' ) ) { return $gid; } $grouparray = posix_getgrgid( $gid ); if ( ! $grouparray ) { return false; } return $grouparray['name']; } /** * Copies a file. * * @since 2.5.0 * * @param string $source Path to the source file. * @param string $destination Path to the destination file. * @param bool $overwrite Optional. Whether to overwrite the destination file if it exists. * Default false. * @param int|false $mode Optional. The permissions as octal number, usually 0644 for files, * 0755 for dirs. Default false. * @return bool True on success, false on failure. */ public function copy( $source, $destination, $overwrite = false, $mode = false ) { if ( ! $overwrite && $this->exists( $destination ) ) { return false; } $rtval = copy( $source, $destination ); if ( $mode ) { $this->chmod( $destination, $mode ); } return $rtval; } /** * Moves a file. * * @since 2.5.0 * * @param string $source Path to the source file. * @param string $destination Path to the destination file. * @param bool $overwrite Optional. Whether to overwrite the destination file if it exists. * Default false. * @return bool True on success, false on failure. */ public function move( $source, $destination, $overwrite = false ) { if ( ! $overwrite && $this->exists( $destination ) ) { return false; } // Try using rename first. if that fails (for example, source is read only) try copy. if ( @rename( $source, $destination ) ) { return true; } if ( $this->copy( $source, $destination, $overwrite ) && $this->exists( $destination ) ) { $this->delete( $source ); return true; } else { return false; } } /** * Deletes a file or directory. * * @since 2.5.0 * * @param string $file Path to the file or directory. * @param bool $recursive Optional. If set to true, deletes files and folders recursively. * Default false. * @param string|false $type Type of resource. 'f' for file, 'd' for directory. * Default false. * @return bool True on success, false on failure. */ public function delete( $file, $recursive = false, $type = false ) { if ( empty( $file ) ) { // Some filesystems report this as /, which can cause non-expected recursive deletion of all files in the filesystem. return false; } $file = str_replace( '\\', '/', $file ); // For Win32, occasional problems deleting files otherwise. if ( 'f' === $type || $this->is_file( $file ) ) { return @unlink( $file ); } if ( ! $recursive && $this->is_dir( $file ) ) { return @rmdir( $file ); } // At this point it's a folder, and we're in recursive mode. $file = trailingslashit( $file ); $filelist = $this->dirlist( $file, true ); $retval = true; if ( is_array( $filelist ) ) { foreach ( $filelist as $filename => $fileinfo ) { if ( ! $this->delete( $file . $filename, $recursive, $fileinfo['type'] ) ) { $retval = false; } } } if ( file_exists( $file ) && ! @rmdir( $file ) ) { $retval = false; } return $retval; } /** * Checks if a file or directory exists. * * @since 2.5.0 * * @param string $path Path to file or directory. * @return bool Whether $path exists or not. */ public function exists( $path ) { return @file_exists( $path ); } /** * Checks if resource is a file. * * @since 2.5.0 * * @param string $file File path. * @return bool Whether $file is a file. */ public function is_file( $file ) { return @is_file( $file ); } /** * Checks if resource is a directory. * * @since 2.5.0 * * @param string $path Directory path. * @return bool Whether $path is a directory. */ public function is_dir( $path ) { return @is_dir( $path ); } /** * Checks if a file is readable. * * @since 2.5.0 * * @param string $file Path to file. * @return bool Whether $file is readable. */ public function is_readable( $file ) { return @is_readable( $file ); } /** * Checks if a file or directory is writable. * * @since 2.5.0 * * @param string $path Path to file or directory. * @return bool Whether $path is writable. */ public function is_writable( $path ) { return @is_writable( $path ); } /** * Gets the file's last access time. * * @since 2.5.0 * * @param string $file Path to file. * @return int|false Unix timestamp representing last access time, false on failure. */ public function atime( $file ) { return @fileatime( $file ); } /** * Gets the file modification time. * * @since 2.5.0 * * @param string $file Path to file. * @return int|false Unix timestamp representing modification time, false on failure. */ public function mtime( $file ) { return @filemtime( $file ); } /** * Gets the file size (in bytes). * * @since 2.5.0 * * @param string $file Path to file. * @return int|false Size of the file in bytes on success, false on failure. */ public function size( $file ) { return @filesize( $file ); } /** * Sets the access and modification times of a file. * * Note: If $file doesn't exist, it will be created. * * @since 2.5.0 * * @param string $file Path to file. * @param int $time Optional. Modified time to set for file. * Default 0. * @param int $atime Optional. Access time to set for file. * Default 0. * @return bool True on success, false on failure. */ public function touch( $file, $time = 0, $atime = 0 ) { if ( 0 === $time ) { $time = time(); } if ( 0 === $atime ) { $atime = time(); } return touch( $file, $time, $atime ); } /** * Creates a directory. * * @since 2.5.0 * * @param string $path Path for new directory. * @param int|false $chmod Optional. The permissions as octal number (or false to skip chmod). * Default false. * @param string|int|false $chown Optional. A user name or number (or false to skip chown). * Default false. * @param string|int|false $chgrp Optional. A group name or number (or false to skip chgrp). * Default false. * @return bool True on success, false on failure. */ public function mkdir( $path, $chmod = false, $chown = false, $chgrp = false ) { // Safe mode fails with a trailing slash under certain PHP versions. $path = untrailingslashit( $path ); if ( empty( $path ) ) { return false; } if ( ! $chmod ) { $chmod = FS_CHMOD_DIR; } if ( ! @mkdir( $path ) ) { return false; } $this->chmod( $path, $chmod ); if ( $chown ) { $this->chown( $path, $chown ); } if ( $chgrp ) { $this->chgrp( $path, $chgrp ); } return true; } /** * Deletes a directory. * * @since 2.5.0 * * @param string $path Path to directory. * @param bool $recursive Optional. Whether to recursively remove files/directories. * Default false. * @return bool True on success, false on failure. */ public function rmdir( $path, $recursive = false ) { return $this->delete( $path, $recursive ); } /** * Gets details for files in a directory or a specific file. * * @since 2.5.0 * * @param string $path Path to directory or file. * @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files. * Default true. * @param bool $recursive Optional. Whether to recursively include file details in nested directories. * Default false. * @return array|false { * Array of files. False if unable to list directory contents. * * @type string $name Name of the file or directory. * @type string $perms *nix representation of permissions. * @type string $permsn Octal representation of permissions. * @type string $owner Owner name or ID. * @type int $size Size of file in bytes. * @type int $lastmodunix Last modified unix timestamp. * @type mixed $lastmod Last modified month (3 letter) and day (without leading 0). * @type int $time Last modified time. * @type string $type Type of resource. 'f' for file, 'd' for directory. * @type mixed $files If a directory and `$recursive` is true, contains another array of files. * } */ public function dirlist( $path, $include_hidden = true, $recursive = false ) { if ( $this->is_file( $path ) ) { $limit_file = basename( $path ); $path = dirname( $path ); } else { $limit_file = false; } if ( ! $this->is_dir( $path ) || ! $this->is_readable( $path ) ) { return false; } $dir = dir( $path ); if ( ! $dir ) { return false; } $ret = array(); while ( false !== ( $entry = $dir->read() ) ) { $struc = array(); $struc['name'] = $entry; if ( '.' === $struc['name'] || '..' === $struc['name'] ) { continue; } if ( ! $include_hidden && '.' === $struc['name'][0] ) { continue; } if ( $limit_file && $struc['name'] !== $limit_file ) { continue; } $struc['perms'] = $this->gethchmod( $path . '/' . $entry ); $struc['permsn'] = $this->getnumchmodfromh( $struc['perms'] ); $struc['number'] = false; $struc['owner'] = $this->owner( $path . '/' . $entry ); $struc['group'] = $this->group( $path . '/' . $entry ); $struc['size'] = $this->size( $path . '/' . $entry ); $struc['lastmodunix'] = $this->mtime( $path . '/' . $entry ); $struc['lastmod'] = gmdate( 'M j', $struc['lastmodunix'] ); $struc['time'] = gmdate( 'h:i:s', $struc['lastmodunix'] ); $struc['type'] = $this->is_dir( $path . '/' . $entry ) ? 'd' : 'f'; if ( 'd' === $struc['type'] ) { if ( $recursive ) { $struc['files'] = $this->dirlist( $path . '/' . $struc['name'], $include_hidden, $recursive ); } else { $struc['files'] = array(); } } $ret[ $struc['name'] ] = $struc; } $dir->close(); unset( $dir ); return $ret; } } ``` | Uses | Description | | --- | --- | | [WP\_Filesystem\_Base](wp_filesystem_base) wp-admin/includes/class-wp-filesystem-base.php | Base WordPress Filesystem class which Filesystem implementations extend. | | Version | Description | | --- | --- | | [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
programming_docs
wordpress class WP_Customize_Custom_CSS_Setting {} class WP\_Customize\_Custom\_CSS\_Setting {} ============================================ Custom Setting to handle WP Custom CSS. * [WP\_Customize\_Setting](wp_customize_setting) * [\_\_construct](wp_customize_custom_css_setting/__construct) β€” WP\_Customize\_Custom\_CSS\_Setting constructor. * [filter\_previewed\_wp\_get\_custom\_css](wp_customize_custom_css_setting/filter_previewed_wp_get_custom_css) β€” Filters `wp\_get\_custom\_css` for applying the customized value. * [preview](wp_customize_custom_css_setting/preview) β€” Add filter to preview post value. * [update](wp_customize_custom_css_setting/update) β€” Store the CSS setting value in the custom\_css custom post type for the stylesheet. * [validate](wp_customize_custom_css_setting/validate) β€” Validate a received value for being valid CSS. * [value](wp_customize_custom_css_setting/value) β€” Fetch the value of the setting. Will return the previewed value when `preview()` is called. File: `wp-includes/customize/class-wp-customize-custom-css-setting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-custom-css-setting.php/) ``` final class WP_Customize_Custom_CSS_Setting extends WP_Customize_Setting { /** * The setting type. * * @since 4.7.0 * @var string */ public $type = 'custom_css'; /** * Setting Transport * * @since 4.7.0 * @var string */ public $transport = 'postMessage'; /** * Capability required to edit this setting. * * @since 4.7.0 * @var string */ public $capability = 'edit_css'; /** * Stylesheet * * @since 4.7.0 * @var string */ public $stylesheet = ''; /** * WP_Customize_Custom_CSS_Setting constructor. * * @since 4.7.0 * * @throws Exception If the setting ID does not match the pattern `custom_css[$stylesheet]`. * * @param WP_Customize_Manager $manager Customizer bootstrap instance. * @param string $id A specific ID of the setting. * Can be a theme mod or option name. * @param array $args Setting arguments. */ public function __construct( $manager, $id, $args = array() ) { parent::__construct( $manager, $id, $args ); if ( 'custom_css' !== $this->id_data['base'] ) { throw new Exception( 'Expected custom_css id_base.' ); } if ( 1 !== count( $this->id_data['keys'] ) || empty( $this->id_data['keys'][0] ) ) { throw new Exception( 'Expected single stylesheet key.' ); } $this->stylesheet = $this->id_data['keys'][0]; } /** * Add filter to preview post value. * * @since 4.7.9 * * @return bool False when preview short-circuits due no change needing to be previewed. */ public function preview() { if ( $this->is_previewed ) { return false; } $this->is_previewed = true; add_filter( 'wp_get_custom_css', array( $this, 'filter_previewed_wp_get_custom_css' ), 9, 2 ); return true; } /** * Filters `wp_get_custom_css` for applying the customized value. * * This is used in the preview when `wp_get_custom_css()` is called for rendering the styles. * * @since 4.7.0 * * @see wp_get_custom_css() * * @param string $css Original CSS. * @param string $stylesheet Current stylesheet. * @return string CSS. */ public function filter_previewed_wp_get_custom_css( $css, $stylesheet ) { if ( $stylesheet === $this->stylesheet ) { $customized_value = $this->post_value( null ); if ( ! is_null( $customized_value ) ) { $css = $customized_value; } } return $css; } /** * Fetch the value of the setting. Will return the previewed value when `preview()` is called. * * @since 4.7.0 * * @see WP_Customize_Setting::value() * * @return string */ public function value() { if ( $this->is_previewed ) { $post_value = $this->post_value( null ); if ( null !== $post_value ) { return $post_value; } } $id_base = $this->id_data['base']; $value = ''; $post = wp_get_custom_css_post( $this->stylesheet ); if ( $post ) { $value = $post->post_content; } if ( empty( $value ) ) { $value = $this->default; } /** This filter is documented in wp-includes/class-wp-customize-setting.php */ $value = apply_filters( "customize_value_{$id_base}", $value, $this ); return $value; } /** * Validate a received value for being valid CSS. * * Checks for imbalanced braces, brackets, and comments. * Notifications are rendered when the customizer state is saved. * * @since 4.7.0 * @since 4.9.0 Checking for balanced characters has been moved client-side via linting in code editor. * @since 5.9.0 Renamed `$css` to `$value` for PHP 8 named parameter support. * * @param string $value CSS to validate. * @return true|WP_Error True if the input was validated, otherwise WP_Error. */ public function validate( $value ) { // Restores the more descriptive, specific name for use within this method. $css = $value; $validity = new WP_Error(); if ( preg_match( '#</?\w+#', $css ) ) { $validity->add( 'illegal_markup', __( 'Markup is not allowed in CSS.' ) ); } if ( ! $validity->has_errors() ) { $validity = parent::validate( $css ); } return $validity; } /** * Store the CSS setting value in the custom_css custom post type for the stylesheet. * * @since 4.7.0 * @since 5.9.0 Renamed `$css` to `$value` for PHP 8 named parameter support. * * @param string $value CSS to update. * @return int|false The post ID or false if the value could not be saved. */ public function update( $value ) { // Restores the more descriptive, specific name for use within this method. $css = $value; if ( empty( $css ) ) { $css = ''; } $r = wp_update_custom_css_post( $css, array( 'stylesheet' => $this->stylesheet, ) ); if ( $r instanceof WP_Error ) { return false; } $post_id = $r->ID; // Cache post ID in theme mod for performance to avoid additional DB query. if ( $this->manager->get_stylesheet() === $this->stylesheet ) { set_theme_mod( 'custom_css_post_id', $post_id ); } return $post_id; } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Setting](wp_customize_setting) wp-includes/class-wp-customize-setting.php | Customize Setting class. | | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. | wordpress class WP_Locale {} class WP\_Locale {} =================== Core class used to store translated data for a locale. * [\_\_construct](wp_locale/__construct) β€” Constructor which calls helper methods to set up object variables. * [\_strings\_for\_pot](wp_locale/_strings_for_pot) β€” Registers date/time format strings for general POT. * [get\_list\_item\_separator](wp_locale/get_list_item_separator) β€” Retrieves the localized list item separator. * [get\_meridiem](wp_locale/get_meridiem) β€” Retrieves translated version of meridiem string. * [get\_month](wp_locale/get_month) β€” Retrieves the full translated month by month number. * [get\_month\_abbrev](wp_locale/get_month_abbrev) β€” Retrieves translated version of month abbreviation string. * [get\_weekday](wp_locale/get_weekday) β€” Retrieves the full translated weekday word. * [get\_weekday\_abbrev](wp_locale/get_weekday_abbrev) β€” Retrieves the translated weekday abbreviation. * [get\_weekday\_initial](wp_locale/get_weekday_initial) β€” Retrieves the translated weekday initial. * [init](wp_locale/init) β€” Sets up the translated strings and object properties. * [is\_rtl](wp_locale/is_rtl) β€” Checks if current locale is RTL. * [register\_globals](wp_locale/register_globals) β€” Global variables are deprecated. β€” deprecated File: `wp-includes/class-wp-locale.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale.php/) ``` class WP_Locale { /** * Stores the translated strings for the full weekday names. * * @since 2.1.0 * @var string[] */ public $weekday; /** * Stores the translated strings for the one character weekday names. * * There is a hack to make sure that Tuesday and Thursday, as well * as Sunday and Saturday, don't conflict. See init() method for more. * * @see WP_Locale::init() for how to handle the hack. * * @since 2.1.0 * @var string[] */ public $weekday_initial; /** * Stores the translated strings for the abbreviated weekday names. * * @since 2.1.0 * @var string[] */ public $weekday_abbrev; /** * Stores the translated strings for the full month names. * * @since 2.1.0 * @var string[] */ public $month; /** * Stores the translated strings for the month names in genitive case, if the locale specifies. * * @since 4.4.0 * @var string[] */ public $month_genitive; /** * Stores the translated strings for the abbreviated month names. * * @since 2.1.0 * @var string[] */ public $month_abbrev; /** * Stores the translated strings for 'am' and 'pm'. * * Also the capitalized versions. * * @since 2.1.0 * @var string[] */ public $meridiem; /** * The text direction of the locale language. * * Default is left to right 'ltr'. * * @since 2.1.0 * @var string */ public $text_direction = 'ltr'; /** * The thousands separator and decimal point values used for localizing numbers. * * @since 2.3.0 * @var array */ public $number_format; /** * The separator string used for localizing list item separator. * * @since 6.0.0 * @var string */ public $list_item_separator; /** * Constructor which calls helper methods to set up object variables. * * @since 2.1.0 */ public function __construct() { $this->init(); $this->register_globals(); } /** * 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. * * @since 2.1.0 * * @global string $text_direction * @global string $wp_version The WordPress version string. */ 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( ' ', '&nbsp;', $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'; } } /** * 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). * * @since 2.1.0 * * @param int $weekday_number 0 for Sunday through 6 Saturday. * @return string Full translated weekday. */ public function get_weekday( $weekday_number ) { return $this->weekday[ $weekday_number ]; } /** * 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. * * @since 2.1.0 * * @param string $weekday_name Full translated weekday word. * @return string Translated weekday initial. */ public function get_weekday_initial( $weekday_name ) { return $this->weekday_initial[ $weekday_name ]; } /** * Retrieves the translated weekday abbreviation. * * The weekday abbreviation is retrieved by the translated * full weekday word. * * @since 2.1.0 * * @param string $weekday_name Full translated weekday word. * @return string Translated weekday abbreviation. */ public function get_weekday_abbrev( $weekday_name ) { return $this->weekday_abbrev[ $weekday_name ]; } /** * 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. * * @since 2.1.0 * * @param string|int $month_number '01' through '12'. * @return string Translated full month name. */ public function get_month( $month_number ) { return $this->month[ zeroise( $month_number, 2 ) ]; } /** * Retrieves translated version of month abbreviation string. * * The $month_name parameter is expected to be the translated or * translatable version of the month. * * @since 2.1.0 * * @param string $month_name Translated month to get abbreviated version. * @return string Translated abbreviated month. */ public function get_month_abbrev( $month_name ) { return $this->month_abbrev[ $month_name ]; } /** * Retrieves translated version of meridiem string. * * The $meridiem parameter is expected to not be translated. * * @since 2.1.0 * * @param string $meridiem Either 'am', 'pm', 'AM', or 'PM'. Not translated version. * @return string Translated version */ public function get_meridiem( $meridiem ) { return $this->meridiem[ $meridiem ]; } /** * Global variables are deprecated. * * For backward compatibility only. * * @deprecated For backward compatibility only. * * @global array $weekday * @global array $weekday_initial * @global array $weekday_abbrev * @global array $month * @global array $month_abbrev * * @since 2.1.0 */ 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; } /** * Checks if current locale is RTL. * * @since 3.0.0 * @return bool Whether locale is RTL. */ public function is_rtl() { return 'rtl' === $this->text_direction; } /** * 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. * * @since 3.6.0 */ 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' ); } /** * Retrieves the localized list item separator. * * @since 6.0.0 * * @return string Localized list item separator. */ public function get_list_item_separator() { return $this->list_item_separator; } } ``` | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Moved to its own file from wp-includes/locale.php. | | [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Block_Directory_Controller {} class WP\_REST\_Block\_Directory\_Controller {} =============================================== Controller which provides REST endpoint for the blocks. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_block_directory_controller/__construct) β€” Constructs the controller. * [find\_plugin\_for\_slug](wp_rest_block_directory_controller/find_plugin_for_slug) β€” Finds an installed plugin for the given slug. * [get\_collection\_params](wp_rest_block_directory_controller/get_collection_params) β€” Retrieves the search params for the blocks collection. * [get\_item\_schema](wp_rest_block_directory_controller/get_item_schema) β€” Retrieves the theme's schema, conforming to JSON Schema. * [get\_items](wp_rest_block_directory_controller/get_items) β€” Search and retrieve blocks metadata * [get\_items\_permissions\_check](wp_rest_block_directory_controller/get_items_permissions_check) β€” Checks whether a given request has permission to install and activate plugins. * [prepare\_item\_for\_response](wp_rest_block_directory_controller/prepare_item_for_response) β€” Parse block metadata for a block, and prepare it for an API response. * [prepare\_links](wp_rest_block_directory_controller/prepare_links) β€” Generates a list of links to include in the response for the plugin. * [register\_routes](wp_rest_block_directory_controller/register_routes) β€” Registers the necessary REST API routes. File: `wp-includes/rest-api/endpoints/class-wp-rest-block-directory-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-directory-controller.php/) ``` class WP_REST_Block_Directory_Controller extends WP_REST_Controller { /** * Constructs the controller. */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'block-directory'; } /** * Registers the necessary REST API routes. */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base . '/search', 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' ), ) ); } /** * Checks whether a given request has permission to install and activate plugins. * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has permission, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { if ( ! current_user_can( 'install_plugins' ) || ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( 'rest_block_directory_cannot_view', __( 'Sorry, you are not allowed to browse the block directory.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Search and retrieve blocks metadata * * @since 5.5.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { require_once ABSPATH . 'wp-admin/includes/plugin-install.php'; require_once ABSPATH . 'wp-admin/includes/plugin.php'; $response = plugins_api( 'query_plugins', array( 'block' => $request['term'], 'per_page' => $request['per_page'], 'page' => $request['page'], ) ); if ( is_wp_error( $response ) ) { $response->add_data( array( 'status' => 500 ) ); return $response; } $result = array(); foreach ( $response->plugins as $plugin ) { // If the API returned a plugin with empty data for 'blocks', skip it. if ( empty( $plugin['blocks'] ) ) { continue; } $data = $this->prepare_item_for_response( $plugin, $request ); $result[] = $this->prepare_response_for_collection( $data ); } return rest_ensure_response( $result ); } /** * Parse block metadata for a block, and prepare it for an API response. * * @since 5.5.0 * @since 5.9.0 Renamed `$plugin` to `$item` to match parent class for PHP 8 named parameter support. * * @param array $item The plugin metadata. * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $plugin = $item; $fields = $this->get_fields_for_response( $request ); // There might be multiple blocks in a plugin. Only the first block is mapped. $block_data = reset( $plugin['blocks'] ); // A data array containing the properties we'll return. $block = array( 'name' => $block_data['name'], 'title' => ( $block_data['title'] ? $block_data['title'] : $plugin['name'] ), 'description' => wp_trim_words( $plugin['short_description'], 30, '...' ), 'id' => $plugin['slug'], 'rating' => $plugin['rating'] / 20, 'rating_count' => (int) $plugin['num_ratings'], 'active_installs' => (int) $plugin['active_installs'], 'author_block_rating' => $plugin['author_block_rating'] / 20, 'author_block_count' => (int) $plugin['author_block_count'], 'author' => wp_strip_all_tags( $plugin['author'] ), 'icon' => ( isset( $plugin['icons']['1x'] ) ? $plugin['icons']['1x'] : 'block-default' ), 'last_updated' => gmdate( 'Y-m-d\TH:i:s', strtotime( $plugin['last_updated'] ) ), 'humanized_updated' => sprintf( /* translators: %s: Human-readable time difference. */ __( '%s ago' ), human_time_diff( strtotime( $plugin['last_updated'] ) ) ), ); $this->add_additional_fields_to_object( $block, $request ); $response = new WP_REST_Response( $block ); if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { $response->add_links( $this->prepare_links( $plugin ) ); } return $response; } /** * Generates a list of links to include in the response for the plugin. * * @since 5.5.0 * * @param array $plugin The plugin data from WordPress.org. * @return array */ protected function prepare_links( $plugin ) { $links = array( 'https://api.w.org/install-plugin' => array( 'href' => add_query_arg( 'slug', urlencode( $plugin['slug'] ), rest_url( 'wp/v2/plugins' ) ), ), ); $plugin_file = $this->find_plugin_for_slug( $plugin['slug'] ); if ( $plugin_file ) { $links['https://api.w.org/plugin'] = array( 'href' => rest_url( 'wp/v2/plugins/' . substr( $plugin_file, 0, - 4 ) ), 'embeddable' => true, ); } return $links; } /** * Finds an installed plugin for the given slug. * * @since 5.5.0 * * @param string $slug The WordPress.org directory slug for a plugin. * @return string The plugin file found matching it. */ protected function find_plugin_for_slug( $slug ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; $plugin_files = get_plugins( '/' . $slug ); if ( ! $plugin_files ) { return ''; } $plugin_files = array_keys( $plugin_files ); return $slug . '/' . reset( $plugin_files ); } /** * Retrieves the theme's schema, conforming to JSON Schema. * * @since 5.5.0 * * @return array Item schema data. */ 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' => 'block-directory-item', 'type' => 'object', 'properties' => array( 'name' => array( 'description' => __( 'The block name, in namespace/block-name format.' ), 'type' => 'string', 'context' => array( 'view' ), ), 'title' => array( 'description' => __( 'The block title, in human readable format.' ), 'type' => 'string', 'context' => array( 'view' ), ), 'description' => array( 'description' => __( 'A short description of the block, in human readable format.' ), 'type' => 'string', 'context' => array( 'view' ), ), 'id' => array( 'description' => __( 'The block slug.' ), 'type' => 'string', 'context' => array( 'view' ), ), 'rating' => array( 'description' => __( 'The star rating of the block.' ), 'type' => 'number', 'context' => array( 'view' ), ), 'rating_count' => array( 'description' => __( 'The number of ratings.' ), 'type' => 'integer', 'context' => array( 'view' ), ), 'active_installs' => array( 'description' => __( 'The number sites that have activated this block.' ), 'type' => 'integer', 'context' => array( 'view' ), ), 'author_block_rating' => array( 'description' => __( 'The average rating of blocks published by the same author.' ), 'type' => 'number', 'context' => array( 'view' ), ), 'author_block_count' => array( 'description' => __( 'The number of blocks published by the same author.' ), 'type' => 'integer', 'context' => array( 'view' ), ), 'author' => array( 'description' => __( 'The WordPress.org username of the block author.' ), 'type' => 'string', 'context' => array( 'view' ), ), 'icon' => array( 'description' => __( 'The block icon.' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'view' ), ), 'last_updated' => array( 'description' => __( 'The date when the block was last updated.' ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'view' ), ), 'humanized_updated' => array( 'description' => __( 'The date when the block was last updated, in fuzzy human readable format.' ), 'type' => 'string', 'context' => array( 'view' ), ), ), ); return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the search params for the blocks collection. * * @since 5.5.0 * * @return array Collection parameters. */ public function get_collection_params() { $query_params = parent::get_collection_params(); $query_params['context']['default'] = 'view'; $query_params['term'] = array( 'description' => __( 'Limit result set to blocks matching the search term.' ), 'type' => 'string', 'required' => true, 'minLength' => 1, ); unset( $query_params['search'] ); /** * Filters REST API collection parameters for the block directory controller. * * @since 5.5.0 * * @param array $query_params JSON Schema-formatted collection parameters. */ return apply_filters( 'rest_block_directory_collection_params', $query_params ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. | wordpress class WP_Site_Health_Auto_Updates {} class WP\_Site\_Health\_Auto\_Updates {} ======================================== Class for testing automatic updates in the WordPress code. * [\_\_construct](wp_site_health_auto_updates/__construct) β€” WP\_Site\_Health\_Auto\_Updates constructor. * [run\_tests](wp_site_health_auto_updates/run_tests) β€” Runs tests to determine if auto-updates can run. * [test\_accepts\_dev\_updates](wp_site_health_auto_updates/test_accepts_dev_updates) β€” Checks if the install is using a development branch and can use nightly packages. * [test\_accepts\_minor\_updates](wp_site_health_auto_updates/test_accepts_minor_updates) β€” Checks if the site supports automatic minor updates. * [test\_all\_files\_writable](wp_site_health_auto_updates/test_all_files_writable) β€” Checks if core files are writable by the web user/group. * [test\_check\_wp\_filesystem\_method](wp_site_health_auto_updates/test_check_wp_filesystem_method) β€” Checks if we can access files without providing credentials. * [test\_constants](wp_site_health_auto_updates/test_constants) β€” Tests if auto-updates related constants are set correctly. * [test\_filters\_automatic\_updater\_disabled](wp_site_health_auto_updates/test_filters_automatic_updater_disabled) β€” Checks if automatic updates are disabled by a filter. * [test\_if\_failed\_update](wp_site_health_auto_updates/test_if_failed_update) β€” Checks if automatic updates have tried to run, but failed, previously. * [test\_vcs\_abspath](wp_site_health_auto_updates/test_vcs_abspath) β€” Checks if WordPress is controlled by a VCS (Git, Subversion etc). * [test\_wp\_automatic\_updates\_disabled](wp_site_health_auto_updates/test_wp_automatic_updates_disabled) β€” Checks if automatic updates are disabled. * [test\_wp\_version\_check\_attached](wp_site_health_auto_updates/test_wp_version_check_attached) β€” Checks if updates are intercepted by a filter. File: `wp-admin/includes/class-wp-site-health-auto-updates.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health-auto-updates.php/) ``` class WP_Site_Health_Auto_Updates { /** * WP_Site_Health_Auto_Updates constructor. * * @since 5.2.0 */ public function __construct() { require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; } /** * Runs tests to determine if auto-updates can run. * * @since 5.2.0 * * @return array The test results. */ public function run_tests() { $tests = array( $this->test_constants( 'WP_AUTO_UPDATE_CORE', array( true, 'beta', 'rc', 'development', 'branch-development', 'minor' ) ), $this->test_wp_version_check_attached(), $this->test_filters_automatic_updater_disabled(), $this->test_wp_automatic_updates_disabled(), $this->test_if_failed_update(), $this->test_vcs_abspath(), $this->test_check_wp_filesystem_method(), $this->test_all_files_writable(), $this->test_accepts_dev_updates(), $this->test_accepts_minor_updates(), ); $tests = array_filter( $tests ); $tests = array_map( static function( $test ) { $test = (object) $test; if ( empty( $test->severity ) ) { $test->severity = 'warning'; } return $test; }, $tests ); return $tests; } /** * Tests if auto-updates related constants are set correctly. * * @since 5.2.0 * @since 5.5.1 The `$value` parameter can accept an array. * * @param string $constant The name of the constant to check. * @param bool|string|array $value The value that the constant should be, if set, * or an array of acceptable values. * @return array The test results. */ public function test_constants( $constant, $value ) { $acceptable_values = (array) $value; if ( defined( $constant ) && ! in_array( constant( $constant ), $acceptable_values, true ) ) { return array( 'description' => sprintf( /* translators: 1: Name of the constant used. 2: Value of the constant used. */ __( 'The %1$s constant is defined as %2$s' ), "<code>$constant</code>", '<code>' . esc_html( var_export( constant( $constant ), true ) ) . '</code>' ), 'severity' => 'fail', ); } } /** * Checks if updates are intercepted by a filter. * * @since 5.2.0 * * @return array The test results. */ public function test_wp_version_check_attached() { if ( ( ! is_multisite() || is_main_site() && is_network_admin() ) && ! has_filter( 'wp_version_check', 'wp_version_check' ) ) { return array( 'description' => sprintf( /* translators: %s: Name of the filter used. */ __( 'A plugin has prevented updates by disabling %s.' ), '<code>wp_version_check()</code>' ), 'severity' => 'fail', ); } } /** * Checks if automatic updates are disabled by a filter. * * @since 5.2.0 * * @return array The test results. */ public function test_filters_automatic_updater_disabled() { /** This filter is documented in wp-admin/includes/class-wp-automatic-updater.php */ if ( apply_filters( 'automatic_updater_disabled', false ) ) { return array( 'description' => sprintf( /* translators: %s: Name of the filter used. */ __( 'The %s filter is enabled.' ), '<code>automatic_updater_disabled</code>' ), 'severity' => 'fail', ); } } /** * Checks if automatic updates are disabled. * * @since 5.3.0 * * @return array|false The test results. False if auto-updates are enabled. */ public function test_wp_automatic_updates_disabled() { if ( ! class_exists( 'WP_Automatic_Updater' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-automatic-updater.php'; } $auto_updates = new WP_Automatic_Updater(); if ( ! $auto_updates->is_disabled() ) { return false; } return array( 'description' => __( 'All automatic updates are disabled.' ), 'severity' => 'fail', ); } /** * Checks if automatic updates have tried to run, but failed, previously. * * @since 5.2.0 * * @return array|false The test results. False if the auto-updates failed. */ public function test_if_failed_update() { $failed = get_site_option( 'auto_core_update_failed' ); if ( ! $failed ) { return false; } if ( ! empty( $failed['critical'] ) ) { $description = __( 'A previous automatic background update ended with a critical failure, so updates are now disabled.' ); $description .= ' ' . __( 'You would have received an email because of this.' ); $description .= ' ' . __( "When you've been able to update using the \"Update now\" button on Dashboard > Updates, this error will be cleared for future update attempts." ); $description .= ' ' . sprintf( /* translators: %s: Code of error shown. */ __( 'The error code was %s.' ), '<code>' . $failed['error_code'] . '</code>' ); return array( 'description' => $description, 'severity' => 'warning', ); } $description = __( 'A previous automatic background update could not occur.' ); if ( empty( $failed['retry'] ) ) { $description .= ' ' . __( 'You would have received an email because of this.' ); } $description .= ' ' . __( 'Another attempt will be made with the next release.' ); $description .= ' ' . sprintf( /* translators: %s: Code of error shown. */ __( 'The error code was %s.' ), '<code>' . $failed['error_code'] . '</code>' ); return array( 'description' => $description, 'severity' => 'warning', ); } /** * Checks if WordPress is controlled by a VCS (Git, Subversion etc). * * @since 5.2.0 * * @return array The test results. */ public function test_vcs_abspath() { $context_dirs = array( ABSPATH ); $vcs_dirs = array( '.svn', '.git', '.hg', '.bzr' ); $check_dirs = array(); foreach ( $context_dirs as $context_dir ) { // Walk up from $context_dir to the root. do { $check_dirs[] = $context_dir; // Once we've hit '/' or 'C:\', we need to stop. dirname will keep returning the input here. if ( dirname( $context_dir ) === $context_dir ) { break; } // Continue one level at a time. } while ( $context_dir = dirname( $context_dir ) ); } $check_dirs = array_unique( $check_dirs ); // Search all directories we've found for evidence of version control. foreach ( $vcs_dirs as $vcs_dir ) { foreach ( $check_dirs as $check_dir ) { // phpcs:ignore WordPress.CodeAnalysis.AssignmentInCondition,Squiz.PHP.DisallowMultipleAssignments if ( $checkout = @is_dir( rtrim( $check_dir, '\\/' ) . "/$vcs_dir" ) ) { break 2; } } } /** This filter is documented in wp-admin/includes/class-wp-automatic-updater.php */ if ( $checkout && ! apply_filters( 'automatic_updates_is_vcs_checkout', true, ABSPATH ) ) { return array( 'description' => sprintf( /* translators: 1: Folder name. 2: Version control directory. 3: Filter name. */ __( 'The folder %1$s was detected as being under version control (%2$s), but the %3$s filter is allowing updates.' ), '<code>' . $check_dir . '</code>', "<code>$vcs_dir</code>", '<code>automatic_updates_is_vcs_checkout</code>' ), 'severity' => 'info', ); } if ( $checkout ) { return array( 'description' => sprintf( /* translators: 1: Folder name. 2: Version control directory. */ __( 'The folder %1$s was detected as being under version control (%2$s).' ), '<code>' . $check_dir . '</code>', "<code>$vcs_dir</code>" ), 'severity' => 'warning', ); } return array( 'description' => __( 'No version control systems were detected.' ), 'severity' => 'pass', ); } /** * Checks if we can access files without providing credentials. * * @since 5.2.0 * * @return array The test results. */ public function test_check_wp_filesystem_method() { // Make sure the `request_filesystem_credentials()` function is available during our REST API call. if ( ! function_exists( 'request_filesystem_credentials' ) ) { require_once ABSPATH . '/wp-admin/includes/file.php'; } $skin = new Automatic_Upgrader_Skin; $success = $skin->request_filesystem_credentials( false, ABSPATH ); if ( ! $success ) { $description = __( 'Your installation of WordPress prompts for FTP credentials to perform updates.' ); $description .= ' ' . __( '(Your site is performing updates over FTP due to file ownership. Talk to your hosting company.)' ); return array( 'description' => $description, 'severity' => 'fail', ); } return array( 'description' => __( 'Your installation of WordPress does not require FTP credentials to perform updates.' ), 'severity' => 'pass', ); } /** * Checks if core files are writable by the web user/group. * * @since 5.2.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @return array|false The test results. False if they're not writeable. */ public function test_all_files_writable() { global $wp_filesystem; require ABSPATH . WPINC . '/version.php'; // $wp_version; // x.y.z $skin = new Automatic_Upgrader_Skin; $success = $skin->request_filesystem_credentials( false, ABSPATH ); if ( ! $success ) { return false; } WP_Filesystem(); if ( 'direct' !== $wp_filesystem->method ) { return false; } // Make sure the `get_core_checksums()` function is available during our REST API call. if ( ! function_exists( 'get_core_checksums' ) ) { require_once ABSPATH . '/wp-admin/includes/update.php'; } $checksums = get_core_checksums( $wp_version, 'en_US' ); $dev = ( false !== strpos( $wp_version, '-' ) ); // Get the last stable version's files and test against that. if ( ! $checksums && $dev ) { $checksums = get_core_checksums( (float) $wp_version - 0.1, 'en_US' ); } // There aren't always checksums for development releases, so just skip the test if we still can't find any. if ( ! $checksums && $dev ) { return false; } if ( ! $checksums ) { $description = sprintf( /* translators: %s: WordPress version. */ __( "Couldn't retrieve a list of the checksums for WordPress %s." ), $wp_version ); $description .= ' ' . __( 'This could mean that connections are failing to WordPress.org.' ); return array( 'description' => $description, 'severity' => 'warning', ); } $unwritable_files = array(); foreach ( array_keys( $checksums ) as $file ) { if ( 'wp-content' === substr( $file, 0, 10 ) ) { continue; } if ( ! file_exists( ABSPATH . $file ) ) { continue; } if ( ! is_writable( ABSPATH . $file ) ) { $unwritable_files[] = $file; } } if ( $unwritable_files ) { if ( count( $unwritable_files ) > 20 ) { $unwritable_files = array_slice( $unwritable_files, 0, 20 ); $unwritable_files[] = '...'; } return array( 'description' => __( 'Some files are not writable by WordPress:' ) . ' <ul><li>' . implode( '</li><li>', $unwritable_files ) . '</li></ul>', 'severity' => 'fail', ); } else { return array( 'description' => __( 'All of your WordPress files are writable.' ), 'severity' => 'pass', ); } } /** * Checks if the install is using a development branch and can use nightly packages. * * @since 5.2.0 * * @return array|false The test results. False if it isn't a development version. */ public function test_accepts_dev_updates() { require ABSPATH . WPINC . '/version.php'; // $wp_version; // x.y.z // Only for dev versions. if ( false === strpos( $wp_version, '-' ) ) { return false; } if ( defined( 'WP_AUTO_UPDATE_CORE' ) && ( 'minor' === WP_AUTO_UPDATE_CORE || false === WP_AUTO_UPDATE_CORE ) ) { return array( 'description' => sprintf( /* translators: %s: Name of the constant used. */ __( 'WordPress development updates are blocked by the %s constant.' ), '<code>WP_AUTO_UPDATE_CORE</code>' ), 'severity' => 'fail', ); } /** This filter is documented in wp-admin/includes/class-core-upgrader.php */ if ( ! apply_filters( 'allow_dev_auto_core_updates', $wp_version ) ) { return array( 'description' => sprintf( /* translators: %s: Name of the filter used. */ __( 'WordPress development updates are blocked by the %s filter.' ), '<code>allow_dev_auto_core_updates</code>' ), 'severity' => 'fail', ); } } /** * Checks if the site supports automatic minor updates. * * @since 5.2.0 * * @return array The test results. */ public function test_accepts_minor_updates() { if ( defined( 'WP_AUTO_UPDATE_CORE' ) && false === WP_AUTO_UPDATE_CORE ) { return array( 'description' => sprintf( /* translators: %s: Name of the constant used. */ __( 'WordPress security and maintenance releases are blocked by %s.' ), "<code>define( 'WP_AUTO_UPDATE_CORE', false );</code>" ), 'severity' => 'fail', ); } /** This filter is documented in wp-admin/includes/class-core-upgrader.php */ if ( ! apply_filters( 'allow_minor_auto_core_updates', true ) ) { return array( 'description' => sprintf( /* translators: %s: Name of the filter used. */ __( 'WordPress security and maintenance releases are blocked by the %s filter.' ), '<code>allow_minor_auto_core_updates</code>' ), 'severity' => 'fail', ); } } } ``` | Version | Description | | --- | --- | | [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
programming_docs
wordpress class WP_Themes_List_Table {} class WP\_Themes\_List\_Table {} ================================ Core class used to implement displaying installed themes in a list table. * [WP\_List\_Table](wp_list_table) * [\_\_construct](wp_themes_list_table/__construct) β€” Constructor. * [\_js\_vars](wp_themes_list_table/_js_vars) β€” Send required variables to JavaScript land * [ajax\_user\_can](wp_themes_list_table/ajax_user_can) * [display](wp_themes_list_table/display) β€” Displays the themes table. * [display\_rows](wp_themes_list_table/display_rows) * [display\_rows\_or\_placeholder](wp_themes_list_table/display_rows_or_placeholder) * [get\_columns](wp_themes_list_table/get_columns) * [no\_items](wp_themes_list_table/no_items) * [prepare\_items](wp_themes_list_table/prepare_items) * [search\_theme](wp_themes_list_table/search_theme) * [tablenav](wp_themes_list_table/tablenav) File: `wp-admin/includes/class-wp-themes-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-themes-list-table.php/) ``` class WP_Themes_List_Table extends WP_List_Table { protected $search_terms = array(); public $features = array(); /** * Constructor. * * @since 3.1.0 * * @see WP_List_Table::__construct() for more information on default arguments. * * @param array $args An associative array of arguments. */ public function __construct( $args = array() ) { parent::__construct( array( 'ajax' => true, 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); } /** * @return bool */ public function ajax_user_can() { // Do not check edit_theme_options here. Ajax calls for available themes require switch_themes. return current_user_can( 'switch_themes' ); } /** */ public function prepare_items() { $themes = wp_get_themes( array( 'allowed' => true ) ); if ( ! empty( $_REQUEST['s'] ) ) { $this->search_terms = array_unique( array_filter( array_map( 'trim', explode( ',', strtolower( wp_unslash( $_REQUEST['s'] ) ) ) ) ) ); } if ( ! empty( $_REQUEST['features'] ) ) { $this->features = $_REQUEST['features']; } if ( $this->search_terms || $this->features ) { foreach ( $themes as $key => $theme ) { if ( ! $this->search_theme( $theme ) ) { unset( $themes[ $key ] ); } } } unset( $themes[ get_option( 'stylesheet' ) ] ); WP_Theme::sort_by_name( $themes ); $per_page = 36; $page = $this->get_pagenum(); $start = ( $page - 1 ) * $per_page; $this->items = array_slice( $themes, $start, $per_page, true ); $this->set_pagination_args( array( 'total_items' => count( $themes ), 'per_page' => $per_page, 'infinite_scroll' => true, ) ); } /** */ public function no_items() { if ( $this->search_terms || $this->features ) { _e( 'No items found.' ); return; } $blog_id = get_current_blog_id(); if ( is_multisite() ) { if ( current_user_can( 'install_themes' ) && current_user_can( 'manage_network_themes' ) ) { printf( /* translators: 1: URL to Themes tab on Edit Site screen, 2: URL to Add Themes screen. */ __( 'You only have one theme enabled for this site right now. Visit the Network Admin to <a href="%1$s">enable</a> or <a href="%2$s">install</a> more themes.' ), network_admin_url( 'site-themes.php?id=' . $blog_id ), network_admin_url( 'theme-install.php' ) ); return; } elseif ( current_user_can( 'manage_network_themes' ) ) { printf( /* translators: %s: URL to Themes tab on Edit Site screen. */ __( 'You only have one theme enabled for this site right now. Visit the Network Admin to <a href="%s">enable</a> more themes.' ), network_admin_url( 'site-themes.php?id=' . $blog_id ) ); return; } // Else, fallthrough. install_themes doesn't help if you can't enable it. } else { if ( current_user_can( 'install_themes' ) ) { printf( /* translators: %s: URL to Add Themes screen. */ __( 'You only have one theme installed right now. Live a little! You can choose from over 1,000 free themes in the WordPress Theme Directory at any time: just click on the <a href="%s">Install Themes</a> tab above.' ), admin_url( 'theme-install.php' ) ); return; } } // Fallthrough. printf( /* translators: %s: Network title. */ __( 'Only the active theme is available to you. Contact the %s administrator for information about accessing additional themes.' ), get_site_option( 'site_name' ) ); } /** * @param string $which */ public function tablenav( $which = 'top' ) { if ( $this->get_pagination_arg( 'total_pages' ) <= 1 ) { return; } ?> <div class="tablenav themes <?php echo $which; ?>"> <?php $this->pagination( $which ); ?> <span class="spinner"></span> <br class="clear" /> </div> <?php } /** * Displays the themes table. * * Overrides the parent display() method to provide a different container. * * @since 3.1.0 */ public function display() { wp_nonce_field( 'fetch-list-' . get_class( $this ), '_ajax_fetch_list_nonce' ); ?> <?php $this->tablenav( 'top' ); ?> <div id="availablethemes"> <?php $this->display_rows_or_placeholder(); ?> </div> <?php $this->tablenav( 'bottom' ); ?> <?php } /** * @return array */ public function get_columns() { return array(); } /** */ public function display_rows_or_placeholder() { if ( $this->has_items() ) { $this->display_rows(); } else { echo '<div class="no-items">'; $this->no_items(); echo '</div>'; } } /** */ public function display_rows() { $themes = $this->items; foreach ( $themes as $theme ) : ?> <div class="available-theme"> <?php $template = $theme->get_template(); $stylesheet = $theme->get_stylesheet(); $title = $theme->display( 'Name' ); $version = $theme->display( 'Version' ); $author = $theme->display( 'Author' ); $activate_link = wp_nonce_url( 'themes.php?action=activate&amp;template=' . urlencode( $template ) . '&amp;stylesheet=' . urlencode( $stylesheet ), 'switch-theme_' . $stylesheet ); $actions = array(); $actions['activate'] = sprintf( '<a href="%s" class="activatelink" title="%s">%s</a>', $activate_link, /* translators: %s: Theme name. */ esc_attr( sprintf( _x( 'Activate &#8220;%s&#8221;', 'theme' ), $title ) ), __( 'Activate' ) ); if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) { $actions['preview'] .= sprintf( '<a href="%s" class="load-customize hide-if-no-customize">%s</a>', wp_customize_url( $stylesheet ), __( 'Live Preview' ) ); } if ( ! is_multisite() && current_user_can( 'delete_themes' ) ) { $actions['delete'] = sprintf( '<a class="submitdelete deletion" href="%s" onclick="return confirm( \'%s\' );">%s</a>', wp_nonce_url( 'themes.php?action=delete&amp;stylesheet=' . urlencode( $stylesheet ), 'delete-theme_' . $stylesheet ), /* translators: %s: Theme name. */ esc_js( sprintf( __( "You are about to delete this theme '%s'\n 'Cancel' to stop, 'OK' to delete." ), $title ) ), __( 'Delete' ) ); } /** This filter is documented in wp-admin/includes/class-wp-ms-themes-list-table.php */ $actions = apply_filters( 'theme_action_links', $actions, $theme, 'all' ); /** This filter is documented in wp-admin/includes/class-wp-ms-themes-list-table.php */ $actions = apply_filters( "theme_action_links_{$stylesheet}", $actions, $theme, 'all' ); $delete_action = isset( $actions['delete'] ) ? '<div class="delete-theme">' . $actions['delete'] . '</div>' : ''; unset( $actions['delete'] ); $screenshot = $theme->get_screenshot(); ?> <span class="screenshot hide-if-customize"> <?php if ( $screenshot ) : ?> <img src="<?php echo esc_url( $screenshot . '?ver=' . $theme->version ); ?>" alt="" /> <?php endif; ?> </span> <a href="<?php echo wp_customize_url( $stylesheet ); ?>" class="screenshot load-customize hide-if-no-customize"> <?php if ( $screenshot ) : ?> <img src="<?php echo esc_url( $screenshot . '?ver=' . $theme->version ); ?>" alt="" /> <?php endif; ?> </a> <h3><?php echo $title; ?></h3> <div class="theme-author"> <?php /* translators: %s: Theme author. */ printf( __( 'By %s' ), $author ); ?> </div> <div class="action-links"> <ul> <?php foreach ( $actions as $action ) : ?> <li><?php echo $action; ?></li> <?php endforeach; ?> <li class="hide-if-no-js"><a href="#" class="theme-detail"><?php _e( 'Details' ); ?></a></li> </ul> <?php echo $delete_action; ?> <?php theme_update_available( $theme ); ?> </div> <div class="themedetaildiv hide-if-js"> <p><strong><?php _e( 'Version:' ); ?></strong> <?php echo $version; ?></p> <p><?php echo $theme->display( 'Description' ); ?></p> <?php if ( $theme->parent() ) { printf( /* translators: 1: Link to documentation on child themes, 2: Name of parent theme. */ ' <p class="howto">' . __( 'This <a href="%1$s">child theme</a> requires its parent theme, %2$s.' ) . '</p>', __( 'https://developer.wordpress.org/themes/advanced-topics/child-themes/' ), $theme->parent()->display( 'Name' ) ); } ?> </div> </div> <?php endforeach; } /** * @param WP_Theme $theme * @return bool */ public function search_theme( $theme ) { // Search the features. foreach ( $this->features as $word ) { if ( ! in_array( $word, $theme->get( 'Tags' ), true ) ) { return false; } } // Match all phrases. foreach ( $this->search_terms as $word ) { if ( in_array( $word, $theme->get( 'Tags' ), true ) ) { continue; } foreach ( array( 'Name', 'Description', 'Author', 'AuthorURI' ) as $header ) { // Don't mark up; Do translate. if ( false !== stripos( strip_tags( $theme->display( $header, false, true ) ), $word ) ) { continue 2; } } if ( false !== stripos( $theme->get_stylesheet(), $word ) ) { continue; } if ( false !== stripos( $theme->get_template(), $word ) ) { continue; } return false; } return true; } /** * Send required variables to JavaScript land * * @since 3.4.0 * * @param array $extra_args */ public function _js_vars( $extra_args = array() ) { $search_string = isset( $_REQUEST['s'] ) ? esc_attr( wp_unslash( $_REQUEST['s'] ) ) : ''; $args = array( 'search' => $search_string, 'features' => $this->features, 'paged' => $this->get_pagenum(), 'total_pages' => ! empty( $this->_pagination_args['total_pages'] ) ? $this->_pagination_args['total_pages'] : 1, ); if ( is_array( $extra_args ) ) { $args = array_merge( $args, $extra_args ); } printf( "<script type='text/javascript'>var theme_list_args = %s;</script>\n", wp_json_encode( $args ) ); parent::_js_vars(); } } ``` | Uses | Description | | --- | --- | | [WP\_List\_Table](wp_list_table) wp-admin/includes/class-wp-list-table.php | Base class for displaying a list of items in an ajaxified HTML table. | | Used By | Description | | --- | --- | | [WP\_Theme\_Install\_List\_Table](wp_theme_install_list_table) wp-admin/includes/class-wp-theme-install-list-table.php | Core class used to implement displaying themes to install in a list table. | | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. | wordpress class NOOP_Translations {} class NOOP\_Translations {} =========================== * [add\_entry](noop_translations/add_entry) * [get\_header](noop_translations/get_header) * [get\_plural\_forms\_count](noop_translations/get_plural_forms_count) * [merge\_with](noop_translations/merge_with) * [select\_plural\_form](noop_translations/select_plural_form) * [set\_header](noop_translations/set_header) * [set\_headers](noop_translations/set_headers) * [translate](noop_translations/translate) * [translate\_entry](noop_translations/translate_entry) * [translate\_plural](noop_translations/translate_plural) File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/) ``` class NOOP_Translations { public $entries = array(); public $headers = array(); public function add_entry( $entry ) { return true; } /** * @param string $header * @param string $value */ public function set_header( $header, $value ) { } /** * @param array $headers */ public function set_headers( $headers ) { } /** * @param string $header * @return false */ public function get_header( $header ) { return false; } /** * @param Translation_Entry $entry * @return false */ public function translate_entry( &$entry ) { return false; } /** * @param string $singular * @param string $context */ public function translate( $singular, $context = null ) { return $singular; } /** * @param int $count * @return bool */ public function select_plural_form( $count ) { return 1 == $count ? 0 : 1; } /** * @return int */ public function get_plural_forms_count() { return 2; } /** * @param string $singular * @param string $plural * @param int $count * @param string $context */ public function translate_plural( $singular, $plural, $count, $context = null ) { return 1 == $count ? $singular : $plural; } /** * @param object $other */ public function merge_with( &$other ) { } } ``` wordpress class WP_Customize_New_Menu_Control {} class WP\_Customize\_New\_Menu\_Control {} ========================================== This class has been deprecated. Use [WP\_Customize\_Control](wp_customize_control) instead. Customize control class for new menus. * [WP\_Customize\_Control](wp_customize_control) * [\_\_construct](wp_customize_new_menu_control/__construct) β€” Constructor. β€” deprecated * [render\_content](wp_customize_new_menu_control/render_content) β€” Render the control's content. β€” deprecated File: `wp-includes/customize/class-wp-customize-new-menu-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-new-menu-control.php/) ``` class WP_Customize_New_Menu_Control extends WP_Customize_Control { /** * Control type. * * @since 4.3.0 * @var string */ public $type = 'new_menu'; /** * Constructor. * * @since 4.9.0 * @deprecated 4.9.0 * * @see WP_Customize_Control::__construct() * * @param WP_Customize_Manager $manager Customizer bootstrap instance. * @param string $id The control ID. * @param array $args Optional. Arguments to override class property defaults. * See WP_Customize_Control::__construct() for information * on accepted arguments. Default empty array. */ public function __construct( WP_Customize_Manager $manager, $id, array $args = array() ) { _deprecated_function( __METHOD__, '4.9.0' ); parent::__construct( $manager, $id, $args ); } /** * Render the control's content. * * @since 4.3.0 * @deprecated 4.9.0 */ public function render_content() { _deprecated_function( __METHOD__, '4.9.0' ); ?> <button type="button" class="button button-primary" id="create-new-menu-submit"><?php _e( 'Create Menu' ); ?></button> <span class="spinner"></span> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Control](wp_customize_control) wp-includes/class-wp-customize-control.php | Customize Control class. | | Version | Description | | --- | --- | | [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | This class is no longer used as of the menu creation UX introduced in #40104. | | [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. | wordpress class WP_SimplePie_Sanitize_KSES {} class WP\_SimplePie\_Sanitize\_KSES {} ====================================== Core class used to implement SimplePie feed sanitization. Extends the SimplePie\_Sanitize class to use KSES, because we cannot universally count on DOMDocument being available. * [SimplePie\_Sanitize](simplepie_sanitize) * [sanitize](wp_simplepie_sanitize_kses/sanitize) β€” WordPress SimplePie sanitization using KSES. File: `wp-includes/class-wp-simplepie-sanitize-kses.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-simplepie-sanitize-kses.php/) ``` class WP_SimplePie_Sanitize_KSES extends SimplePie_Sanitize { /** * WordPress SimplePie sanitization using KSES. * * Sanitizes the incoming data, to ensure that it matches the type of data expected, using KSES. * * @since 3.5.0 * * @param mixed $data The data that needs to be sanitized. * @param int $type The type of data that it's supposed to be. * @param string $base Optional. The `xml:base` value to use when converting relative * URLs to absolute ones. Default empty. * @return mixed Sanitized data. */ public function sanitize( $data, $type, $base = '' ) { $data = trim( $data ); if ( $type & SIMPLEPIE_CONSTRUCT_MAYBE_HTML ) { if ( preg_match( '/(&(#(x[0-9a-fA-F]+|[0-9]+)|[a-zA-Z0-9]+)|<\/[A-Za-z][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E]*' . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . '>)/', $data ) ) { $type |= SIMPLEPIE_CONSTRUCT_HTML; } else { $type |= SIMPLEPIE_CONSTRUCT_TEXT; } } if ( $type & SIMPLEPIE_CONSTRUCT_BASE64 ) { $data = base64_decode( $data ); } if ( $type & ( SIMPLEPIE_CONSTRUCT_HTML | SIMPLEPIE_CONSTRUCT_XHTML ) ) { $data = wp_kses_post( $data ); if ( 'UTF-8' !== $this->output_encoding ) { $data = $this->registry->call( 'Misc', 'change_encoding', array( $data, 'UTF-8', $this->output_encoding ) ); } return $data; } else { return parent::sanitize( $data, $type, $base ); } } } ``` | Version | Description | | --- | --- | | [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. | wordpress class Requests_Exception_HTTP_431 {} class Requests\_Exception\_HTTP\_431 {} ======================================= Exception for 431 Request Header Fields Too Large responses * <https://tools.ietf.org/html/rfc6585> File: `wp-includes/Requests/Exception/HTTP/431.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/431.php/) ``` class Requests_Exception_HTTP_431 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 431; /** * Reason phrase * * @var string */ protected $reason = 'Request Header Fields Too Large'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class Requests_SSL {} class Requests\_SSL {} ====================== SSL utilities for Requests Collection of utilities for working with and verifying SSL certificates. * [match\_domain](requests_ssl/match_domain) β€” Match a hostname against a dNSName reference * [verify\_certificate](requests_ssl/verify_certificate) β€” Verify the certificate against common name and subject alternative names * [verify\_reference\_name](requests_ssl/verify_reference_name) β€” Verify that a reference name is valid File: `wp-includes/Requests/SSL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/ssl.php/) ``` class Requests_SSL { /** * 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. * * @see https://tools.ietf.org/html/rfc2818#section-3.1 RFC2818, Section 3.1 * * @throws Requests_Exception On not obtaining a match for the host (`fsockopen.ssl.no_match`) * @param string $host Host name to verify against * @param array $cert Certificate data from openssl_x509_parse() * @return bool */ 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; } /** * 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. * * @param string $reference Reference dNSName * @return boolean Is the name valid? */ 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; } /** * Match a hostname against a dNSName reference * * @param string $host Requested host * @param string $reference dNSName to match against * @return boolean Does the domain match? */ 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; } } ```
programming_docs
wordpress class WP_Feed_Cache_Transient {} class WP\_Feed\_Cache\_Transient {} =================================== Core class used to implement feed cache transients. * [\_\_construct](wp_feed_cache_transient/__construct) β€” Constructor. * [load](wp_feed_cache_transient/load) β€” Gets the transient. * [mtime](wp_feed_cache_transient/mtime) β€” Gets mod transient. * [save](wp_feed_cache_transient/save) β€” Sets the transient. * [touch](wp_feed_cache_transient/touch) β€” Sets mod transient. * [unlink](wp_feed_cache_transient/unlink) β€” Deletes transients. File: `wp-includes/class-wp-feed-cache-transient.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-feed-cache-transient.php/) ``` class WP_Feed_Cache_Transient { /** * Holds the transient name. * * @since 2.8.0 * @var string */ public $name; /** * Holds the transient mod name. * * @since 2.8.0 * @var string */ public $mod_name; /** * Holds the cache duration in seconds. * * Defaults to 43200 seconds (12 hours). * * @since 2.8.0 * @var int */ public $lifetime = 43200; /** * Constructor. * * @since 2.8.0 * @since 3.2.0 Updated to use a PHP5 constructor. * * @param string $location URL location (scheme is used to determine handler). * @param string $filename Unique identifier for cache object. * @param string $extension 'spi' or 'spc'. */ public function __construct( $location, $filename, $extension ) { $this->name = 'feed_' . $filename; $this->mod_name = 'feed_mod_' . $filename; $lifetime = $this->lifetime; /** * Filters the transient lifetime of the feed cache. * * @since 2.8.0 * * @param int $lifetime Cache duration in seconds. Default is 43200 seconds (12 hours). * @param string $filename Unique identifier for the cache object. */ $this->lifetime = apply_filters( 'wp_feed_cache_transient_lifetime', $lifetime, $filename ); } /** * Sets the transient. * * @since 2.8.0 * * @param SimplePie $data Data to save. * @return true Always true. */ public function save( $data ) { if ( $data instanceof SimplePie ) { $data = $data->data; } set_transient( $this->name, $data, $this->lifetime ); set_transient( $this->mod_name, time(), $this->lifetime ); return true; } /** * Gets the transient. * * @since 2.8.0 * * @return mixed Transient value. */ public function load() { return get_transient( $this->name ); } /** * Gets mod transient. * * @since 2.8.0 * * @return mixed Transient value. */ public function mtime() { return get_transient( $this->mod_name ); } /** * Sets mod transient. * * @since 2.8.0 * * @return bool False if value was not set and true if value was set. */ public function touch() { return set_transient( $this->mod_name, time(), $this->lifetime ); } /** * Deletes transients. * * @since 2.8.0 * * @return true Always true. */ public function unlink() { delete_transient( $this->name ); delete_transient( $this->mod_name ); return true; } } ``` | Version | Description | | --- | --- | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. | wordpress class WP_Ajax_Upgrader_Skin {} class WP\_Ajax\_Upgrader\_Skin {} ================================= Upgrader Skin for Ajax WordPress upgrades. This skin is designed to be used for Ajax updates. * [Automatic\_Upgrader\_Skin](automatic_upgrader_skin) * [\_\_construct](wp_ajax_upgrader_skin/__construct) β€” Constructor. * [error](wp_ajax_upgrader_skin/error) β€” Stores an error message about the upgrade. * [feedback](wp_ajax_upgrader_skin/feedback) β€” Stores a message about the upgrade. * [get\_error\_messages](wp_ajax_upgrader_skin/get_error_messages) β€” Retrieves a string for error messages. * [get\_errors](wp_ajax_upgrader_skin/get_errors) β€” Retrieves the list of errors. File: `wp-admin/includes/class-wp-ajax-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ajax-upgrader-skin.php/) ``` class WP_Ajax_Upgrader_Skin extends Automatic_Upgrader_Skin { /** * Plugin info. * * The Plugin_Upgrader::bulk_upgrade() method will fill this in * with info retrieved from the get_plugin_data() function. * * @var array Plugin data. Values will be empty if not supplied by the plugin. */ public $plugin_info = array(); /** * Theme info. * * The Theme_Upgrader::bulk_upgrade() method will fill this in * with info retrieved from the Theme_Upgrader::theme_info() method, * which in turn calls the wp_get_theme() function. * * @var WP_Theme|false The theme's info object, or false. */ public $theme_info = false; /** * Holds the WP_Error object. * * @since 4.6.0 * * @var null|WP_Error */ protected $errors = null; /** * Constructor. * * Sets up the WordPress Ajax upgrader skin. * * @since 4.6.0 * * @see WP_Upgrader_Skin::__construct() * * @param array $args Optional. The WordPress Ajax upgrader skin arguments to * override default options. See WP_Upgrader_Skin::__construct(). * Default empty array. */ public function __construct( $args = array() ) { parent::__construct( $args ); $this->errors = new WP_Error(); } /** * Retrieves the list of errors. * * @since 4.6.0 * * @return WP_Error Errors during an upgrade. */ public function get_errors() { return $this->errors; } /** * Retrieves a string for error messages. * * @since 4.6.0 * * @return string Error messages during an upgrade. */ public function get_error_messages() { $messages = array(); foreach ( $this->errors->get_error_codes() as $error_code ) { $error_data = $this->errors->get_error_data( $error_code ); if ( $error_data && is_string( $error_data ) ) { $messages[] = $this->errors->get_error_message( $error_code ) . ' ' . esc_html( strip_tags( $error_data ) ); } else { $messages[] = $this->errors->get_error_message( $error_code ); } } return implode( ', ', $messages ); } /** * Stores an error message about the upgrade. * * @since 4.6.0 * @since 5.3.0 Formalized the existing `...$args` parameter by adding it * to the function signature. * * @param string|WP_Error $errors Errors. * @param mixed ...$args Optional text replacements. */ public function error( $errors, ...$args ) { if ( is_string( $errors ) ) { $string = $errors; if ( ! empty( $this->upgrader->strings[ $string ] ) ) { $string = $this->upgrader->strings[ $string ]; } if ( false !== strpos( $string, '%' ) ) { if ( ! empty( $args ) ) { $string = vsprintf( $string, $args ); } } // Count existing errors to generate a unique error code. $errors_count = count( $this->errors->get_error_codes() ); $this->errors->add( 'unknown_upgrade_error_' . ( $errors_count + 1 ), $string ); } elseif ( is_wp_error( $errors ) ) { foreach ( $errors->get_error_codes() as $error_code ) { $this->errors->add( $error_code, $errors->get_error_message( $error_code ), $errors->get_error_data( $error_code ) ); } } parent::error( $errors, ...$args ); } /** * Stores a message about the upgrade. * * @since 4.6.0 * @since 5.3.0 Formalized the existing `...$args` parameter by adding it * to the function signature. * @since 5.9.0 Renamed `$data` to `$feedback` for PHP 8 named parameter support. * * @param string|array|WP_Error $feedback Message data. * @param mixed ...$args Optional text replacements. */ public function feedback( $feedback, ...$args ) { if ( is_wp_error( $feedback ) ) { foreach ( $feedback->get_error_codes() as $error_code ) { $this->errors->add( $error_code, $feedback->get_error_message( $error_code ), $feedback->get_error_data( $error_code ) ); } } parent::feedback( $feedback, ...$args ); } } ``` | Uses | Description | | --- | --- | | [Automatic\_Upgrader\_Skin](automatic_upgrader_skin) wp-admin/includes/class-automatic-upgrader-skin.php | Upgrader Skin for Automatic WordPress Upgrades. | | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. | wordpress class WP_Block_Pattern_Categories_Registry {} class WP\_Block\_Pattern\_Categories\_Registry {} ================================================= Class used for interacting with block pattern categories. * [get\_all\_registered](wp_block_pattern_categories_registry/get_all_registered) β€” Retrieves all registered pattern categories. * [get\_instance](wp_block_pattern_categories_registry/get_instance) β€” Utility method to retrieve the main instance of the class. * [get\_registered](wp_block_pattern_categories_registry/get_registered) β€” Retrieves an array containing the properties of a registered pattern category. * [is\_registered](wp_block_pattern_categories_registry/is_registered) β€” Checks if a pattern category is registered. * [register](wp_block_pattern_categories_registry/register) β€” Registers a pattern category. * [unregister](wp_block_pattern_categories_registry/unregister) β€” Unregisters a pattern category. 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/) ``` final class WP_Block_Pattern_Categories_Registry { /** * Registered block pattern categories array. * * @since 5.5.0 * @var array[] */ private $registered_categories = array(); /** * Pattern categories registered outside the `init` action. * * @since 6.0.0 * @var array[] */ private $registered_categories_outside_init = array(); /** * Container for the main instance of the class. * * @since 5.5.0 * @var WP_Block_Pattern_Categories_Registry|null */ private static $instance = null; /** * Registers a pattern category. * * @since 5.5.0 * * @param string $category_name Pattern category name including namespace. * @param array $category_properties { * List of properties for the block pattern category. * * @type string $label Required. A human-readable label for the pattern category. * } * @return bool True if the pattern was registered with success and false otherwise. */ 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; } /** * Unregisters a pattern category. * * @since 5.5.0 * * @param string $category_name Pattern category name including namespace. * @return bool True if the pattern was unregistered with success and false otherwise. */ 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; } /** * Retrieves an array containing the properties of a registered pattern category. * * @since 5.5.0 * * @param string $category_name Pattern category name including namespace. * @return array Registered pattern properties. */ public function get_registered( $category_name ) { if ( ! $this->is_registered( $category_name ) ) { return null; } return $this->registered_categories[ $category_name ]; } /** * Retrieves all registered pattern categories. * * @since 5.5.0 * * @param bool $outside_init_only Return only categories registered outside the `init` action. * @return array[] Array of arrays containing the registered pattern categories properties. */ public function get_all_registered( $outside_init_only = false ) { return array_values( $outside_init_only ? $this->registered_categories_outside_init : $this->registered_categories ); } /** * Checks if a pattern category is registered. * * @since 5.5.0 * * @param string $category_name Pattern category name including namespace. * @return bool True if the pattern category is registered, false otherwise. */ public function is_registered( $category_name ) { return isset( $this->registered_categories[ $category_name ] ); } /** * Utility method to retrieve the main instance of the class. * * The instance will be created if it does not exist yet. * * @since 5.5.0 * * @return WP_Block_Pattern_Categories_Registry The main instance. */ public static function get_instance() { if ( null === self::$instance ) { self::$instance = new self(); } return self::$instance; } } ``` wordpress class WP_REST_Widgets_Controller {} class WP\_REST\_Widgets\_Controller {} ====================================== Core class to access widgets via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_widgets_controller/__construct) β€” Widgets controller constructor. * [check\_read\_sidebar\_permission](wp_rest_widgets_controller/check_read_sidebar_permission) β€” Checks if a sidebar can be read publicly. * [create\_item](wp_rest_widgets_controller/create_item) β€” Creates a widget. * [create\_item\_permissions\_check](wp_rest_widgets_controller/create_item_permissions_check) β€” Checks if a given request has access to create widgets. * [delete\_item](wp_rest_widgets_controller/delete_item) β€” Deletes a widget. * [delete\_item\_permissions\_check](wp_rest_widgets_controller/delete_item_permissions_check) β€” Checks if a given request has access to delete widgets. * [get\_collection\_params](wp_rest_widgets_controller/get_collection_params) β€” Gets the list of collection params. * [get\_item](wp_rest_widgets_controller/get_item) β€” Gets an individual widget. * [get\_item\_permissions\_check](wp_rest_widgets_controller/get_item_permissions_check) β€” Checks if a given request has access to get a widget. * [get\_item\_schema](wp_rest_widgets_controller/get_item_schema) β€” Retrieves the widget's schema, conforming to JSON Schema. * [get\_items](wp_rest_widgets_controller/get_items) β€” Retrieves a collection of widgets. * [get\_items\_permissions\_check](wp_rest_widgets_controller/get_items_permissions_check) β€” Checks if a given request has access to get widgets. * [permissions\_check](wp_rest_widgets_controller/permissions_check) β€” Performs a permissions check for managing widgets. * [prepare\_item\_for\_response](wp_rest_widgets_controller/prepare_item_for_response) β€” Prepares the widget for the REST response. * [prepare\_links](wp_rest_widgets_controller/prepare_links) β€” Prepares links for the widget. * [register\_routes](wp_rest_widgets_controller/register_routes) β€” Registers the widget routes for the controller. * [retrieve\_widgets](wp_rest_widgets_controller/retrieve_widgets) β€” Looks for "lost" widgets once per request. * [save\_widget](wp_rest_widgets_controller/save_widget) β€” Saves the widget in the request object. * [update\_item](wp_rest_widgets_controller/update_item) β€” Updates an existing widget. * [update\_item\_permissions\_check](wp_rest_widgets_controller/update_item_permissions_check) β€” Checks if a given request has access to update widgets. File: `wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php/) ``` class WP_REST_Widgets_Controller extends WP_REST_Controller { /** * Tracks whether {@see retrieve_widgets()} has been called in the current request. * * @since 5.9.0 * @var bool */ protected $widgets_retrieved = false; /** * Whether the controller supports batching. * * @since 5.9.0 * @var array */ protected $allow_batch = array( 'v1' => true ); /** * Widgets controller constructor. * * @since 5.8.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'widgets'; } /** * Registers the widget routes for the controller. * * @since 5.8.0 */ 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(), ), 'allow_batch' => $this->allow_batch, 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, $this->rest_base . '/(?P<id>[\w\-]+)', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'permission_callback' => array( $this, 'get_item_permissions_check' ), 'args' => array( '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( 'description' => __( 'Whether to force removal of the widget, or move it to the inactive sidebar.' ), 'type' => 'boolean', ), ), ), 'allow_batch' => $this->allow_batch, 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks if a given request has access to get widgets. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { $this->retrieve_widgets(); if ( isset( $request['sidebar'] ) && $this->check_read_sidebar_permission( $request['sidebar'] ) ) { return true; } foreach ( wp_get_sidebars_widgets() as $sidebar_id => $widget_ids ) { if ( $this->check_read_sidebar_permission( $sidebar_id ) ) { return true; } } return $this->permissions_check( $request ); } /** * Retrieves a collection of widgets. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { $this->retrieve_widgets(); $prepared = array(); $permissions_check = $this->permissions_check( $request ); foreach ( wp_get_sidebars_widgets() as $sidebar_id => $widget_ids ) { if ( isset( $request['sidebar'] ) && $sidebar_id !== $request['sidebar'] ) { continue; } if ( is_wp_error( $permissions_check ) && ! $this->check_read_sidebar_permission( $sidebar_id ) ) { continue; } foreach ( $widget_ids as $widget_id ) { $response = $this->prepare_item_for_response( compact( 'sidebar_id', 'widget_id' ), $request ); if ( ! is_wp_error( $response ) ) { $prepared[] = $this->prepare_response_for_collection( $response ); } } } return new WP_REST_Response( $prepared ); } /** * Checks if a given request has access to get a widget. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_item_permissions_check( $request ) { $this->retrieve_widgets(); $widget_id = $request['id']; $sidebar_id = wp_find_widgets_sidebar( $widget_id ); if ( $sidebar_id && $this->check_read_sidebar_permission( $sidebar_id ) ) { return true; } return $this->permissions_check( $request ); } /** * Checks if a sidebar can be read publicly. * * @since 5.9.0 * * @param string $sidebar_id The sidebar ID. * @return bool Whether the sidebar can be read. */ protected function check_read_sidebar_permission( $sidebar_id ) { $sidebar = wp_get_sidebar( $sidebar_id ); return ! empty( $sidebar['show_in_rest'] ); } /** * Gets an individual widget. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { $this->retrieve_widgets(); $widget_id = $request['id']; $sidebar_id = wp_find_widgets_sidebar( $widget_id ); if ( is_null( $sidebar_id ) ) { return new WP_Error( 'rest_widget_not_found', __( 'No widget was found with that id.' ), array( 'status' => 404 ) ); } return $this->prepare_item_for_response( compact( 'widget_id', 'sidebar_id' ), $request ); } /** * Checks if a given request has access to create widgets. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function create_item_permissions_check( $request ) { return $this->permissions_check( $request ); } /** * Creates a widget. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function create_item( $request ) { $sidebar_id = $request['sidebar']; $widget_id = $this->save_widget( $request, $sidebar_id ); if ( is_wp_error( $widget_id ) ) { return $widget_id; } wp_assign_widget_to_sidebar( $widget_id, $sidebar_id ); $request['context'] = 'edit'; $response = $this->prepare_item_for_response( compact( 'sidebar_id', 'widget_id' ), $request ); if ( is_wp_error( $response ) ) { return $response; } $response->set_status( 201 ); return $response; } /** * Checks if a given request has access to update widgets. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function update_item_permissions_check( $request ) { return $this->permissions_check( $request ); } /** * Updates an existing widget. * * @since 5.8.0 * * @global WP_Widget_Factory $wp_widget_factory * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function update_item( $request ) { global $wp_widget_factory; /* * retrieve_widgets() contains logic to move "hidden" or "lost" widgets to the * wp_inactive_widgets sidebar based on the contents of the $sidebars_widgets global. * * When batch requests are processed, this global is not properly updated by previous * calls, resulting in widgets incorrectly being moved to the wp_inactive_widgets * sidebar. * * See https://core.trac.wordpress.org/ticket/53657. */ wp_get_sidebars_widgets(); $this->retrieve_widgets(); $widget_id = $request['id']; $sidebar_id = wp_find_widgets_sidebar( $widget_id ); // Allow sidebar to be unset or missing when widget is not a WP_Widget. $parsed_id = wp_parse_widget_id( $widget_id ); $widget_object = $wp_widget_factory->get_widget_object( $parsed_id['id_base'] ); if ( is_null( $sidebar_id ) && $widget_object ) { return new WP_Error( 'rest_widget_not_found', __( 'No widget was found with that id.' ), array( 'status' => 404 ) ); } if ( $request->has_param( 'instance' ) || $request->has_param( 'form_data' ) ) { $maybe_error = $this->save_widget( $request, $sidebar_id ); if ( is_wp_error( $maybe_error ) ) { return $maybe_error; } } if ( $request->has_param( 'sidebar' ) ) { if ( $sidebar_id !== $request['sidebar'] ) { $sidebar_id = $request['sidebar']; wp_assign_widget_to_sidebar( $widget_id, $sidebar_id ); } } $request['context'] = 'edit'; return $this->prepare_item_for_response( compact( 'widget_id', 'sidebar_id' ), $request ); } /** * Checks if a given request has access to delete widgets. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function delete_item_permissions_check( $request ) { return $this->permissions_check( $request ); } /** * Deletes a widget. * * @since 5.8.0 * * @global WP_Widget_Factory $wp_widget_factory * @global array $wp_registered_widget_updates The registered widget update functions. * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function delete_item( $request ) { global $wp_widget_factory, $wp_registered_widget_updates; /* * retrieve_widgets() contains logic to move "hidden" or "lost" widgets to the * wp_inactive_widgets sidebar based on the contents of the $sidebars_widgets global. * * When batch requests are processed, this global is not properly updated by previous * calls, resulting in widgets incorrectly being moved to the wp_inactive_widgets * sidebar. * * See https://core.trac.wordpress.org/ticket/53657. */ wp_get_sidebars_widgets(); $this->retrieve_widgets(); $widget_id = $request['id']; $sidebar_id = wp_find_widgets_sidebar( $widget_id ); if ( is_null( $sidebar_id ) ) { return new WP_Error( 'rest_widget_not_found', __( 'No widget was found with that id.' ), array( 'status' => 404 ) ); } $request['context'] = 'edit'; if ( $request['force'] ) { $response = $this->prepare_item_for_response( compact( 'widget_id', 'sidebar_id' ), $request ); $parsed_id = wp_parse_widget_id( $widget_id ); $id_base = $parsed_id['id_base']; $original_post = $_POST; $original_request = $_REQUEST; $_POST = array( 'sidebar' => $sidebar_id, "widget-$id_base" => array(), 'the-widget-id' => $widget_id, 'delete_widget' => '1', ); $_REQUEST = $_POST; /** This action is documented in wp-admin/widgets-form.php */ do_action( 'delete_widget', $widget_id, $sidebar_id, $id_base ); $callback = $wp_registered_widget_updates[ $id_base ]['callback']; $params = $wp_registered_widget_updates[ $id_base ]['params']; if ( is_callable( $callback ) ) { ob_start(); call_user_func_array( $callback, $params ); ob_end_clean(); } $_POST = $original_post; $_REQUEST = $original_request; $widget_object = $wp_widget_factory->get_widget_object( $id_base ); if ( $widget_object ) { /* * WP_Widget sets `updated = true` after an update to prevent more than one widget * from being saved per request. This isn't what we want in the REST API, though, * as we support batch requests. */ $widget_object->updated = false; } wp_assign_widget_to_sidebar( $widget_id, '' ); $response->set_data( array( 'deleted' => true, 'previous' => $response->get_data(), ) ); } else { wp_assign_widget_to_sidebar( $widget_id, 'wp_inactive_widgets' ); $response = $this->prepare_item_for_response( array( 'sidebar_id' => 'wp_inactive_widgets', 'widget_id' => $widget_id, ), $request ); } /** * Fires after a widget is deleted via the REST API. * * @since 5.8.0 * * @param string $widget_id ID of the widget marked for deletion. * @param string $sidebar_id ID of the sidebar the widget was deleted from. * @param WP_REST_Response|WP_Error $response The response data, or WP_Error object on failure. * @param WP_REST_Request $request The request sent to the API. */ do_action( 'rest_delete_widget', $widget_id, $sidebar_id, $response, $request ); return $response; } /** * Performs a permissions check for managing widgets. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error */ protected function permissions_check( $request ) { if ( ! current_user_can( 'edit_theme_options' ) ) { return new WP_Error( 'rest_cannot_manage_widgets', __( 'Sorry, you are not allowed to manage widgets on this site.' ), array( 'status' => rest_authorization_required_code(), ) ); } return true; } /** * Looks for "lost" widgets once per request. * * @since 5.9.0 * * @see retrieve_widgets() */ protected function retrieve_widgets() { if ( ! $this->widgets_retrieved ) { retrieve_widgets(); $this->widgets_retrieved = true; } } /** * Saves the widget in the request object. * * @since 5.8.0 * * @global WP_Widget_Factory $wp_widget_factory * @global array $wp_registered_widget_updates The registered widget update functions. * * @param WP_REST_Request $request Full details about the request. * @param string $sidebar_id ID of the sidebar the widget belongs to. * @return string|WP_Error The saved widget ID. */ protected function save_widget( $request, $sidebar_id ) { global $wp_widget_factory, $wp_registered_widget_updates; require_once ABSPATH . 'wp-admin/includes/widgets.php'; // For next_widget_id_number(). if ( isset( $request['id'] ) ) { // Saving an existing widget. $id = $request['id']; $parsed_id = wp_parse_widget_id( $id ); $id_base = $parsed_id['id_base']; $number = isset( $parsed_id['number'] ) ? $parsed_id['number'] : null; $widget_object = $wp_widget_factory->get_widget_object( $id_base ); $creating = false; } elseif ( $request['id_base'] ) { // Saving a new widget. $id_base = $request['id_base']; $widget_object = $wp_widget_factory->get_widget_object( $id_base ); $number = $widget_object ? next_widget_id_number( $id_base ) : null; $id = $widget_object ? $id_base . '-' . $number : $id_base; $creating = true; } else { return new WP_Error( 'rest_invalid_widget', __( 'Widget type (id_base) is required.' ), array( 'status' => 400 ) ); } if ( ! isset( $wp_registered_widget_updates[ $id_base ] ) ) { return new WP_Error( 'rest_invalid_widget', __( 'The provided widget type (id_base) cannot be updated.' ), array( 'status' => 400 ) ); } if ( isset( $request['instance'] ) ) { if ( ! $widget_object ) { return new WP_Error( 'rest_invalid_widget', __( 'Cannot set instance on a widget that does not extend WP_Widget.' ), array( 'status' => 400 ) ); } if ( isset( $request['instance']['raw'] ) ) { if ( empty( $widget_object->widget_options['show_instance_in_rest'] ) ) { return new WP_Error( 'rest_invalid_widget', __( 'Widget type does not support raw instances.' ), array( 'status' => 400 ) ); } $instance = $request['instance']['raw']; } elseif ( isset( $request['instance']['encoded'], $request['instance']['hash'] ) ) { $serialized_instance = base64_decode( $request['instance']['encoded'] ); if ( ! hash_equals( wp_hash( $serialized_instance ), $request['instance']['hash'] ) ) { return new WP_Error( 'rest_invalid_widget', __( 'The provided instance is malformed.' ), array( 'status' => 400 ) ); } $instance = unserialize( $serialized_instance ); } else { return new WP_Error( 'rest_invalid_widget', __( 'The provided instance is invalid. Must contain raw OR encoded and hash.' ), array( 'status' => 400 ) ); } $form_data = array( "widget-$id_base" => array( $number => $instance, ), 'sidebar' => $sidebar_id, ); } elseif ( isset( $request['form_data'] ) ) { $form_data = $request['form_data']; } else { $form_data = array(); } $original_post = $_POST; $original_request = $_REQUEST; foreach ( $form_data as $key => $value ) { $slashed_value = wp_slash( $value ); $_POST[ $key ] = $slashed_value; $_REQUEST[ $key ] = $slashed_value; } $callback = $wp_registered_widget_updates[ $id_base ]['callback']; $params = $wp_registered_widget_updates[ $id_base ]['params']; if ( is_callable( $callback ) ) { ob_start(); call_user_func_array( $callback, $params ); ob_end_clean(); } $_POST = $original_post; $_REQUEST = $original_request; if ( $widget_object ) { // Register any multi-widget that the update callback just created. $widget_object->_set( $number ); $widget_object->_register_one( $number ); /* * WP_Widget sets `updated = true` after an update to prevent more than one widget * from being saved per request. This isn't what we want in the REST API, though, * as we support batch requests. */ $widget_object->updated = false; } /** * Fires after a widget is created or updated via the REST API. * * @since 5.8.0 * * @param string $id ID of the widget being saved. * @param string $sidebar_id ID of the sidebar containing the widget being saved. * @param WP_REST_Request $request Request object. * @param bool $creating True when creating a widget, false when updating. */ do_action( 'rest_after_save_widget', $id, $sidebar_id, $request, $creating ); return $id; } /** * Prepares the widget for the REST response. * * @since 5.8.0 * * @global WP_Widget_Factory $wp_widget_factory * @global array $wp_registered_widgets The registered widgets. * * @param array $item An array containing a widget_id and sidebar_id. * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function prepare_item_for_response( $item, $request ) { global $wp_widget_factory, $wp_registered_widgets; $widget_id = $item['widget_id']; $sidebar_id = $item['sidebar_id']; if ( ! isset( $wp_registered_widgets[ $widget_id ] ) ) { return new WP_Error( 'rest_invalid_widget', __( 'The requested widget is invalid.' ), array( 'status' => 500 ) ); } $widget = $wp_registered_widgets[ $widget_id ]; $parsed_id = wp_parse_widget_id( $widget_id ); $fields = $this->get_fields_for_response( $request ); $prepared = array( 'id' => $widget_id, 'id_base' => $parsed_id['id_base'], 'sidebar' => $sidebar_id, 'rendered' => '', 'rendered_form' => null, 'instance' => null, ); if ( rest_is_field_included( 'rendered', $fields ) && 'wp_inactive_widgets' !== $sidebar_id ) { $prepared['rendered'] = trim( wp_render_widget( $widget_id, $sidebar_id ) ); } if ( rest_is_field_included( 'rendered_form', $fields ) ) { $rendered_form = wp_render_widget_control( $widget_id ); if ( ! is_null( $rendered_form ) ) { $prepared['rendered_form'] = trim( $rendered_form ); } } if ( rest_is_field_included( 'instance', $fields ) ) { $widget_object = $wp_widget_factory->get_widget_object( $parsed_id['id_base'] ); if ( $widget_object && isset( $parsed_id['number'] ) ) { $all_instances = $widget_object->get_settings(); $instance = $all_instances[ $parsed_id['number'] ]; $serialized_instance = serialize( $instance ); $prepared['instance']['encoded'] = base64_encode( $serialized_instance ); $prepared['instance']['hash'] = wp_hash( $serialized_instance ); if ( ! empty( $widget_object->widget_options['show_instance_in_rest'] ) ) { // Use new stdClass so that JSON result is {} and not []. $prepared['instance']['raw'] = empty( $instance ) ? new stdClass : $instance; } } } $context = ! empty( $request['context'] ) ? $request['context'] : 'view'; $prepared = $this->add_additional_fields_to_object( $prepared, $request ); $prepared = $this->filter_response_by_context( $prepared, $context ); $response = rest_ensure_response( $prepared ); if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { $response->add_links( $this->prepare_links( $prepared ) ); } /** * Filters the REST API response for a widget. * * @since 5.8.0 * * @param WP_REST_Response|WP_Error $response The response object, or WP_Error object on failure. * @param array $widget The registered widget data. * @param WP_REST_Request $request Request used to generate the response. */ return apply_filters( 'rest_prepare_widget', $response, $widget, $request ); } /** * Prepares links for the widget. * * @since 5.8.0 * * @param array $prepared Widget. * @return array Links for the given widget. */ protected function prepare_links( $prepared ) { $id_base = ! empty( $prepared['id_base'] ) ? $prepared['id_base'] : $prepared['id']; return array( 'self' => array( 'href' => rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $prepared['id'] ) ), ), 'collection' => array( 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ), ), 'about' => array( 'href' => rest_url( sprintf( 'wp/v2/widget-types/%s', $id_base ) ), 'embeddable' => true, ), 'https://api.w.org/sidebar' => array( 'href' => rest_url( sprintf( 'wp/v2/sidebars/%s/', $prepared['sidebar'] ) ), ), ); } /** * Gets the list of collection params. * * @since 5.8.0 * * @return array[] */ public function get_collection_params() { return array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), 'sidebar' => array( 'description' => __( 'The sidebar to return widgets for.' ), 'type' => 'string', ), ); } /** * Retrieves the widget's schema, conforming to JSON Schema. * * @since 5.8.0 * * @return array Item schema data. */ 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' => 'widget', 'type' => 'object', 'properties' => array( 'id' => array( 'description' => __( 'Unique identifier for the widget.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), ), 'id_base' => array( 'description' => __( 'The type of the widget. Corresponds to ID in widget-types endpoint.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), ), 'sidebar' => array( 'description' => __( 'The sidebar the widget belongs to.' ), 'type' => 'string', 'default' => 'wp_inactive_widgets', 'required' => true, 'context' => array( 'view', 'edit', 'embed' ), ), 'rendered' => array( 'description' => __( 'HTML representation of the widget.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'rendered_form' => array( 'description' => __( 'HTML representation of the widget admin form.' ), 'type' => 'string', 'context' => array( 'edit' ), 'readonly' => true, ), 'instance' => array( 'description' => __( 'Instance settings of the widget, if supported.' ), 'type' => 'object', 'context' => array( 'edit' ), 'default' => null, 'properties' => array( 'encoded' => array( 'description' => __( 'Base64 encoded representation of the instance settings.' ), 'type' => 'string', 'context' => array( 'edit' ), ), 'hash' => array( 'description' => __( 'Cryptographic hash of the instance settings.' ), 'type' => 'string', 'context' => array( 'edit' ), ), 'raw' => array( 'description' => __( 'Unencoded instance settings, if supported.' ), 'type' => 'object', 'context' => array( 'edit' ), ), ), ), 'form_data' => array( 'description' => __( 'URL-encoded form data from the widget admin form. Used to update a widget that does not support instance. Write only.' ), 'type' => 'string', 'context' => array(), 'arg_options' => array( 'sanitize_callback' => static function( $string ) { $array = array(); wp_parse_str( $string, $array ); return $array; }, ), ), ), ); return $this->add_additional_fields_schema( $this->schema ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
programming_docs
wordpress class IXR_Base64 {} class IXR\_Base64 {} ==================== [IXR\_Base64](ixr_base64) * [\_\_construct](ixr_base64/__construct) β€” PHP5 constructor. * [getXml](ixr_base64/getxml) * [IXR\_Base64](ixr_base64/ixr_base64) β€” PHP4 constructor. File: `wp-includes/IXR/class-IXR-base64.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-base64.php/) ``` class IXR_Base64 { var $data; /** * PHP5 constructor. */ function __construct( $data ) { $this->data = $data; } /** * PHP4 constructor. */ public function IXR_Base64( $data ) { self::__construct( $data ); } function getXml() { return '<base64>'.base64_encode($this->data).'</base64>'; } } ``` | Version | Description | | --- | --- | | [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. | wordpress class WP_Taxonomy {} class WP\_Taxonomy {} ===================== Core class used for interacting with taxonomies. * [\_\_construct](wp_taxonomy/__construct) β€” Constructor. * [add\_hooks](wp_taxonomy/add_hooks) β€” Registers the ajax callback for the meta box. * [add\_rewrite\_rules](wp_taxonomy/add_rewrite_rules) β€” Adds the necessary rewrite rules for the taxonomy. * [get\_default\_labels](wp_taxonomy/get_default_labels) β€” Returns the default labels for taxonomies. * [get\_rest\_controller](wp_taxonomy/get_rest_controller) β€” Gets the REST API controller for this taxonomy. * [remove\_hooks](wp_taxonomy/remove_hooks) β€” Removes the ajax callback for the meta box. * [remove\_rewrite\_rules](wp_taxonomy/remove_rewrite_rules) β€” Removes any rewrite rules, permastructs, and rules for the taxonomy. * [reset\_default\_labels](wp_taxonomy/reset_default_labels) β€” Resets the cache for the default labels. * [set\_props](wp_taxonomy/set_props) β€” Sets taxonomy properties. File: `wp-includes/class-wp-taxonomy.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-taxonomy.php/) ``` final class WP_Taxonomy { /** * Taxonomy key. * * @since 4.7.0 * @var string */ public $name; /** * Name of the taxonomy shown in the menu. Usually plural. * * @since 4.7.0 * @var string */ public $label; /** * Labels object for this taxonomy. * * If not set, tag labels are inherited for non-hierarchical types * and category labels for hierarchical ones. * * @see get_taxonomy_labels() * * @since 4.7.0 * @var stdClass */ public $labels; /** * Default labels. * * @since 6.0.0 * @var (string|null)[][] $default_labels */ protected static $default_labels = array(); /** * A short descriptive summary of what the taxonomy is for. * * @since 4.7.0 * @var string */ public $description = ''; /** * Whether a taxonomy is intended for use publicly either via the admin interface or by front-end users. * * @since 4.7.0 * @var bool */ public $public = true; /** * Whether the taxonomy is publicly queryable. * * @since 4.7.0 * @var bool */ public $publicly_queryable = true; /** * Whether the taxonomy is hierarchical. * * @since 4.7.0 * @var bool */ public $hierarchical = false; /** * Whether to generate and allow a UI for managing terms in this taxonomy in the admin. * * @since 4.7.0 * @var bool */ public $show_ui = true; /** * Whether to show the taxonomy in the admin menu. * * If true, the taxonomy is shown as a submenu of the object type menu. If false, no menu is shown. * * @since 4.7.0 * @var bool */ public $show_in_menu = true; /** * Whether the taxonomy is available for selection in navigation menus. * * @since 4.7.0 * @var bool */ public $show_in_nav_menus = true; /** * Whether to list the taxonomy in the tag cloud widget controls. * * @since 4.7.0 * @var bool */ public $show_tagcloud = true; /** * Whether to show the taxonomy in the quick/bulk edit panel. * * @since 4.7.0 * @var bool */ public $show_in_quick_edit = true; /** * Whether to display a column for the taxonomy on its post type listing screens. * * @since 4.7.0 * @var bool */ public $show_admin_column = false; /** * The callback function for the meta box display. * * @since 4.7.0 * @var bool|callable */ public $meta_box_cb = null; /** * The callback function for sanitizing taxonomy data saved from a meta box. * * @since 5.1.0 * @var callable */ public $meta_box_sanitize_cb = null; /** * An array of object types this taxonomy is registered for. * * @since 4.7.0 * @var string[] */ public $object_type = null; /** * Capabilities for this taxonomy. * * @since 4.7.0 * @var stdClass */ public $cap; /** * Rewrites information for this taxonomy. * * @since 4.7.0 * @var array|false */ public $rewrite; /** * Query var string for this taxonomy. * * @since 4.7.0 * @var string|false */ public $query_var; /** * Function that will be called when the count is updated. * * @since 4.7.0 * @var callable */ public $update_count_callback; /** * Whether this taxonomy should appear in the REST API. * * Default false. If true, standard endpoints will be registered with * respect to $rest_base and $rest_controller_class. * * @since 4.7.4 * @var bool $show_in_rest */ public $show_in_rest; /** * The base path for this taxonomy's REST API endpoints. * * @since 4.7.4 * @var string|bool $rest_base */ public $rest_base; /** * The namespace for this taxonomy's REST API endpoints. * * @since 5.9.0 * @var string|bool $rest_namespace */ public $rest_namespace; /** * The controller for this taxonomy's REST API endpoints. * * Custom controllers must extend WP_REST_Controller. * * @since 4.7.4 * @var string|bool $rest_controller_class */ public $rest_controller_class; /** * The controller instance for this taxonomy's REST API endpoints. * * Lazily computed. Should be accessed using {@see WP_Taxonomy::get_rest_controller()}. * * @since 5.5.0 * @var WP_REST_Controller $rest_controller */ public $rest_controller; /** * The default term name for this taxonomy. If you pass an array you have * to set 'name' and optionally 'slug' and 'description'. * * @since 5.5.0 * @var array|string */ public $default_term; /** * Whether terms in this taxonomy should be sorted in the order they are provided to `wp_set_object_terms()`. * * Use this in combination with `'orderby' => 'term_order'` when fetching terms. * * @since 2.5.0 * @var bool|null */ public $sort = null; /** * Array of arguments to automatically use inside `wp_get_object_terms()` for this taxonomy. * * @since 2.6.0 * @var array|null */ public $args = null; /** * Whether it is a built-in taxonomy. * * @since 4.7.0 * @var bool */ public $_builtin; /** * Constructor. * * See the register_taxonomy() function for accepted arguments for `$args`. * * @since 4.7.0 * * @global WP $wp Current WordPress environment instance. * * @param string $taxonomy Taxonomy key, must not exceed 32 characters. * @param array|string $object_type Name of the object type for the taxonomy object. * @param array|string $args Optional. Array or query string of arguments for registering a taxonomy. * Default empty array. */ public function __construct( $taxonomy, $object_type, $args = array() ) { $this->name = $taxonomy; $this->set_props( $object_type, $args ); } /** * Sets taxonomy properties. * * See the register_taxonomy() function for accepted arguments for `$args`. * * @since 4.7.0 * * @param string|string[] $object_type Name or array of names of the object types for the taxonomy. * @param array|string $args Array or query string of arguments for registering a taxonomy. */ 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; } /** * Adds the necessary rewrite rules for the taxonomy. * * @since 4.7.0 * * @global WP $wp Current WordPress environment instance. */ 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 ); } } /** * Removes any rewrite rules, permastructs, and rules for the taxonomy. * * @since 4.7.0 * * @global WP $wp Current WordPress environment instance. */ 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 ); } } /** * Registers the ajax callback for the meta box. * * @since 4.7.0 */ public function add_hooks() { add_filter( 'wp_ajax_add-' . $this->name, '_wp_ajax_add_hierarchical_term' ); } /** * Removes the ajax callback for the meta box. * * @since 4.7.0 */ public function remove_hooks() { remove_filter( 'wp_ajax_add-' . $this->name, '_wp_ajax_add_hierarchical_term' ); } /** * Gets the REST API controller for this taxonomy. * * Will only instantiate the controller class once per request. * * @since 5.5.0 * * @return WP_REST_Controller|null The controller instance, or null if the taxonomy * is set not to show in rest. */ 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; } /** * Returns the default labels for taxonomies. * * @since 6.0.0 * * @return (string|null)[][] The default labels for taxonomies. */ 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 &#8220;slug&#8221; 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( __( '&larr; Go to Tags' ), __( '&larr; 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; } /** * Resets the cache for the default labels. * * @since 6.0.0 */ public static function reset_default_labels() { self::$default_labels = array(); } } ``` | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
programming_docs
wordpress class WP_List_Table {} class WP\_List\_Table {} ======================== Base class for displaying a list of items in an ajaxified HTML table. Note: This class’s access is marked as private. That means it is not intended for use by plugin and theme developers as it is subject to change without warning in any future WordPress release. If you would still like to make use of the class, you should make a copy to use and distribute with your own project, or else use it at your own risk. This class is used to generate the List Tables that populate WordPress’ various admin screens. It has an advantage over previous implementations in that it can be dynamically altered with AJAX and may be hooked in future WordPress releases. On March 27, 2012, [Andrew Nacin](https://profiles.wordpress.org/nacin) [warned developers](http://wpengineer.com/2426/wp_list_table-a-step-by-step-guide/#comment-9617) that this class was created for private core use only as it may be subject to change in any future WordPress release. Nevertheless, [the](http://kovshenin.com/2012/wp_list_table-tutorial/#comment-10362) [WP\_List\_Table](wp_list_table) class has become widely used by plugins and WordPress developers as it provides a reliable, consistent, and semantic way to create custom list tables in WordPress. To date, no major changes have occurred in this class or are scheduled to occur, so testing your plugin with beta/RC phases of WordPress development should be more than enough to avoid any major issues. If you are at all uncomfortable with this risk, a common (and safe) workaround is to **make a copy the [WP\_List\_Table](wp_list_table) class ( `[/wp-admin/includes/class-wp-list-table.php](https://core.trac.wordpress.org/browser/tags/5.5.1/src//wp-admin/includes/class-wp-list-table.php#L0)` ) to use and distribute in your plugins**, instead of using the original core class. This way, if the core class should ever change, your plugins will continue to work as-is. Developers should use this class at their own risk. This class is meant to be used as a kind of framework, since any data queries need to be loaded, sorted, and filtered manually. Nevertheless, it is potentially a very powerful tool for developers as it creates WordPress-standard list tables, which makes it very easy to implement advanced features like pagination, actions, bulk actions, and filtering. To use the [WP\_List\_Table](wp_list_table), you first create a new class that extends the original. Your new class must be instantiated, and the prepare\_items() and display() methods called explicitly on the instance. See the method descriptions below for more details. The WordPress core loads and returns its classes dynamically by using the [\_get\_list\_table()](../functions/_get_list_table) function, which automatically loads the appropriate extended class and instantiates it. *This is a private function, however, and should not be used by developers.* Since this class is marked as private, developers should use this only at their own risk as this class is subject to change in future WordPress releases. Any developers using this class are **strongly** encouraged to test their plugins with all WordPress beta/RC releases to maintain compatibility. Since developers cannot use the [\_get\_list\_table()](../functions/_get_list_table) function directly, the class needs to be extended and instantiated manually, like so… ``` class Example_List_Table extends WP_List_Table {} $example_lt = new Example_List_Table(); ``` The above example won’t be able to output anything meaningful, however, as several methods MUST be specified (as well as your data) in order for [WP\_List\_Table](wp_list_table) to render a useful table. Please refer source code for the complete lists of methods and properties. Below description may cover some of them. The following properties are built into the base [WP\_List\_Table](wp_list_table) class. Note that the magic methods \_\_get and \_\_set of [WP\_List\_Table](wp_list_table) will prevent setting other class instance variables in a subclass of [WP\_List\_Table](wp_list_table), please use the recommended variables: $items This is used to store the raw data you want to display. Generally you will set this property directly in the prepare\_items() method. $\_args Stores various information about the current table (as an array). This generally isn’t manipulated directly. $\_pagination\_args Stores information needed for handling table pagination (as an array). This generally isn’t manipulated directly, but rather used with get\_pagination\_arg( string ) or set\_pagination\_args(array). $screen This can be used to store the current screen, when it’s necessary to keep it consistent with the entire instance. $\_actions Stores cached bulk actions. This generally isn’t manipulated directly. $\_pagination Stores cached pagination output. This generally isn’t manipulated directly. These properties are not built-in, but are expected by several class methods. You must define them manually in your extended class. $\_column\_headers In core, this property is assigned automatically. Developers **must** manually define it in their prepare\_items() *or* \_\_construct() methods. This property requires a 4-value array : * The first value is an array containing column slugs and titles (see the get\_columns() method). * The second value is an array containing the values of fields to be hidden. * The third value is an array of columns that should allow sorting (see the get\_sortable\_columns() method). * The fourth value is a string defining which column is deemed to be the primary one, displaying the row’s actions (edit, view, etc). The value should match that of one of your column slugs in the first value. These methods are not included in the base class but can, and should, be defined in your extended class! column\_default( $item, $column\_name ) 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://codex.wordpress.org/Version_3.5.1 "Version 3.5.1"), in core $item is passed an Object, not an array. column\_$custom( $item ) Custom columns must be provided by the developer and can be used to handle each type column individually. For example: if a method named *column\_movie\_title()* were provided, it would be used to render any column that had the slug β€œmovie\_titleβ€œ. This function accepts one argument – a single **$item** array. **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. * [\_\_call](wp_list_table/__call) β€” Make private/protected methods readable for backward compatibility. * [\_\_construct](wp_list_table/__construct) β€” Constructor. * [\_\_get](wp_list_table/__get) β€” Make private properties readable for backward compatibility. * [\_\_isset](wp_list_table/__isset) β€” Make private properties checkable for backward compatibility. * [\_\_set](wp_list_table/__set) β€” Make private properties settable for backward compatibility. * [\_\_unset](wp_list_table/__unset) β€” Make private properties un-settable for backward compatibility. * [\_js\_vars](wp_list_table/_js_vars) β€” Sends required variables to JavaScript land. * [ajax\_response](wp_list_table/ajax_response) β€” Handles an incoming ajax request (called from admin-ajax.php) * [ajax\_user\_can](wp_list_table/ajax_user_can) β€” Checks the current user's permissions * [bulk\_actions](wp_list_table/bulk_actions) β€” Displays the bulk actions dropdown. * [column\_cb](wp_list_table/column_cb) * [column\_default](wp_list_table/column_default) * [comments\_bubble](wp_list_table/comments_bubble) β€” Displays a comment count bubble. * [current\_action](wp_list_table/current_action) β€” Gets the current action selected from the bulk actions dropdown. * [display](wp_list_table/display) β€” Displays the table. * [display\_rows](wp_list_table/display_rows) β€” Generates the table rows. * [display\_rows\_or\_placeholder](wp_list_table/display_rows_or_placeholder) β€” Generates the tbody element for the list table. * [display\_tablenav](wp_list_table/display_tablenav) β€” Generates the table navigation above or below the table * [extra\_tablenav](wp_list_table/extra_tablenav) β€” Extra controls to be displayed between bulk actions and pagination. * [get\_bulk\_actions](wp_list_table/get_bulk_actions) β€” Retrieves the list of bulk actions available for this table. * [get\_column\_count](wp_list_table/get_column_count) β€” Returns the number of visible columns. * [get\_column\_info](wp_list_table/get_column_info) β€” Gets a list of all, hidden, and sortable columns, with filter applied. * [get\_columns](wp_list_table/get_columns) β€” Gets a list of columns. * [get\_default\_primary\_column\_name](wp_list_table/get_default_primary_column_name) β€” Gets the name of the default primary column. * [get\_items\_per\_page](wp_list_table/get_items_per_page) β€” Gets the number of items to display on a single page. * [get\_pagenum](wp_list_table/get_pagenum) β€” Gets the current page number. * [get\_pagination\_arg](wp_list_table/get_pagination_arg) β€” Access the pagination args. * [get\_primary\_column](wp_list_table/get_primary_column) β€” Public wrapper for WP\_List\_Table::get\_default\_primary\_column\_name(). * [get\_primary\_column\_name](wp_list_table/get_primary_column_name) β€” Gets the name of the primary column. * [get\_sortable\_columns](wp_list_table/get_sortable_columns) β€” Gets a list of sortable columns. * [get\_table\_classes](wp_list_table/get_table_classes) β€” Gets a list of CSS classes for the WP\_List\_Table table tag. * [get\_views](wp_list_table/get_views) β€” Gets the list of views available on this table. * [get\_views\_links](wp_list_table/get_views_links) β€” Generates views links. * [handle\_row\_actions](wp_list_table/handle_row_actions) β€” Generates and display row actions links for the list table. * [has\_items](wp_list_table/has_items) β€” Whether the table has items to display or not * [months\_dropdown](wp_list_table/months_dropdown) β€” Displays a dropdown for filtering items in the list table by month. * [no\_items](wp_list_table/no_items) β€” Message to be displayed when there are no items * [pagination](wp_list_table/pagination) β€” Displays the pagination. * [prepare\_items](wp_list_table/prepare_items) β€” Prepares the list of items for displaying. * [print\_column\_headers](wp_list_table/print_column_headers) β€” Prints column headers, accounting for hidden and sortable columns. * [row\_actions](wp_list_table/row_actions) β€” Generates the required HTML for a list of row action links. * [search\_box](wp_list_table/search_box) β€” Displays the search box. * [set\_pagination\_args](wp_list_table/set_pagination_args) β€” An internal method that sets all the necessary pagination arguments * [single\_row](wp_list_table/single_row) β€” Generates content for a single row of the table. * [single\_row\_columns](wp_list_table/single_row_columns) β€” Generates the columns for a single row of the table. * [view\_switcher](wp_list_table/view_switcher) β€” Displays a view switcher. * [views](wp_list_table/views) β€” Displays the list of views available on 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/) ``` class WP_List_Table { /** * The current list of items. * * @since 3.1.0 * @var array */ public $items; /** * Various information about the current table. * * @since 3.1.0 * @var array */ protected $_args; /** * Various information needed for displaying the pagination. * * @since 3.1.0 * @var array */ protected $_pagination_args = array(); /** * The current screen. * * @since 3.1.0 * @var WP_Screen */ protected $screen; /** * Cached bulk actions. * * @since 3.1.0 * @var array */ private $_actions; /** * Cached pagination output. * * @since 3.1.0 * @var string */ private $_pagination; /** * The view switcher modes. * * @since 4.1.0 * @var array */ protected $modes = array(); /** * Stores the value returned by ->get_column_info(). * * @since 4.1.0 * @var array */ protected $_column_headers; /** * {@internal Missing Summary} * * @var array */ protected $compat_fields = array( '_args', '_pagination_args', 'screen', '_actions', '_pagination' ); /** * {@internal Missing Summary} * * @var array */ protected $compat_methods = array( 'set_pagination_args', 'get_views', 'get_bulk_actions', 'bulk_actions', 'row_actions', 'months_dropdown', 'view_switcher', 'comments_bubble', 'get_items_per_page', 'pagination', 'get_sortable_columns', 'get_column_info', 'get_table_classes', 'display_tablenav', 'extra_tablenav', 'single_row_columns', ); /** * Constructor. * * The child class should call this constructor from its own constructor to override * the default $args. * * @since 3.1.0 * * @param array|string $args { * Array or string of arguments. * * @type string $plural Plural 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'. Default empty. * @type string $singular Singular label for an object being listed, e.g. 'post'. * Default empty * @type bool $ajax Whether 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. * @type string $screen String containing the hook name used to determine the current * screen. If left null, the current screen will be automatically set. * Default null. * } */ 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' ), ); } } /** * Make private properties readable for backward compatibility. * * @since 4.0.0 * * @param string $name Property to get. * @return mixed Property. */ public function __get( $name ) { if ( in_array( $name, $this->compat_fields, true ) ) { return $this->$name; } } /** * Make private properties settable for backward compatibility. * * @since 4.0.0 * * @param string $name Property to check if set. * @param mixed $value Property value. * @return mixed Newly-set property. */ public function __set( $name, $value ) { if ( in_array( $name, $this->compat_fields, true ) ) { return $this->$name = $value; } } /** * Make private properties checkable for backward compatibility. * * @since 4.0.0 * * @param string $name Property to check if set. * @return bool Whether the property is a back-compat property and it is set. */ public function __isset( $name ) { if ( in_array( $name, $this->compat_fields, true ) ) { return isset( $this->$name ); } return false; } /** * Make private properties un-settable for backward compatibility. * * @since 4.0.0 * * @param string $name Property to unset. */ public function __unset( $name ) { if ( in_array( $name, $this->compat_fields, true ) ) { unset( $this->$name ); } } /** * Make private/protected methods readable for backward compatibility. * * @since 4.0.0 * * @param string $name Method to call. * @param array $arguments Arguments to pass when calling. * @return mixed|bool Return value of the callback, false otherwise. */ public function __call( $name, $arguments ) { if ( in_array( $name, $this->compat_methods, true ) ) { return $this->$name( ...$arguments ); } return false; } /** * Checks the current user's permissions * * @since 3.1.0 * @abstract */ public function ajax_user_can() { die( 'function WP_List_Table::ajax_user_can() must be overridden in a subclass.' ); } /** * Prepares the list of items for displaying. * * @uses WP_List_Table::set_pagination_args() * * @since 3.1.0 * @abstract */ public function prepare_items() { die( 'function WP_List_Table::prepare_items() must be overridden in a subclass.' ); } /** * An internal method that sets all the necessary pagination arguments * * @since 3.1.0 * * @param array|string $args Array or string of arguments with information about the pagination. */ 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; } /** * Access the pagination args. * * @since 3.1.0 * * @param string $key Pagination argument to retrieve. Common values include 'total_items', * 'total_pages', 'per_page', or 'infinite_scroll'. * @return int Number of items that correspond to the given pagination argument. */ 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; } /** * Whether the table has items to display or not * * @since 3.1.0 * * @return bool */ public function has_items() { return ! empty( $this->items ); } /** * Message to be displayed when there are no items * * @since 3.1.0 */ public function no_items() { _e( 'No items found.' ); } /** * Displays the search box. * * @since 3.1.0 * * @param string $text The 'submit' button label. * @param string $input_id ID attribute value for the search input field. */ 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 } /** * Generates views links. * * @since 6.1.0 * * @param array $link_data { * An array of link data. * * @type string $url The link URL. * @type string $label The link label. * @type bool $current Optional. Whether this is the currently selected view. * } * @return array An array of link markup. Keys match the `$link_data` input array. */ 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; } /** * Gets the list of views available on this table. * * The format is an associative array: * - `'id' => 'link'` * * @since 3.1.0 * * @return array */ protected function get_views() { return array(); } /** * Displays the list of views available on this table. * * @since 3.1.0 */ 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>'; } /** * 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', * ] * ] * * @since 3.1.0 * @since 5.6.0 A bulk action can now contain an array of options in order to create an optgroup. * * @return array */ protected function get_bulk_actions() { return array(); } /** * Displays the bulk actions dropdown. * * @since 3.1.0 * * @param string $which The location of the bulk actions: 'top' or 'bottom'. * This is designated as optional for backward compatibility. */ 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"; } /** * Gets the current action selected from the bulk actions dropdown. * * @since 3.1.0 * * @return string|false The action name. False if no action was selected. */ 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; } /** * Generates the required HTML for a list of row action links. * * @since 3.1.0 * * @param string[] $actions An array of action links. * @param bool $always_visible Whether the actions should be always visible. * @return string The HTML for the row actions. */ 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; } /** * Displays a dropdown for filtering items in the list table by month. * * @since 3.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * @global WP_Locale $wp_locale WordPress date and time locale object. * * @param string $post_type The post type. */ 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 } /** * Displays a view switcher. * * @since 3.1.0 * * @param string $current_mode */ 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 } /** * Displays a comment count bubble. * * @since 3.1.0 * * @param int $post_id The post ID. * @param int $pending_comments Number of pending comments. */ 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">&#8212;</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' ) ); } } /** * Gets the current page number. * * @since 3.1.0 * * @return int */ 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 ); } /** * Gets the number of items to display on a single page. * * @since 3.1.0 * * @param string $option User option name. * @param int $default_value Optional. The number of items to display. Default 20. * @return int */ 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 ); } /** * Displays the pagination. * * @since 3.1.0 * * @param string $which */ 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">&laquo;</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' ), '&laquo;' ); } if ( $disable_prev ) { $page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">&lsaquo;</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' ), '&lsaquo;' ); } 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">&rsaquo;</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' ), '&rsaquo;' ); } if ( $disable_last ) { $page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">&raquo;</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' ), '&raquo;' ); } $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; } /** * Gets a list of columns. * * The format is: * - `'internal-name' => 'Title'` * * @since 3.1.0 * @abstract * * @return array */ public function get_columns() { die( 'function WP_List_Table::get_columns() must be overridden in a subclass.' ); } /** * 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. * * @since 3.1.0 * * @return array */ protected function get_sortable_columns() { return array(); } /** * Gets the name of the default primary column. * * @since 4.3.0 * * @return string Name of the default primary column, in this case, an empty string. */ 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; } /** * Public wrapper for WP_List_Table::get_default_primary_column_name(). * * @since 4.4.0 * * @return string Name of the default primary column. */ public function get_primary_column() { return $this->get_primary_column_name(); } /** * Gets the name of the primary column. * * @since 4.3.0 * * @return string The name of the primary column. */ 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; } /** * Gets a list of all, hidden, and sortable columns, with filter applied. * * @since 3.1.0 * * @return array */ 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; } /** * Returns the number of visible columns. * * @since 3.1.0 * * @return int */ 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 ); } /** * Prints column headers, accounting for hidden and sortable columns. * * @since 3.1.0 * * @param bool $with_id Whether to set the ID attribute or not */ 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>"; } } /** * Displays the table. * * @since 3.1.0 */ 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' ); } /** * Gets a list of CSS classes for the WP_List_Table table tag. * * @since 3.1.0 * * @return string[] Array of CSS classes for the table tag. */ 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'] ); } /** * Generates the table navigation above or below the table * * @since 3.1.0 * @param string $which */ 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 } /** * Extra controls to be displayed between bulk actions and pagination. * * @since 3.1.0 * * @param string $which */ protected function extra_tablenav( $which ) {} /** * Generates the tbody element for the list table. * * @since 3.1.0 */ 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>'; } } /** * Generates the table rows. * * @since 3.1.0 */ public function display_rows() { foreach ( $this->items as $item ) { $this->single_row( $item ); } } /** * Generates content for a single row of the table. * * @since 3.1.0 * * @param object|array $item The current item */ public function single_row( $item ) { echo '<tr>'; $this->single_row_columns( $item ); echo '</tr>'; } /** * @param object|array $item * @param string $column_name */ protected function column_default( $item, $column_name ) {} /** * @param object|array $item */ protected function column_cb( $item ) {} /** * Generates the columns for a single row of the table. * * @since 3.1.0 * * @param object|array $item The current item. */ 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>'; } } } /** * Generates and display row actions links for the list table. * * @since 4.3.0 * * @param object|array $item The item being acted upon. * @param string $column_name Current column name. * @param string $primary Primary column name. * @return string The row actions HTML, or an empty string * if the current column is not the primary column. */ 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>' : ''; } /** * Handles an incoming ajax request (called from admin-ajax.php) * * @since 3.1.0 */ 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 ) ); } /** * Sends required variables to JavaScript land. * * @since 3.1.0 */ 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 ) ); } } ``` | Used By | Description | | --- | --- | | [WP\_Application\_Passwords\_List\_Table](wp_application_passwords_list_table) wp-admin/includes/class-wp-application-passwords-list-table.php | Class for displaying the list of application password items. | | [WP\_Privacy\_Requests\_Table](wp_privacy_requests_table) wp-admin/includes/class-wp-privacy-requests-table.php | List Table API: [WP\_Privacy\_Requests\_Table](wp_privacy_requests_table) class | | [WP\_MS\_Users\_List\_Table](wp_ms_users_list_table) wp-admin/includes/class-wp-ms-users-list-table.php | Core class used to implement displaying users in a list table for the network admin. | | [WP\_Plugins\_List\_Table](wp_plugins_list_table) wp-admin/includes/class-wp-plugins-list-table.php | Core class used to implement displaying installed plugins in a list table. | | [WP\_Links\_List\_Table](wp_links_list_table) wp-admin/includes/class-wp-links-list-table.php | Core class used to implement displaying links in a list table. | | [WP\_MS\_Themes\_List\_Table](wp_ms_themes_list_table) wp-admin/includes/class-wp-ms-themes-list-table.php | Core class used to implement displaying themes in a list table for the network admin. | | [\_WP\_List\_Table\_Compat](_wp_list_table_compat) wp-admin/includes/class-wp-list-table-compat.php | Helper class to be used only by back compat functions. | | [WP\_Plugin\_Install\_List\_Table](wp_plugin_install_list_table) wp-admin/includes/class-wp-plugin-install-list-table.php | Core class used to implement displaying plugins to install in a list table. | | [WP\_Themes\_List\_Table](wp_themes_list_table) wp-admin/includes/class-wp-themes-list-table.php | Core class used to implement displaying installed themes in a list table. | | [WP\_MS\_Sites\_List\_Table](wp_ms_sites_list_table) wp-admin/includes/class-wp-ms-sites-list-table.php | Core class used to implement displaying sites in a list table for the network admin. | | [WP\_Users\_List\_Table](wp_users_list_table) wp-admin/includes/class-wp-users-list-table.php | Core class used to implement displaying users in a list table. | | [WP\_Media\_List\_Table](wp_media_list_table) wp-admin/includes/class-wp-media-list-table.php | Core class used to implement displaying media items in a list table. | | [WP\_Comments\_List\_Table](wp_comments_list_table) wp-admin/includes/class-wp-comments-list-table.php | Core class used to implement displaying comments in a list table. | | [WP\_Terms\_List\_Table](wp_terms_list_table) wp-admin/includes/class-wp-terms-list-table.php | Core class used to implement displaying terms in a list table. | | [WP\_Posts\_List\_Table](wp_posts_list_table) wp-admin/includes/class-wp-posts-list-table.php | Core class used to implement displaying posts in a list table. | | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
programming_docs
wordpress class WP_Sitemaps_Registry {} class WP\_Sitemaps\_Registry {} =============================== Class [WP\_Sitemaps\_Registry](wp_sitemaps_registry). * [add\_provider](wp_sitemaps_registry/add_provider) β€” Adds a new sitemap provider. * [get\_provider](wp_sitemaps_registry/get_provider) β€” Returns a single registered sitemap provider. * [get\_providers](wp_sitemaps_registry/get_providers) β€” Returns all registered 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/) ``` class WP_Sitemaps_Registry { /** * Registered sitemap providers. * * @since 5.5.0 * * @var WP_Sitemaps_Provider[] Array of registered sitemap providers. */ private $providers = array(); /** * Adds a new sitemap provider. * * @since 5.5.0 * * @param string $name Name of the sitemap provider. * @param WP_Sitemaps_Provider $provider Instance of a WP_Sitemaps_Provider. * @return bool Whether the provider was added successfully. */ 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; } /** * Returns a single registered sitemap provider. * * @since 5.5.0 * * @param string $name Sitemap provider name. * @return WP_Sitemaps_Provider|null Sitemap provider if it exists, null otherwise. */ public function get_provider( $name ) { if ( ! is_string( $name ) || ! isset( $this->providers[ $name ] ) ) { return null; } return $this->providers[ $name ]; } /** * Returns all registered sitemap providers. * * @since 5.5.0 * * @return WP_Sitemaps_Provider[] Array of sitemap providers. */ public function get_providers() { return $this->providers; } } ``` | Version | Description | | --- | --- | | [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. | wordpress class MO {} class MO {} =========== * [export](mo/export) * [export\_headers](mo/export_headers) * [export\_original](mo/export_original) * [export\_to\_file](mo/export_to_file) * [export\_to\_file\_handle](mo/export_to_file_handle) * [export\_translations](mo/export_translations) * [get\_byteorder](mo/get_byteorder) * [get\_filename](mo/get_filename) β€” Returns the loaded MO file. * [get\_plural\_forms\_count](mo/get_plural_forms_count) * [import\_from\_file](mo/import_from_file) β€” Fills up with the entries from MO file $filename * [import\_from\_reader](mo/import_from_reader) * [is\_entry\_good\_for\_export](mo/is_entry_good_for_export) * [make\_entry](mo/make_entry) β€” Build a Translation\_Entry from original string and translation strings, found in a MO file * [select\_plural\_form](mo/select_plural_form) File: `wp-includes/pomo/mo.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/mo.php/) ``` class MO extends Gettext_Translations { /** * Number of plural forms. * * @var int */ public $_nplurals = 2; /** * Loaded MO file. * * @var string */ private $filename = ''; /** * Returns the loaded MO file. * * @return string The loaded MO file. */ public function get_filename() { return $this->filename; } /** * Fills up with the entries from MO file $filename * * @param string $filename MO file to load * @return bool True if the import from file was successful, otherwise false. */ public function import_from_file( $filename ) { $reader = new POMO_FileReader( $filename ); if ( ! $reader->is_resource() ) { return false; } $this->filename = (string) $filename; return $this->import_from_reader( $reader ); } /** * @param string $filename * @return bool */ public function export_to_file( $filename ) { $fh = fopen( $filename, 'wb' ); if ( ! $fh ) { return false; } $res = $this->export_to_file_handle( $fh ); fclose( $fh ); return $res; } /** * @return string|false */ public function export() { $tmp_fh = fopen( 'php://temp', 'r+' ); if ( ! $tmp_fh ) { return false; } $this->export_to_file_handle( $tmp_fh ); rewind( $tmp_fh ); return stream_get_contents( $tmp_fh ); } /** * @param Translation_Entry $entry * @return bool */ public function is_entry_good_for_export( $entry ) { if ( empty( $entry->translations ) ) { return false; } if ( ! array_filter( $entry->translations ) ) { return false; } return true; } /** * @param resource $fh * @return true */ public function export_to_file_handle( $fh ) { $entries = array_filter( $this->entries, array( $this, 'is_entry_good_for_export' ) ); ksort( $entries ); $magic = 0x950412de; $revision = 0; $total = count( $entries ) + 1; // All the headers are one entry. $originals_lengths_addr = 28; $translations_lengths_addr = $originals_lengths_addr + 8 * $total; $size_of_hash = 0; $hash_addr = $translations_lengths_addr + 8 * $total; $current_addr = $hash_addr; fwrite( $fh, pack( 'V*', $magic, $revision, $total, $originals_lengths_addr, $translations_lengths_addr, $size_of_hash, $hash_addr ) ); fseek( $fh, $originals_lengths_addr ); // Headers' msgid is an empty string. fwrite( $fh, pack( 'VV', 0, $current_addr ) ); $current_addr++; $originals_table = "\0"; $reader = new POMO_Reader(); foreach ( $entries as $entry ) { $originals_table .= $this->export_original( $entry ) . "\0"; $length = $reader->strlen( $this->export_original( $entry ) ); fwrite( $fh, pack( 'VV', $length, $current_addr ) ); $current_addr += $length + 1; // Account for the NULL byte after. } $exported_headers = $this->export_headers(); fwrite( $fh, pack( 'VV', $reader->strlen( $exported_headers ), $current_addr ) ); $current_addr += strlen( $exported_headers ) + 1; $translations_table = $exported_headers . "\0"; foreach ( $entries as $entry ) { $translations_table .= $this->export_translations( $entry ) . "\0"; $length = $reader->strlen( $this->export_translations( $entry ) ); fwrite( $fh, pack( 'VV', $length, $current_addr ) ); $current_addr += $length + 1; } fwrite( $fh, $originals_table ); fwrite( $fh, $translations_table ); return true; } /** * @param Translation_Entry $entry * @return string */ public function export_original( $entry ) { // TODO: Warnings for control characters. $exported = $entry->singular; if ( $entry->is_plural ) { $exported .= "\0" . $entry->plural; } if ( $entry->context ) { $exported = $entry->context . "\4" . $exported; } return $exported; } /** * @param Translation_Entry $entry * @return string */ public function export_translations( $entry ) { // TODO: Warnings for control characters. return $entry->is_plural ? implode( "\0", $entry->translations ) : $entry->translations[0]; } /** * @return string */ public function export_headers() { $exported = ''; foreach ( $this->headers as $header => $value ) { $exported .= "$header: $value\n"; } return $exported; } /** * @param int $magic * @return string|false */ public function get_byteorder( $magic ) { // The magic is 0x950412de. // bug in PHP 5.0.2, see https://savannah.nongnu.org/bugs/?func=detailitem&item_id=10565 $magic_little = (int) - 1794895138; $magic_little_64 = (int) 2500072158; // 0xde120495 $magic_big = ( (int) - 569244523 ) & 0xFFFFFFFF; if ( $magic_little == $magic || $magic_little_64 == $magic ) { return 'little'; } elseif ( $magic_big == $magic ) { return 'big'; } else { return false; } } /** * @param POMO_FileReader $reader * @return bool True if the import was successful, otherwise false. */ public function import_from_reader( $reader ) { $endian_string = MO::get_byteorder( $reader->readint32() ); if ( false === $endian_string ) { return false; } $reader->setEndian( $endian_string ); $endian = ( 'big' === $endian_string ) ? 'N' : 'V'; $header = $reader->read( 24 ); if ( $reader->strlen( $header ) != 24 ) { return false; } // Parse header. $header = unpack( "{$endian}revision/{$endian}total/{$endian}originals_lengths_addr/{$endian}translations_lengths_addr/{$endian}hash_length/{$endian}hash_addr", $header ); if ( ! is_array( $header ) ) { return false; } // Support revision 0 of MO format specs, only. if ( 0 != $header['revision'] ) { return false; } // Seek to data blocks. $reader->seekto( $header['originals_lengths_addr'] ); // Read originals' indices. $originals_lengths_length = $header['translations_lengths_addr'] - $header['originals_lengths_addr']; if ( $originals_lengths_length != $header['total'] * 8 ) { return false; } $originals = $reader->read( $originals_lengths_length ); if ( $reader->strlen( $originals ) != $originals_lengths_length ) { return false; } // Read translations' indices. $translations_lengths_length = $header['hash_addr'] - $header['translations_lengths_addr']; if ( $translations_lengths_length != $header['total'] * 8 ) { return false; } $translations = $reader->read( $translations_lengths_length ); if ( $reader->strlen( $translations ) != $translations_lengths_length ) { return false; } // Transform raw data into set of indices. $originals = $reader->str_split( $originals, 8 ); $translations = $reader->str_split( $translations, 8 ); // Skip hash table. $strings_addr = $header['hash_addr'] + $header['hash_length'] * 4; $reader->seekto( $strings_addr ); $strings = $reader->read_all(); $reader->close(); for ( $i = 0; $i < $header['total']; $i++ ) { $o = unpack( "{$endian}length/{$endian}pos", $originals[ $i ] ); $t = unpack( "{$endian}length/{$endian}pos", $translations[ $i ] ); if ( ! $o || ! $t ) { return false; } // Adjust offset due to reading strings to separate space before. $o['pos'] -= $strings_addr; $t['pos'] -= $strings_addr; $original = $reader->substr( $strings, $o['pos'], $o['length'] ); $translation = $reader->substr( $strings, $t['pos'], $t['length'] ); if ( '' === $original ) { $this->set_headers( $this->make_headers( $translation ) ); } else { $entry = &$this->make_entry( $original, $translation ); $this->entries[ $entry->key() ] = &$entry; } } return true; } /** * Build a Translation_Entry from original string and translation strings, * found in a MO file * * @static * @param string $original original string to translate from MO file. Might contain * 0x04 as context separator or 0x00 as singular/plural separator * @param string $translation translation string from MO file. Might contain * 0x00 as a plural translations separator * @return Translation_Entry Entry instance. */ public function &make_entry( $original, $translation ) { $entry = new Translation_Entry(); // Look for context, separated by \4. $parts = explode( "\4", $original ); if ( isset( $parts[1] ) ) { $original = $parts[1]; $entry->context = $parts[0]; } // Look for plural original. $parts = explode( "\0", $original ); $entry->singular = $parts[0]; if ( isset( $parts[1] ) ) { $entry->is_plural = true; $entry->plural = $parts[1]; } // Plural translations are also separated by \0. $entry->translations = explode( "\0", $translation ); return $entry; } /** * @param int $count * @return string */ public function select_plural_form( $count ) { return $this->gettext_select_plural_form( $count ); } /** * @return int */ public function get_plural_forms_count() { return $this->_nplurals; } } ``` | Uses | Description | | --- | --- | | [Gettext\_Translations](gettext_translations) wp-includes/pomo/translations.php | | wordpress class Requests_Exception {} class Requests\_Exception {} ============================ Exception for HTTP requests * [\_\_construct](requests_exception/__construct) β€” Create a new exception * [getData](requests_exception/getdata) β€” Gives any relevant data * [getType](requests_exception/gettype) β€” Like {@see getCode()}, but a string code. File: `wp-includes/Requests/Exception.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception.php/) ``` class Requests_Exception extends Exception { /** * Type of exception * * @var string */ protected $type; /** * Data associated with the exception * * @var mixed */ protected $data; /** * Create a new exception * * @param string $message Exception message * @param string $type Exception type * @param mixed $data Associated data * @param integer $code Exception numerical code, if applicable */ public function __construct($message, $type, $data = null, $code = 0) { parent::__construct($message, $code); $this->type = $type; $this->data = $data; } /** * Like {@see getCode()}, but a string code. * * @codeCoverageIgnore * @return string */ public function getType() { return $this->type; } /** * Gives any relevant data * * @codeCoverageIgnore * @return mixed */ public function getData() { return $this->data; } } ``` | Used By | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | | [Requests\_Exception\_Transport](requests_exception_transport) wp-includes/Requests/Exception/Transport.php | | wordpress class Requests_Utility_FilteredIterator {} class Requests\_Utility\_FilteredIterator {} ============================================ Iterator for arrays requiring filtered values * [\_\_construct](requests_utility_filterediterator/__construct) β€” Create a new iterator * [\_\_unserialize](requests_utility_filterediterator/__unserialize) * [\_\_wakeup](requests_utility_filterediterator/__wakeup) * [current](requests_utility_filterediterator/current) β€” Get the current item's value after filtering * [unserialize](requests_utility_filterediterator/unserialize) File: `wp-includes/Requests/Utility/FilteredIterator.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/utility/filterediterator.php/) ``` class Requests_Utility_FilteredIterator extends ArrayIterator { /** * Callback to run as a filter * * @var callable */ protected $callback; /** * Create a new iterator * * @param array $data * @param callable $callback Callback to be called on each value */ public function __construct($data, $callback) { parent::__construct($data); $this->callback = $callback; } /** * Get the current item's value after filtering * * @return string */ public function current() { $value = parent::current(); if (is_callable($this->callback)) { $value = call_user_func($this->callback, $value); } return $value; } /** * @inheritdoc */ public function unserialize($serialized) {} /** * @inheritdoc * * @phpcs:disable PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.MethodDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.NewMagicMethods.__unserializeFound */ public function __unserialize($serialized) {} public function __wakeup() { unset($this->callback); } } ``` wordpress class WP_REST_Templates_Controller {} class WP\_REST\_Templates\_Controller {} ======================================== Base Templates REST API Controller. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_templates_controller/__construct) β€” Constructor. * [\_sanitize\_template\_id](wp_rest_templates_controller/_sanitize_template_id) β€” Requesting this endpoint for a template like 'twentytwentytwo//home' requires using a path like /wp/v2/templates/twentytwentytwo//home. There are special cases when WordPress routing corrects the name to contain only a single slash like 'twentytwentytwo/home'. * [create\_item](wp_rest_templates_controller/create_item) β€” Creates a single template. * [create\_item\_permissions\_check](wp_rest_templates_controller/create_item_permissions_check) β€” Checks if a given request has access to create a template. * [delete\_item](wp_rest_templates_controller/delete_item) β€” Deletes a single template. * [delete\_item\_permissions\_check](wp_rest_templates_controller/delete_item_permissions_check) β€” Checks if a given request has access to delete a single template. * [get\_available\_actions](wp_rest_templates_controller/get_available_actions) β€” Get the link relations available for the post and current user. * [get\_collection\_params](wp_rest_templates_controller/get_collection_params) β€” Retrieves the query params for the posts collection. * [get\_item](wp_rest_templates_controller/get_item) β€” Returns the given template * [get\_item\_permissions\_check](wp_rest_templates_controller/get_item_permissions_check) β€” Checks if a given request has access to read a single template. * [get\_item\_schema](wp_rest_templates_controller/get_item_schema) β€” Retrieves the block type' schema, conforming to JSON Schema. * [get\_items](wp_rest_templates_controller/get_items) β€” Returns a list of templates. * [get\_items\_permissions\_check](wp_rest_templates_controller/get_items_permissions_check) β€” Checks if a given request has access to read templates. * [get\_template\_fallback](wp_rest_templates_controller/get_template_fallback) β€” Returns the fallback template for the given slug. * [permissions\_check](wp_rest_templates_controller/permissions_check) β€” Checks if the user has permissions to make the request. * [prepare\_item\_for\_database](wp_rest_templates_controller/prepare_item_for_database) β€” Prepares a single template for create or update. * [prepare\_item\_for\_response](wp_rest_templates_controller/prepare_item_for_response) β€” Prepare a single template output for response * [prepare\_links](wp_rest_templates_controller/prepare_links) β€” Prepares links for the request. * [register\_routes](wp_rest_templates_controller/register_routes) β€” Registers the controllers routes. * [update\_item](wp_rest_templates_controller/update_item) β€” Updates a single template. * [update\_item\_permissions\_check](wp_rest_templates_controller/update_item_permissions_check) β€” Checks if a given request has access to write a single template. File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/) ``` class WP_REST_Templates_Controller extends WP_REST_Controller { /** * Post type. * * @since 5.8.0 * @var string */ protected $post_type; /** * Constructor. * * @since 5.8.0 * * @param string $post_type Post type. */ public function __construct( $post_type ) { $this->post_type = $post_type; $obj = get_post_type_object( $post_type ); $this->rest_base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name; $this->namespace = ! empty( $obj->rest_namespace ) ? $obj->rest_namespace : 'wp/v2'; } /** * Registers the controllers routes. * * @since 5.8.0 * @since 6.1.0 Endpoint for fallback template content. */ public function register_routes() { // Lists all templates. 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 ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); // Get fallback template content. register_rest_route( $this->namespace, '/' . $this->rest_base . '/lookup', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_template_fallback' ), 'permission_callback' => array( $this, 'get_item_permissions_check' ), 'args' => array( 'slug' => array( 'description' => __( 'The slug of the template to get the fallback for' ), 'type' => 'string', 'required' => true, ), 'is_custom' => array( 'description' => __( 'Indicates if a template is custom or part of the template hierarchy' ), 'type' => 'boolean', ), 'template_prefix' => array( 'description' => __( 'The template prefix for the created template. This is used to extract the main template type, e.g. in `taxonomy-books` extracts the `taxonomy`' ), 'type' => 'string', ), ), ), ) ); // Lists/updates a single template based on the given id. register_rest_route( $this->namespace, // The route. sprintf( '/%s/(?P<id>%s%s)', $this->rest_base, // Matches theme's directory: `/themes/<subdirectory>/<theme>/` or `/themes/<theme>/`. // Excludes invalid directory name characters: `/:<>*?"|`. '([^\/:<>\*\?"\|]+(?:\/[^\/:<>\*\?"\|]+)?)', // Matches the template name. '[\/\w-]+' ), array( 'args' => array( 'id' => array( 'description' => __( 'The id of a template' ), 'type' => 'string', 'sanitize_callback' => array( $this, '_sanitize_template_id' ), ), ), 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' => __( 'Whether to bypass Trash and force deletion.' ), ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Returns the fallback template for the given slug. * * @since 6.1.0 * * @param WP_REST_Request $request The request instance. * @return WP_REST_Response|WP_Error */ public function get_template_fallback( $request ) { $hierarchy = get_template_hierarchy( $request['slug'], $request['is_custom'], $request['template_prefix'] ); $fallback_template = resolve_block_template( $request['slug'], $hierarchy, '' ); $response = $this->prepare_item_for_response( $fallback_template, $request ); return rest_ensure_response( $response ); } /** * Checks if the user has permissions to make the request. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ protected function 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_templates', __( 'Sorry, you are not allowed to access the templates on this site.' ), array( 'status' => rest_authorization_required_code(), ) ); } return true; } /** * Requesting this endpoint for a template like 'twentytwentytwo//home' * requires using a path like /wp/v2/templates/twentytwentytwo//home. There * are special cases when WordPress routing corrects the name to contain * only a single slash like 'twentytwentytwo/home'. * * This method doubles the last slash if it's not already doubled. It relies * on the template ID format {theme_name}//{template_slug} and the fact that * slugs cannot contain slashes. * * @since 5.9.0 * @see https://core.trac.wordpress.org/ticket/54507 * * @param string $id Template ID. * @return string Sanitized template ID. */ public function _sanitize_template_id( $id ) { $id = urldecode( $id ); $last_slash_pos = strrpos( $id, '/' ); if ( false === $last_slash_pos ) { return $id; } $is_double_slashed = substr( $id, $last_slash_pos - 1, 1 ) === '/'; if ( $is_double_slashed ) { return $id; } return ( substr( $id, 0, $last_slash_pos ) . '/' . substr( $id, $last_slash_pos ) ); } /** * Checks if a given request has access to read templates. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { return $this->permissions_check( $request ); } /** * Returns a list of templates. * * @since 5.8.0 * * @param WP_REST_Request $request The request instance. * @return WP_REST_Response */ public function get_items( $request ) { $query = array(); if ( isset( $request['wp_id'] ) ) { $query['wp_id'] = $request['wp_id']; } if ( isset( $request['area'] ) ) { $query['area'] = $request['area']; } if ( isset( $request['post_type'] ) ) { $query['post_type'] = $request['post_type']; } $templates = array(); foreach ( get_block_templates( $query, $this->post_type ) as $template ) { $data = $this->prepare_item_for_response( $template, $request ); $templates[] = $this->prepare_response_for_collection( $data ); } return rest_ensure_response( $templates ); } /** * Checks if a given request has access to read a single template. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise. */ public function get_item_permissions_check( $request ) { return $this->permissions_check( $request ); } /** * Returns the given template * * @since 5.8.0 * * @param WP_REST_Request $request The request instance. * @return WP_REST_Response|WP_Error */ public function get_item( $request ) { if ( isset( $request['source'] ) && 'theme' === $request['source'] ) { $template = get_block_file_template( $request['id'], $this->post_type ); } else { $template = get_block_template( $request['id'], $this->post_type ); } if ( ! $template ) { return new WP_Error( 'rest_template_not_found', __( 'No templates exist with that id.' ), array( 'status' => 404 ) ); } return $this->prepare_item_for_response( $template, $request ); } /** * Checks if a given request has access to write a single template. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has write access for the item, WP_Error object otherwise. */ public function update_item_permissions_check( $request ) { return $this->permissions_check( $request ); } /** * Updates a single template. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function update_item( $request ) { $template = get_block_template( $request['id'], $this->post_type ); if ( ! $template ) { return new WP_Error( 'rest_template_not_found', __( 'No templates exist with that id.' ), array( 'status' => 404 ) ); } $post_before = get_post( $template->wp_id ); if ( isset( $request['source'] ) && 'theme' === $request['source'] ) { wp_delete_post( $template->wp_id, true ); $request->set_param( 'context', 'edit' ); $template = get_block_template( $request['id'], $this->post_type ); $response = $this->prepare_item_for_response( $template, $request ); return rest_ensure_response( $response ); } $changes = $this->prepare_item_for_database( $request ); if ( is_wp_error( $changes ) ) { return $changes; } if ( 'custom' === $template->source ) { $update = true; $result = wp_update_post( wp_slash( (array) $changes ), false ); } else { $update = false; $post_before = null; $result = wp_insert_post( wp_slash( (array) $changes ), false ); } if ( is_wp_error( $result ) ) { if ( 'db_update_error' === $result->get_error_code() ) { $result->add_data( array( 'status' => 500 ) ); } else { $result->add_data( array( 'status' => 400 ) ); } return $result; } $template = get_block_template( $request['id'], $this->post_type ); $fields_update = $this->update_additional_fields_for_object( $template, $request ); if ( is_wp_error( $fields_update ) ) { return $fields_update; } $request->set_param( 'context', 'edit' ); $post = get_post( $template->wp_id ); /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */ do_action( "rest_after_insert_{$this->post_type}", $post, $request, false ); wp_after_insert_post( $post, $update, $post_before ); $response = $this->prepare_item_for_response( $template, $request ); return rest_ensure_response( $response ); } /** * Checks if a given request has access to create a template. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise. */ public function create_item_permissions_check( $request ) { return $this->permissions_check( $request ); } /** * Creates a single template. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function create_item( $request ) { $prepared_post = $this->prepare_item_for_database( $request ); if ( is_wp_error( $prepared_post ) ) { return $prepared_post; } $prepared_post->post_name = $request['slug']; $post_id = wp_insert_post( wp_slash( (array) $prepared_post ), true ); if ( is_wp_error( $post_id ) ) { if ( 'db_insert_error' === $post_id->get_error_code() ) { $post_id->add_data( array( 'status' => 500 ) ); } else { $post_id->add_data( array( 'status' => 400 ) ); } return $post_id; } $posts = get_block_templates( array( 'wp_id' => $post_id ), $this->post_type ); if ( ! count( $posts ) ) { return new WP_Error( 'rest_template_insert_error', __( 'No templates exist with that id.' ), array( 'status' => 400 ) ); } $id = $posts[0]->id; $post = get_post( $post_id ); $template = get_block_template( $id, $this->post_type ); $fields_update = $this->update_additional_fields_for_object( $template, $request ); if ( is_wp_error( $fields_update ) ) { return $fields_update; } /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */ do_action( "rest_after_insert_{$this->post_type}", $post, $request, true ); wp_after_insert_post( $post, false, null ); $response = $this->prepare_item_for_response( $template, $request ); $response = rest_ensure_response( $response ); $response->set_status( 201 ); $response->header( 'Location', rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $template->id ) ) ); return $response; } /** * Checks if a given request has access to delete a single template. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has delete access for the item, WP_Error object otherwise. */ public function delete_item_permissions_check( $request ) { return $this->permissions_check( $request ); } /** * Deletes a single template. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function delete_item( $request ) { $template = get_block_template( $request['id'], $this->post_type ); if ( ! $template ) { return new WP_Error( 'rest_template_not_found', __( 'No templates exist with that id.' ), array( 'status' => 404 ) ); } if ( 'custom' !== $template->source ) { return new WP_Error( 'rest_invalid_template', __( 'Templates based on theme files can\'t be removed.' ), array( 'status' => 400 ) ); } $id = $template->wp_id; $force = (bool) $request['force']; $request->set_param( 'context', 'edit' ); // If we're forcing, then delete permanently. if ( $force ) { $previous = $this->prepare_item_for_response( $template, $request ); $result = wp_delete_post( $id, true ); $response = new WP_REST_Response(); $response->set_data( array( 'deleted' => true, 'previous' => $previous->get_data(), ) ); } else { // Otherwise, only trash if we haven't already. if ( 'trash' === $template->status ) { return new WP_Error( 'rest_template_already_trashed', __( 'The template has already been deleted.' ), array( 'status' => 410 ) ); } // (Note that internally this falls through to `wp_delete_post()` // if the Trash is disabled.) $result = wp_trash_post( $id ); $template->status = 'trash'; $response = $this->prepare_item_for_response( $template, $request ); } if ( ! $result ) { return new WP_Error( 'rest_cannot_delete', __( 'The template cannot be deleted.' ), array( 'status' => 500 ) ); } return $response; } /** * Prepares a single template for create or update. * * @since 5.8.0 * * @param WP_REST_Request $request Request object. * @return stdClass Changes to pass to wp_update_post. */ protected function prepare_item_for_database( $request ) { $template = $request['id'] ? get_block_template( $request['id'], $this->post_type ) : null; $changes = new stdClass(); if ( null === $template ) { $changes->post_type = $this->post_type; $changes->post_status = 'publish'; $changes->tax_input = array( 'wp_theme' => isset( $request['theme'] ) ? $request['theme'] : wp_get_theme()->get_stylesheet(), ); } elseif ( 'custom' !== $template->source ) { $changes->post_name = $template->slug; $changes->post_type = $this->post_type; $changes->post_status = 'publish'; $changes->tax_input = array( 'wp_theme' => $template->theme, ); $changes->meta_input = array( 'origin' => $template->source, ); } else { $changes->post_name = $template->slug; $changes->ID = $template->wp_id; $changes->post_status = 'publish'; } if ( isset( $request['content'] ) ) { if ( is_string( $request['content'] ) ) { $changes->post_content = $request['content']; } elseif ( isset( $request['content']['raw'] ) ) { $changes->post_content = $request['content']['raw']; } } elseif ( null !== $template && 'custom' !== $template->source ) { $changes->post_content = $template->content; } 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']; } } elseif ( null !== $template && 'custom' !== $template->source ) { $changes->post_title = $template->title; } if ( isset( $request['description'] ) ) { $changes->post_excerpt = $request['description']; } elseif ( null !== $template && 'custom' !== $template->source ) { $changes->post_excerpt = $template->description; } if ( 'wp_template' === $this->post_type && isset( $request['is_wp_suggestion'] ) ) { $changes->meta_input = wp_parse_args( array( 'is_wp_suggestion' => $request['is_wp_suggestion'], ), $changes->meta_input = array() ); } if ( 'wp_template_part' === $this->post_type ) { if ( isset( $request['area'] ) ) { $changes->tax_input['wp_template_part_area'] = _filter_block_template_part_area( $request['area'] ); } elseif ( null !== $template && 'custom' !== $template->source && $template->area ) { $changes->tax_input['wp_template_part_area'] = _filter_block_template_part_area( $template->area ); } elseif ( ! $template->area ) { $changes->tax_input['wp_template_part_area'] = WP_TEMPLATE_PART_AREA_UNCATEGORIZED; } } if ( ! empty( $request['author'] ) ) { $post_author = (int) $request['author']; if ( get_current_user_id() !== $post_author ) { $user_obj = get_userdata( $post_author ); if ( ! $user_obj ) { return new WP_Error( 'rest_invalid_author', __( 'Invalid author ID.' ), array( 'status' => 400 ) ); } } $changes->post_author = $post_author; } return $changes; } /** * Prepare a single template output for response * * @since 5.8.0 * @since 5.9.0 Renamed `$template` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Block_Template $item Template instance. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function prepare_item_for_response( $item, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable // Restores the more descriptive, specific name for use within this method. $template = $item; $fields = $this->get_fields_for_response( $request ); // Base fields for every template. $data = array(); if ( rest_is_field_included( 'id', $fields ) ) { $data['id'] = $template->id; } if ( rest_is_field_included( 'theme', $fields ) ) { $data['theme'] = $template->theme; } if ( rest_is_field_included( 'content', $fields ) ) { $data['content'] = array(); } if ( rest_is_field_included( 'content.raw', $fields ) ) { $data['content']['raw'] = $template->content; } if ( rest_is_field_included( 'content.block_version', $fields ) ) { $data['content']['block_version'] = block_version( $template->content ); } if ( rest_is_field_included( 'slug', $fields ) ) { $data['slug'] = $template->slug; } if ( rest_is_field_included( 'source', $fields ) ) { $data['source'] = $template->source; } if ( rest_is_field_included( 'origin', $fields ) ) { $data['origin'] = $template->origin; } if ( rest_is_field_included( 'type', $fields ) ) { $data['type'] = $template->type; } if ( rest_is_field_included( 'description', $fields ) ) { $data['description'] = $template->description; } if ( rest_is_field_included( 'title', $fields ) ) { $data['title'] = array(); } if ( rest_is_field_included( 'title.raw', $fields ) ) { $data['title']['raw'] = $template->title; } if ( rest_is_field_included( 'title.rendered', $fields ) ) { if ( $template->wp_id ) { /** This filter is documented in wp-includes/post-template.php */ $data['title']['rendered'] = apply_filters( 'the_title', $template->title, $template->wp_id ); } else { $data['title']['rendered'] = $template->title; } } if ( rest_is_field_included( 'status', $fields ) ) { $data['status'] = $template->status; } if ( rest_is_field_included( 'wp_id', $fields ) ) { $data['wp_id'] = (int) $template->wp_id; } if ( rest_is_field_included( 'has_theme_file', $fields ) ) { $data['has_theme_file'] = (bool) $template->has_theme_file; } if ( rest_is_field_included( 'is_custom', $fields ) && 'wp_template' === $template->type ) { $data['is_custom'] = $template->is_custom; } if ( rest_is_field_included( 'author', $fields ) ) { $data['author'] = (int) $template->author; } if ( rest_is_field_included( 'area', $fields ) && 'wp_template_part' === $template->type ) { $data['area'] = $template->area; } $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( $template->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; } /** * Prepares links for the request. * * @since 5.8.0 * * @param integer $id ID. * @return array Links for the given post. */ protected function prepare_links( $id ) { $links = array( 'self' => array( 'href' => rest_url( rest_get_route_for_post( $id ) ), ), 'collection' => array( 'href' => rest_url( rest_get_route_for_post_type_items( $this->post_type ) ), ), 'about' => array( 'href' => rest_url( 'wp/v2/types/' . $this->post_type ), ), ); return $links; } /** * Get the link relations available for the post and current user. * * @since 5.8.0 * * @return string[] List of link relations. */ 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'; } if ( current_user_can( 'unfiltered_html' ) ) { $rels[] = 'https://api.w.org/action-unfiltered-html'; } return $rels; } /** * Retrieves the query params for the posts collection. * * @since 5.8.0 * @since 5.9.0 Added `'area'` and `'post_type'`. * * @return array Collection parameters. */ public function get_collection_params() { return array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), 'wp_id' => array( 'description' => __( 'Limit to the specified post id.' ), 'type' => 'integer', ), 'area' => array( 'description' => __( 'Limit to the specified template part area.' ), 'type' => 'string', ), 'post_type' => array( 'description' => __( 'Post type to get the templates for.' ), 'type' => 'string', ), ); } /** * Retrieves the block type' schema, conforming to JSON Schema. * * @since 5.8.0 * @since 5.9.0 Added `'area'`. * * @return array Item schema data. */ 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 template.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'slug' => array( 'description' => __( 'Unique slug identifying the template.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'required' => true, 'minLength' => 1, 'pattern' => '[a-zA-Z0-9_\-]+', ), 'theme' => array( 'description' => __( 'Theme identifier for the template.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), ), 'type' => array( 'description' => __( 'Type of template.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), ), 'source' => array( 'description' => __( 'Source of template' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'origin' => array( 'description' => __( 'Source of a customized template' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'content' => array( 'description' => __( 'Content of template.' ), 'type' => array( 'object', 'string' ), 'default' => '', 'context' => array( 'embed', 'view', 'edit' ), 'properties' => array( 'raw' => array( 'description' => __( 'Content for the template, as it exists in the database.' ), 'type' => 'string', 'context' => array( 'view', 'edit' ), ), 'block_version' => array( 'description' => __( 'Version of the content block format used by the template.' ), 'type' => 'integer', 'context' => array( 'edit' ), 'readonly' => true, ), ), ), 'title' => array( 'description' => __( 'Title of template.' ), 'type' => array( 'object', 'string' ), 'default' => '', 'context' => array( 'embed', 'view', 'edit' ), 'properties' => array( 'raw' => array( 'description' => __( 'Title for the template, as it exists in the database.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), ), 'rendered' => array( 'description' => __( 'HTML title for the template, transformed for display.' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), ), ), 'description' => array( 'description' => __( 'Description of template.' ), 'type' => 'string', 'default' => '', 'context' => array( 'embed', 'view', 'edit' ), ), 'status' => array( 'description' => __( 'Status of template.' ), 'type' => 'string', 'enum' => array_keys( get_post_stati( array( 'internal' => false ) ) ), 'default' => 'publish', 'context' => array( 'embed', 'view', 'edit' ), ), 'wp_id' => array( 'description' => __( 'Post ID.' ), 'type' => 'integer', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'has_theme_file' => array( 'description' => __( 'Theme file exists.' ), 'type' => 'bool', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'author' => array( 'description' => __( 'The ID for the author of the template.' ), 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), ), ), ); if ( 'wp_template' === $this->post_type ) { $schema['properties']['is_custom'] = array( 'description' => __( 'Whether a template is a custom template.' ), 'type' => 'bool', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ); } if ( 'wp_template_part' === $this->post_type ) { $schema['properties']['area'] = array( 'description' => __( 'Where the template part is intended for use (header, footer, etc.)' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), ); } $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
programming_docs
wordpress class WP {} class WP {} =========== WordPress environment setup class. * [add\_query\_var](wp/add_query_var) β€” Adds a query variable to the list of public query variables. * [build\_query\_string](wp/build_query_string) β€” Sets the query string property based off of the query variable property. * [handle\_404](wp/handle_404) β€” Set the Headers for 404, if nothing is found for requested URL. * [init](wp/init) β€” Set up the current user. * [main](wp/main) β€” Sets up all of the variables required by the WordPress environment. * [parse\_request](wp/parse_request) β€” Parses the request to find the correct WordPress query. * [query\_posts](wp/query_posts) β€” Set up the Loop based on the query variables. * [register\_globals](wp/register_globals) β€” Set up the WordPress Globals. * [remove\_query\_var](wp/remove_query_var) β€” Removes a query variable from a list of public query variables. * [send\_headers](wp/send_headers) β€” Sends additional HTTP headers for caching, content type, etc. * [set\_query\_var](wp/set_query_var) β€” Sets the value of a query variable. File: `wp-includes/class-wp.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp.php/) ``` class WP { /** * Public query variables. * * Long list of public query variables. * * @since 2.0.0 * @var string[] */ public $public_query_vars = array( 'm', 'p', 'posts', 'w', 'cat', 'withcomments', 'withoutcomments', 's', 'search', 'exact', 'sentence', 'calendar', 'page', 'paged', 'more', 'tb', 'pb', 'author', 'order', 'orderby', 'year', 'monthnum', 'day', 'hour', 'minute', 'second', 'name', 'category_name', 'tag', 'feed', 'author_name', 'pagename', 'page_id', 'error', 'attachment', 'attachment_id', 'subpost', 'subpost_id', 'preview', 'robots', 'favicon', 'taxonomy', 'term', 'cpage', 'post_type', 'embed' ); /** * Private query variables. * * Long list of private query variables. * * @since 2.0.0 * @var string[] */ public $private_query_vars = array( 'offset', 'posts_per_page', 'posts_per_archive_page', 'showposts', 'nopaging', 'post_type', 'post_status', 'category__in', 'category__not_in', 'category__and', 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and', 'tag_id', 'post_mime_type', 'perm', 'comments_per_page', 'post__in', 'post__not_in', 'post_parent', 'post_parent__in', 'post_parent__not_in', 'title', 'fields' ); /** * Extra query variables set by the user. * * @since 2.1.0 * @var array */ public $extra_query_vars = array(); /** * Query variables for setting up the WordPress Query Loop. * * @since 2.0.0 * @var array */ public $query_vars = array(); /** * String parsed to set the query variables. * * @since 2.0.0 * @var string */ public $query_string = ''; /** * The request path, e.g. 2015/05/06. * * @since 2.0.0 * @var string */ public $request = ''; /** * Rewrite rule the request matched. * * @since 2.0.0 * @var string */ public $matched_rule = ''; /** * Rewrite query the request matched. * * @since 2.0.0 * @var string */ public $matched_query = ''; /** * Whether already did the permalink. * * @since 2.0.0 * @var bool */ public $did_permalink = false; /** * Adds a query variable to the list of public query variables. * * @since 2.1.0 * * @param string $qv Query variable name. */ public function add_query_var( $qv ) { if ( ! in_array( $qv, $this->public_query_vars, true ) ) { $this->public_query_vars[] = $qv; } } /** * Removes a query variable from a list of public query variables. * * @since 4.5.0 * * @param string $name Query variable name. */ public function remove_query_var( $name ) { $this->public_query_vars = array_diff( $this->public_query_vars, array( $name ) ); } /** * Sets the value of a query variable. * * @since 2.3.0 * * @param string $key Query variable name. * @param mixed $value Query variable value. */ public function set_query_var( $key, $value ) { $this->query_vars[ $key ] = $value; } /** * 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. * * @since 2.0.0 * @since 6.0.0 A return value was added. * * @global WP_Rewrite $wp_rewrite WordPress rewrite component. * * @param array|string $extra_query_vars Set the extra query variables. * @return bool Whether the request was parsed. */ 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; } /** * 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. * * @since 2.0.0 * @since 4.4.0 `X-Pingback` header is added conditionally for single posts that allow pings. * @since 6.1.0 Runs after posts have been queried. * * @global WP_Query $wp_query WordPress Query object. */ 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 ) ); } /** * Sets the query string property based off of the query variable property. * * The {@see 'query_string'} filter is deprecated, but still works. Plugins should * use the {@see 'request'} filter instead. * * @since 2.0.0 */ 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 ); } } /** * 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. * * @since 2.0.0 * * @global WP_Query $wp_query WordPress Query object. * @global string $query_string Query string for the loop. * @global array $posts The found posts. * @global WP_Post|null $post The current post, if available. * @global string $request The SQL statement for the request. * @global int $more Only set, if single page or post. * @global int $single If single page or post. Only set, if single page or post. * @global WP_User $authordata Only set, if author archive. */ 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() ); } } /** * Set up the current user. * * @since 2.0.0 */ public function init() { wp_get_current_user(); } /** * Set up the Loop based on the query variables. * * @since 2.0.0 * * @global WP_Query $wp_the_query WordPress Query object. */ public function query_posts() { global $wp_the_query; $this->build_query_string(); $wp_the_query->query( $this->query_vars ); } /** * 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. * * @since 2.0.0 * * @global WP_Query $wp_query WordPress Query object. */ 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 ); } } /** * Sets up all of the variables required by the WordPress environment. * * The action {@see 'wp'} has one parameter that references the WP object. It * allows for accessing the properties and methods to further manipulate the * object. * * @since 2.0.0 * * @param string|array $query_args Passed to parse_request(). */ 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 ) ); } } ``` | Version | Description | | --- | --- | | [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
programming_docs
wordpress class WP_Filesystem_SSH2 {} class WP\_Filesystem\_SSH2 {} ============================= WordPress Filesystem Class for implementing SSH2 To use this class you must follow these steps for PHP 5.2.6+ * [\_\_construct](wp_filesystem_ssh2/__construct) β€” Constructor. * [atime](wp_filesystem_ssh2/atime) β€” Gets the file's last access time. * [chdir](wp_filesystem_ssh2/chdir) β€” Changes current directory. * [chgrp](wp_filesystem_ssh2/chgrp) β€” Changes the file group. * [chmod](wp_filesystem_ssh2/chmod) β€” Changes filesystem permissions. * [chown](wp_filesystem_ssh2/chown) β€” Changes the owner of a file or directory. * [connect](wp_filesystem_ssh2/connect) β€” Connects filesystem. * [copy](wp_filesystem_ssh2/copy) β€” Copies a file. * [cwd](wp_filesystem_ssh2/cwd) β€” Gets the current working directory. * [delete](wp_filesystem_ssh2/delete) β€” Deletes a file or directory. * [dirlist](wp_filesystem_ssh2/dirlist) β€” Gets details for files in a directory or a specific file. * [exists](wp_filesystem_ssh2/exists) β€” Checks if a file or directory exists. * [get\_contents](wp_filesystem_ssh2/get_contents) β€” Reads entire file into a string. * [get\_contents\_array](wp_filesystem_ssh2/get_contents_array) β€” Reads entire file into an array. * [getchmod](wp_filesystem_ssh2/getchmod) β€” Gets the permissions of the specified file or filepath in their octal format. * [group](wp_filesystem_ssh2/group) β€” Gets the file's group. * [is\_dir](wp_filesystem_ssh2/is_dir) β€” Checks if resource is a directory. * [is\_file](wp_filesystem_ssh2/is_file) β€” Checks if resource is a file. * [is\_readable](wp_filesystem_ssh2/is_readable) β€” Checks if a file is readable. * [is\_writable](wp_filesystem_ssh2/is_writable) β€” Checks if a file or directory is writable. * [mkdir](wp_filesystem_ssh2/mkdir) β€” Creates a directory. * [move](wp_filesystem_ssh2/move) β€” Moves a file. * [mtime](wp_filesystem_ssh2/mtime) β€” Gets the file modification time. * [owner](wp_filesystem_ssh2/owner) β€” Gets the file owner. * [put\_contents](wp_filesystem_ssh2/put_contents) β€” Writes a string to a file. * [rmdir](wp_filesystem_ssh2/rmdir) β€” Deletes a directory. * [run\_command](wp_filesystem_ssh2/run_command) * [sftp\_path](wp_filesystem_ssh2/sftp_path) β€” Gets the ssh2.sftp PHP stream wrapper path to open for the given file. * [size](wp_filesystem_ssh2/size) β€” Gets the file size (in bytes). * [touch](wp_filesystem_ssh2/touch) β€” Sets the access and modification times of a file. File: `wp-admin/includes/class-wp-filesystem-ssh2.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-ssh2.php/) ``` class WP_Filesystem_SSH2 extends WP_Filesystem_Base { /** * @since 2.7.0 * @var resource */ public $link = false; /** * @since 2.7.0 * @var resource */ public $sftp_link; /** * @since 2.7.0 * @var bool */ public $keys = false; /** * Constructor. * * @since 2.7.0 * * @param array $opt */ public function __construct( $opt = '' ) { $this->method = 'ssh2'; $this->errors = new WP_Error(); // Check if possible to use ssh2 functions. if ( ! extension_loaded( 'ssh2' ) ) { $this->errors->add( 'no_ssh2_ext', __( 'The ssh2 PHP extension is not available' ) ); return; } // Set defaults: if ( empty( $opt['port'] ) ) { $this->options['port'] = 22; } else { $this->options['port'] = $opt['port']; } if ( empty( $opt['hostname'] ) ) { $this->errors->add( 'empty_hostname', __( 'SSH2 hostname is required' ) ); } else { $this->options['hostname'] = $opt['hostname']; } // Check if the options provided are OK. if ( ! empty( $opt['public_key'] ) && ! empty( $opt['private_key'] ) ) { $this->options['public_key'] = $opt['public_key']; $this->options['private_key'] = $opt['private_key']; $this->options['hostkey'] = array( 'hostkey' => 'ssh-rsa,ssh-ed25519' ); $this->keys = true; } elseif ( empty( $opt['username'] ) ) { $this->errors->add( 'empty_username', __( 'SSH2 username is required' ) ); } if ( ! empty( $opt['username'] ) ) { $this->options['username'] = $opt['username']; } if ( empty( $opt['password'] ) ) { // Password can be blank if we are using keys. if ( ! $this->keys ) { $this->errors->add( 'empty_password', __( 'SSH2 password is required' ) ); } } else { $this->options['password'] = $opt['password']; } } /** * Connects filesystem. * * @since 2.7.0 * * @return bool True on success, false on failure. */ public function connect() { if ( ! $this->keys ) { $this->link = @ssh2_connect( $this->options['hostname'], $this->options['port'] ); } else { $this->link = @ssh2_connect( $this->options['hostname'], $this->options['port'], $this->options['hostkey'] ); } if ( ! $this->link ) { $this->errors->add( 'connect', sprintf( /* translators: %s: hostname:port */ __( 'Failed to connect to SSH2 Server %s' ), $this->options['hostname'] . ':' . $this->options['port'] ) ); return false; } if ( ! $this->keys ) { if ( ! @ssh2_auth_password( $this->link, $this->options['username'], $this->options['password'] ) ) { $this->errors->add( 'auth', sprintf( /* translators: %s: Username. */ __( 'Username/Password incorrect for %s' ), $this->options['username'] ) ); return false; } } else { if ( ! @ssh2_auth_pubkey_file( $this->link, $this->options['username'], $this->options['public_key'], $this->options['private_key'], $this->options['password'] ) ) { $this->errors->add( 'auth', sprintf( /* translators: %s: Username. */ __( 'Public and Private keys incorrect for %s' ), $this->options['username'] ) ); return false; } } $this->sftp_link = ssh2_sftp( $this->link ); if ( ! $this->sftp_link ) { $this->errors->add( 'connect', sprintf( /* translators: %s: hostname:port */ __( 'Failed to initialize a SFTP subsystem session with the SSH2 Server %s' ), $this->options['hostname'] . ':' . $this->options['port'] ) ); return false; } return true; } /** * Gets the ssh2.sftp PHP stream wrapper path to open for the given file. * * This method also works around a PHP bug where the root directory (/) cannot * be opened by PHP functions, causing a false failure. In order to work around * this, the path is converted to /./ which is semantically the same as / * See https://bugs.php.net/bug.php?id=64169 for more details. * * @since 4.4.0 * * @param string $path The File/Directory path on the remote server to return * @return string The ssh2.sftp:// wrapped path to use. */ public function sftp_path( $path ) { if ( '/' === $path ) { $path = '/./'; } return 'ssh2.sftp://' . $this->sftp_link . '/' . ltrim( $path, '/' ); } /** * @since 2.7.0 * * @param string $command * @param bool $returnbool * @return bool|string True on success, false on failure. String if the command was executed, `$returnbool` * is false (default), and data from the resulting stream was retrieved. */ public function run_command( $command, $returnbool = false ) { if ( ! $this->link ) { return false; } $stream = ssh2_exec( $this->link, $command ); if ( ! $stream ) { $this->errors->add( 'command', sprintf( /* translators: %s: Command. */ __( 'Unable to perform command: %s' ), $command ) ); } else { stream_set_blocking( $stream, true ); stream_set_timeout( $stream, FS_TIMEOUT ); $data = stream_get_contents( $stream ); fclose( $stream ); if ( $returnbool ) { return ( false === $data ) ? false : '' !== trim( $data ); } else { return $data; } } return false; } /** * Reads entire file into a string. * * @since 2.7.0 * * @param string $file Name of the file to read. * @return string|false Read data on success, false if no temporary file could be opened, * or if the file couldn't be retrieved. */ public function get_contents( $file ) { return file_get_contents( $this->sftp_path( $file ) ); } /** * Reads entire file into an array. * * @since 2.7.0 * * @param string $file Path to the file. * @return array|false File contents in an array on success, false on failure. */ public function get_contents_array( $file ) { return file( $this->sftp_path( $file ) ); } /** * Writes a string to a file. * * @since 2.7.0 * * @param string $file Remote path to the file where to write the data. * @param string $contents The data to write. * @param int|false $mode Optional. The file permissions as octal number, usually 0644. * Default false. * @return bool True on success, false on failure. */ public function put_contents( $file, $contents, $mode = false ) { $ret = file_put_contents( $this->sftp_path( $file ), $contents ); if ( strlen( $contents ) !== $ret ) { return false; } $this->chmod( $file, $mode ); return true; } /** * Gets the current working directory. * * @since 2.7.0 * * @return string|false The current working directory on success, false on failure. */ public function cwd() { $cwd = ssh2_sftp_realpath( $this->sftp_link, '.' ); if ( $cwd ) { $cwd = trailingslashit( trim( $cwd ) ); } return $cwd; } /** * Changes current directory. * * @since 2.7.0 * * @param string $dir The new current directory. * @return bool True on success, false on failure. */ public function chdir( $dir ) { return $this->run_command( 'cd ' . $dir, true ); } /** * Changes the file group. * * @since 2.7.0 * * @param string $file Path to the file. * @param string|int $group A group name or number. * @param bool $recursive Optional. If set to true, changes file group recursively. * Default false. * @return bool True on success, false on failure. */ public function chgrp( $file, $group, $recursive = false ) { if ( ! $this->exists( $file ) ) { return false; } if ( ! $recursive || ! $this->is_dir( $file ) ) { return $this->run_command( sprintf( 'chgrp %s %s', escapeshellarg( $group ), escapeshellarg( $file ) ), true ); } return $this->run_command( sprintf( 'chgrp -R %s %s', escapeshellarg( $group ), escapeshellarg( $file ) ), true ); } /** * Changes filesystem permissions. * * @since 2.7.0 * * @param string $file Path to the file. * @param int|false $mode Optional. The permissions as octal number, usually 0644 for files, * 0755 for directories. Default false. * @param bool $recursive Optional. If set to true, changes file permissions recursively. * Default false. * @return bool True on success, false on failure. */ public function chmod( $file, $mode = false, $recursive = false ) { if ( ! $this->exists( $file ) ) { return false; } if ( ! $mode ) { if ( $this->is_file( $file ) ) { $mode = FS_CHMOD_FILE; } elseif ( $this->is_dir( $file ) ) { $mode = FS_CHMOD_DIR; } else { return false; } } if ( ! $recursive || ! $this->is_dir( $file ) ) { return $this->run_command( sprintf( 'chmod %o %s', $mode, escapeshellarg( $file ) ), true ); } return $this->run_command( sprintf( 'chmod -R %o %s', $mode, escapeshellarg( $file ) ), true ); } /** * Changes the owner of a file or directory. * * @since 2.7.0 * * @param string $file Path to the file or directory. * @param string|int $owner A user name or number. * @param bool $recursive Optional. If set to true, changes file owner recursively. * Default false. * @return bool True on success, false on failure. */ public function chown( $file, $owner, $recursive = false ) { if ( ! $this->exists( $file ) ) { return false; } if ( ! $recursive || ! $this->is_dir( $file ) ) { return $this->run_command( sprintf( 'chown %s %s', escapeshellarg( $owner ), escapeshellarg( $file ) ), true ); } return $this->run_command( sprintf( 'chown -R %s %s', escapeshellarg( $owner ), escapeshellarg( $file ) ), true ); } /** * Gets the file owner. * * @since 2.7.0 * * @param string $file Path to the file. * @return string|false Username of the owner on success, false on failure. */ public function owner( $file ) { $owneruid = @fileowner( $this->sftp_path( $file ) ); if ( ! $owneruid ) { return false; } if ( ! function_exists( 'posix_getpwuid' ) ) { return $owneruid; } $ownerarray = posix_getpwuid( $owneruid ); if ( ! $ownerarray ) { return false; } return $ownerarray['name']; } /** * Gets the permissions of the specified file or filepath in their octal format. * * @since 2.7.0 * * @param string $file Path to the file. * @return string Mode of the file (the last 3 digits). */ public function getchmod( $file ) { return substr( decoct( @fileperms( $this->sftp_path( $file ) ) ), -3 ); } /** * Gets the file's group. * * @since 2.7.0 * * @param string $file Path to the file. * @return string|false The group on success, false on failure. */ public function group( $file ) { $gid = @filegroup( $this->sftp_path( $file ) ); if ( ! $gid ) { return false; } if ( ! function_exists( 'posix_getgrgid' ) ) { return $gid; } $grouparray = posix_getgrgid( $gid ); if ( ! $grouparray ) { return false; } return $grouparray['name']; } /** * Copies a file. * * @since 2.7.0 * * @param string $source Path to the source file. * @param string $destination Path to the destination file. * @param bool $overwrite Optional. Whether to overwrite the destination file if it exists. * Default false. * @param int|false $mode Optional. The permissions as octal number, usually 0644 for files, * 0755 for dirs. Default false. * @return bool True on success, false on failure. */ public function copy( $source, $destination, $overwrite = false, $mode = false ) { if ( ! $overwrite && $this->exists( $destination ) ) { return false; } $content = $this->get_contents( $source ); if ( false === $content ) { return false; } return $this->put_contents( $destination, $content, $mode ); } /** * Moves a file. * * @since 2.7.0 * * @param string $source Path to the source file. * @param string $destination Path to the destination file. * @param bool $overwrite Optional. Whether to overwrite the destination file if it exists. * Default false. * @return bool True on success, false on failure. */ public function move( $source, $destination, $overwrite = false ) { if ( $this->exists( $destination ) ) { if ( $overwrite ) { // We need to remove the destination file before we can rename the source. $this->delete( $destination, false, 'f' ); } else { // If we're not overwriting, the rename will fail, so return early. return false; } } return ssh2_sftp_rename( $this->sftp_link, $source, $destination ); } /** * Deletes a file or directory. * * @since 2.7.0 * * @param string $file Path to the file or directory. * @param bool $recursive Optional. If set to true, deletes files and folders recursively. * Default false. * @param string|false $type Type of resource. 'f' for file, 'd' for directory. * Default false. * @return bool True on success, false on failure. */ public function delete( $file, $recursive = false, $type = false ) { if ( 'f' === $type || $this->is_file( $file ) ) { return ssh2_sftp_unlink( $this->sftp_link, $file ); } if ( ! $recursive ) { return ssh2_sftp_rmdir( $this->sftp_link, $file ); } $filelist = $this->dirlist( $file ); if ( is_array( $filelist ) ) { foreach ( $filelist as $filename => $fileinfo ) { $this->delete( $file . '/' . $filename, $recursive, $fileinfo['type'] ); } } return ssh2_sftp_rmdir( $this->sftp_link, $file ); } /** * Checks if a file or directory exists. * * @since 2.7.0 * * @param string $path Path to file or directory. * @return bool Whether $path exists or not. */ public function exists( $path ) { return file_exists( $this->sftp_path( $path ) ); } /** * Checks if resource is a file. * * @since 2.7.0 * * @param string $file File path. * @return bool Whether $file is a file. */ public function is_file( $file ) { return is_file( $this->sftp_path( $file ) ); } /** * Checks if resource is a directory. * * @since 2.7.0 * * @param string $path Directory path. * @return bool Whether $path is a directory. */ public function is_dir( $path ) { return is_dir( $this->sftp_path( $path ) ); } /** * Checks if a file is readable. * * @since 2.7.0 * * @param string $file Path to file. * @return bool Whether $file is readable. */ public function is_readable( $file ) { return is_readable( $this->sftp_path( $file ) ); } /** * Checks if a file or directory is writable. * * @since 2.7.0 * * @param string $path Path to file or directory. * @return bool Whether $path is writable. */ public function is_writable( $path ) { // PHP will base its writable checks on system_user === file_owner, not ssh_user === file_owner. return true; } /** * Gets the file's last access time. * * @since 2.7.0 * * @param string $file Path to file. * @return int|false Unix timestamp representing last access time, false on failure. */ public function atime( $file ) { return fileatime( $this->sftp_path( $file ) ); } /** * Gets the file modification time. * * @since 2.7.0 * * @param string $file Path to file. * @return int|false Unix timestamp representing modification time, false on failure. */ public function mtime( $file ) { return filemtime( $this->sftp_path( $file ) ); } /** * Gets the file size (in bytes). * * @since 2.7.0 * * @param string $file Path to file. * @return int|false Size of the file in bytes on success, false on failure. */ public function size( $file ) { return filesize( $this->sftp_path( $file ) ); } /** * Sets the access and modification times of a file. * * Note: Not implemented. * * @since 2.7.0 * * @param string $file Path to file. * @param int $time Optional. Modified time to set for file. * Default 0. * @param int $atime Optional. Access time to set for file. * Default 0. */ public function touch( $file, $time = 0, $atime = 0 ) { // Not implemented. } /** * Creates a directory. * * @since 2.7.0 * * @param string $path Path for new directory. * @param int|false $chmod Optional. The permissions as octal number (or false to skip chmod). * Default false. * @param string|int|false $chown Optional. A user name or number (or false to skip chown). * Default false. * @param string|int|false $chgrp Optional. A group name or number (or false to skip chgrp). * Default false. * @return bool True on success, false on failure. */ public function mkdir( $path, $chmod = false, $chown = false, $chgrp = false ) { $path = untrailingslashit( $path ); if ( empty( $path ) ) { return false; } if ( ! $chmod ) { $chmod = FS_CHMOD_DIR; } if ( ! ssh2_sftp_mkdir( $this->sftp_link, $path, $chmod, true ) ) { return false; } // Set directory permissions. ssh2_sftp_chmod( $this->sftp_link, $path, $chmod ); if ( $chown ) { $this->chown( $path, $chown ); } if ( $chgrp ) { $this->chgrp( $path, $chgrp ); } return true; } /** * Deletes a directory. * * @since 2.7.0 * * @param string $path Path to directory. * @param bool $recursive Optional. Whether to recursively remove files/directories. * Default false. * @return bool True on success, false on failure. */ public function rmdir( $path, $recursive = false ) { return $this->delete( $path, $recursive ); } /** * Gets details for files in a directory or a specific file. * * @since 2.7.0 * * @param string $path Path to directory or file. * @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files. * Default true. * @param bool $recursive Optional. Whether to recursively include file details in nested directories. * Default false. * @return array|false { * Array of files. False if unable to list directory contents. * * @type string $name Name of the file or directory. * @type string $perms *nix representation of permissions. * @type string $permsn Octal representation of permissions. * @type string $owner Owner name or ID. * @type int $size Size of file in bytes. * @type int $lastmodunix Last modified unix timestamp. * @type mixed $lastmod Last modified month (3 letter) and day (without leading 0). * @type int $time Last modified time. * @type string $type Type of resource. 'f' for file, 'd' for directory. * @type mixed $files If a directory and `$recursive` is true, contains another array of files. * } */ public function dirlist( $path, $include_hidden = true, $recursive = false ) { if ( $this->is_file( $path ) ) { $limit_file = basename( $path ); $path = dirname( $path ); } else { $limit_file = false; } if ( ! $this->is_dir( $path ) || ! $this->is_readable( $path ) ) { return false; } $ret = array(); $dir = dir( $this->sftp_path( $path ) ); if ( ! $dir ) { return false; } while ( false !== ( $entry = $dir->read() ) ) { $struc = array(); $struc['name'] = $entry; if ( '.' === $struc['name'] || '..' === $struc['name'] ) { continue; // Do not care about these folders. } if ( ! $include_hidden && '.' === $struc['name'][0] ) { continue; } if ( $limit_file && $struc['name'] !== $limit_file ) { continue; } $struc['perms'] = $this->gethchmod( $path . '/' . $entry ); $struc['permsn'] = $this->getnumchmodfromh( $struc['perms'] ); $struc['number'] = false; $struc['owner'] = $this->owner( $path . '/' . $entry ); $struc['group'] = $this->group( $path . '/' . $entry ); $struc['size'] = $this->size( $path . '/' . $entry ); $struc['lastmodunix'] = $this->mtime( $path . '/' . $entry ); $struc['lastmod'] = gmdate( 'M j', $struc['lastmodunix'] ); $struc['time'] = gmdate( 'h:i:s', $struc['lastmodunix'] ); $struc['type'] = $this->is_dir( $path . '/' . $entry ) ? 'd' : 'f'; if ( 'd' === $struc['type'] ) { if ( $recursive ) { $struc['files'] = $this->dirlist( $path . '/' . $struc['name'], $include_hidden, $recursive ); } else { $struc['files'] = array(); } } $ret[ $struc['name'] ] = $struc; } $dir->close(); unset( $dir ); return $ret; } } ``` | Uses | Description | | --- | --- | | [WP\_Filesystem\_Base](wp_filesystem_base) wp-admin/includes/class-wp-filesystem-base.php | Base WordPress Filesystem class which Filesystem implementations extend. | | Version | Description | | --- | --- | | [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
programming_docs
wordpress class WP_Customize_Background_Image_Setting {} class WP\_Customize\_Background\_Image\_Setting {} ================================================== Customizer Background Image Setting class. * [WP\_Customize\_Setting](wp_customize_setting) * [update](wp_customize_background_image_setting/update) File: `wp-includes/customize/class-wp-customize-background-image-setting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-background-image-setting.php/) ``` final class WP_Customize_Background_Image_Setting extends WP_Customize_Setting { /** * Unique string identifier for the setting. * * @since 3.4.0 * @var string */ public $id = 'background_image_thumb'; /** * @since 3.4.0 * * @param mixed $value The value to update. Not used. */ public function update( $value ) { remove_theme_mod( 'background_image_thumb' ); } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Setting](wp_customize_setting) wp-includes/class-wp-customize-setting.php | Customize Setting class. | | Version | Description | | --- | --- | | [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. | wordpress class Requests_Exception_HTTP_305 {} class Requests\_Exception\_HTTP\_305 {} ======================================= Exception for 305 Use Proxy responses File: `wp-includes/Requests/Exception/HTTP/305.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/305.php/) ``` class Requests_Exception_HTTP_305 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 305; /** * Reason phrase * * @var string */ protected $reason = 'Use Proxy'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_Fatal_Error_Handler {} class WP\_Fatal\_Error\_Handler {} ================================== Core class used as the default shutdown handler for fatal errors. A drop-in β€˜fatal-error-handler.php’ can be used to override the instance of this class and use a custom implementation for the fatal error handler that WordPress registers. The custom class should extend this class and can override its methods individually as necessary. The file must return the instance of the class that should be registered. * [detect\_error](wp_fatal_error_handler/detect_error) β€” Detects the error causing the crash if it should be handled. * [display\_default\_error\_template](wp_fatal_error_handler/display_default_error_template) β€” Displays the default PHP error template. * [display\_error\_template](wp_fatal_error_handler/display_error_template) β€” Displays the PHP error template and sends the HTTP status code, typically 500. * [handle](wp_fatal_error_handler/handle) β€” Runs the shutdown handler. * [should\_handle\_error](wp_fatal_error_handler/should_handle_error) β€” Determines whether we are dealing with an error that WordPress should handle in order to protect the admin backend against WSODs. File: `wp-includes/class-wp-fatal-error-handler.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-fatal-error-handler.php/) ``` class WP_Fatal_Error_Handler { /** * Runs the shutdown handler. * * This method is registered via `register_shutdown_function()`. * * @since 5.2.0 */ public function handle() { if ( defined( 'WP_SANDBOX_SCRAPING' ) && WP_SANDBOX_SCRAPING ) { return; } // Do not trigger the fatal error handler while updates are being installed. if ( wp_is_maintenance_mode() ) { return; } try { // Bail if no error found. $error = $this->detect_error(); if ( ! $error ) { return; } if ( ! isset( $GLOBALS['wp_locale'] ) && function_exists( 'load_default_textdomain' ) ) { load_default_textdomain(); } $handled = false; if ( ! is_multisite() && wp_recovery_mode()->is_initialized() ) { $handled = wp_recovery_mode()->handle_error( $error ); } // Display the PHP error template if headers not sent. if ( is_admin() || ! headers_sent() ) { $this->display_error_template( $error, $handled ); } } catch ( Exception $e ) { // Catch exceptions and remain silent. } } /** * Detects the error causing the crash if it should be handled. * * @since 5.2.0 * * @return array|null Error information returned by `error_get_last()`, or null * if none was recorded or the error should not be handled. */ protected function detect_error() { $error = error_get_last(); // No error, just skip the error handling code. if ( null === $error ) { return null; } // Bail if this error should not be handled. if ( ! $this->should_handle_error( $error ) ) { return null; } return $error; } /** * Determines whether we are dealing with an error that WordPress should handle * in order to protect the admin backend against WSODs. * * @since 5.2.0 * * @param array $error Error information retrieved from `error_get_last()`. * @return bool Whether WordPress should handle this error. */ protected function should_handle_error( $error ) { $error_types_to_handle = array( E_ERROR, E_PARSE, E_USER_ERROR, E_COMPILE_ERROR, E_RECOVERABLE_ERROR, ); if ( isset( $error['type'] ) && in_array( $error['type'], $error_types_to_handle, true ) ) { return true; } /** * Filters whether a given thrown error should be handled by the fatal error handler. * * This filter is only fired if the error is not already configured to be handled by WordPress core. As such, * it exclusively allows adding further rules for which errors should be handled, but not removing existing * ones. * * @since 5.2.0 * * @param bool $should_handle_error Whether the error should be handled by the fatal error handler. * @param array $error Error information retrieved from `error_get_last()`. */ return (bool) apply_filters( 'wp_should_handle_php_error', false, $error ); } /** * Displays the PHP error template and sends the HTTP status code, typically 500. * * A drop-in 'php-error.php' can be used as a custom template. This drop-in should control the HTTP status code and * print the HTML markup indicating that a PHP error occurred. Note that this drop-in may potentially be executed * very early in the WordPress bootstrap process, so any core functions used that are not part of * `wp-includes/load.php` should be checked for before being called. * * If no such drop-in is available, this will call {@see WP_Fatal_Error_Handler::display_default_error_template()}. * * @since 5.2.0 * @since 5.3.0 The `$handled` parameter was added. * * @param array $error Error information retrieved from `error_get_last()`. * @param true|WP_Error $handled Whether Recovery Mode handled the fatal error. */ protected function display_error_template( $error, $handled ) { if ( defined( 'WP_CONTENT_DIR' ) ) { // Load custom PHP error template, if present. $php_error_pluggable = WP_CONTENT_DIR . '/php-error.php'; if ( is_readable( $php_error_pluggable ) ) { require_once $php_error_pluggable; return; } } // Otherwise, display the default error template. $this->display_default_error_template( $error, $handled ); } /** * Displays the default PHP error template. * * This method is called conditionally if no 'php-error.php' drop-in is available. * * It calls {@see wp_die()} with a message indicating that the site is experiencing technical difficulties and a * login link to the admin backend. The {@see 'wp_php_error_message'} and {@see 'wp_php_error_args'} filters can * be used to modify these parameters. * * @since 5.2.0 * @since 5.3.0 The `$handled` parameter was added. * * @param array $error Error information retrieved from `error_get_last()`. * @param true|WP_Error $handled Whether Recovery Mode handled the fatal error. */ protected function display_default_error_template( $error, $handled ) { if ( ! function_exists( '__' ) ) { wp_load_translations_early(); } if ( ! function_exists( 'wp_die' ) ) { require_once ABSPATH . WPINC . '/functions.php'; } if ( ! class_exists( 'WP_Error' ) ) { require_once ABSPATH . WPINC . '/class-wp-error.php'; } if ( true === $handled && wp_is_recovery_mode() ) { $message = __( 'There has been a critical error on this website, putting it in recovery mode. Please check the Themes and Plugins screens for more details. If you just installed or updated a theme or plugin, check the relevant page for that first.' ); } elseif ( is_protected_endpoint() && wp_recovery_mode()->is_initialized() ) { if ( is_multisite() ) { $message = __( 'There has been a critical error on this website. Please reach out to your site administrator, and inform them of this error for further assistance.' ); } else { $message = __( 'There has been a critical error on this website. Please check your site admin email inbox for instructions.' ); } } else { $message = __( 'There has been a critical error on this website.' ); } $message = sprintf( '<p>%s</p><p><a href="%s">%s</a></p>', $message, /* translators: Documentation about troubleshooting. */ __( 'https://wordpress.org/support/article/faq-troubleshooting/' ), __( 'Learn more about troubleshooting WordPress.' ) ); $args = array( 'response' => 500, 'exit' => false, ); /** * Filters the message that the default PHP error template displays. * * @since 5.2.0 * * @param string $message HTML error message to display. * @param array $error Error information retrieved from `error_get_last()`. */ $message = apply_filters( 'wp_php_error_message', $message, $error ); /** * Filters the arguments passed to {@see wp_die()} for the default PHP error template. * * @since 5.2.0 * * @param array $args Associative array of arguments passed to `wp_die()`. By default these contain a * 'response' key, and optionally 'link_url' and 'link_text' keys. * @param array $error Error information retrieved from `error_get_last()`. */ $args = apply_filters( 'wp_php_error_args', $args, $error ); $wp_error = new WP_Error( 'internal_server_error', $message, array( 'error' => $error, ) ); wp_die( $wp_error, '', $args ); } } ``` | Version | Description | | --- | --- | | [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. | wordpress class WP_Block_List {} class WP\_Block\_List {} ======================== Class representing a list of block instances. * [\_\_construct](wp_block_list/__construct) β€” Constructor. * [count](wp_block_list/count) * [current](wp_block_list/current) * [key](wp_block_list/key) * [next](wp_block_list/next) * [offsetExists](wp_block_list/offsetexists) * [offsetGet](wp_block_list/offsetget) * [offsetSet](wp_block_list/offsetset) * [offsetUnset](wp_block_list/offsetunset) * [rewind](wp_block_list/rewind) * [valid](wp_block_list/valid) File: `wp-includes/class-wp-block-list.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-list.php/) ``` class WP_Block_List implements Iterator, ArrayAccess, Countable { /** * Original array of parsed block data, or block instances. * * @since 5.5.0 * @var array[]|WP_Block[] * @access protected */ protected $blocks; /** * All available context of the current hierarchy. * * @since 5.5.0 * @var array * @access protected */ protected $available_context; /** * Block type registry to use in constructing block instances. * * @since 5.5.0 * @var WP_Block_Type_Registry * @access protected */ protected $registry; /** * Constructor. * * Populates object properties from the provided block instance argument. * * @since 5.5.0 * * @param array[]|WP_Block[] $blocks Array of parsed block data, or block instances. * @param array $available_context Optional array of ancestry context values. * @param WP_Block_Type_Registry $registry Optional block type registry. */ public function __construct( $blocks, $available_context = array(), $registry = null ) { if ( ! $registry instanceof WP_Block_Type_Registry ) { $registry = WP_Block_Type_Registry::get_instance(); } $this->blocks = $blocks; $this->available_context = $available_context; $this->registry = $registry; } /** * Returns true if a block exists by the specified block index, or false * otherwise. * * @since 5.5.0 * * @link https://www.php.net/manual/en/arrayaccess.offsetexists.php * * @param string $index Index of block to check. * @return bool Whether block exists. */ #[ReturnTypeWillChange] public function offsetExists( $index ) { return isset( $this->blocks[ $index ] ); } /** * Returns the value by the specified block index. * * @since 5.5.0 * * @link https://www.php.net/manual/en/arrayaccess.offsetget.php * * @param string $index Index of block value to retrieve. * @return mixed|null Block value if exists, or null. */ #[ReturnTypeWillChange] public function offsetGet( $index ) { $block = $this->blocks[ $index ]; if ( isset( $block ) && is_array( $block ) ) { $block = new WP_Block( $block, $this->available_context, $this->registry ); $this->blocks[ $index ] = $block; } return $block; } /** * Assign a block value by the specified block index. * * @since 5.5.0 * * @link https://www.php.net/manual/en/arrayaccess.offsetset.php * * @param string $index Index of block value to set. * @param mixed $value Block value. */ #[ReturnTypeWillChange] public function offsetSet( $index, $value ) { if ( is_null( $index ) ) { $this->blocks[] = $value; } else { $this->blocks[ $index ] = $value; } } /** * Unset a block. * * @since 5.5.0 * * @link https://www.php.net/manual/en/arrayaccess.offsetunset.php * * @param string $index Index of block value to unset. */ #[ReturnTypeWillChange] public function offsetUnset( $index ) { unset( $this->blocks[ $index ] ); } /** * Rewinds back to the first element of the Iterator. * * @since 5.5.0 * * @link https://www.php.net/manual/en/iterator.rewind.php */ #[ReturnTypeWillChange] public function rewind() { reset( $this->blocks ); } /** * Returns the current element of the block list. * * @since 5.5.0 * * @link https://www.php.net/manual/en/iterator.current.php * * @return mixed Current element. */ #[ReturnTypeWillChange] public function current() { return $this->offsetGet( $this->key() ); } /** * Returns the key of the current element of the block list. * * @since 5.5.0 * * @link https://www.php.net/manual/en/iterator.key.php * * @return mixed Key of the current element. */ #[ReturnTypeWillChange] public function key() { return key( $this->blocks ); } /** * Moves the current position of the block list to the next element. * * @since 5.5.0 * * @link https://www.php.net/manual/en/iterator.next.php */ #[ReturnTypeWillChange] public function next() { next( $this->blocks ); } /** * Checks if current position is valid. * * @since 5.5.0 * * @link https://www.php.net/manual/en/iterator.valid.php */ #[ReturnTypeWillChange] public function valid() { return null !== key( $this->blocks ); } /** * Returns the count of blocks in the list. * * @since 5.5.0 * * @link https://www.php.net/manual/en/countable.count.php * * @return int Block count. */ #[ReturnTypeWillChange] public function count() { return count( $this->blocks ); } } ``` | Version | Description | | --- | --- | | [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. | wordpress class WP_Customize_Nav_Menu_Section {} class WP\_Customize\_Nav\_Menu\_Section {} ========================================== Customize Menu Section Class Custom section only needed in JS. * [WP\_Customize\_Section](wp_customize_section) * [json](wp_customize_nav_menu_section/json) β€” Get section parameters for JS. File: `wp-includes/customize/class-wp-customize-nav-menu-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-section.php/) ``` class WP_Customize_Nav_Menu_Section extends WP_Customize_Section { /** * Control type. * * @since 4.3.0 * @var string */ public $type = 'nav_menu'; /** * Get section parameters for JS. * * @since 4.3.0 * @return array Exported parameters. */ public function json() { $exported = parent::json(); $exported['menu_id'] = (int) preg_replace( '/^nav_menu\[(-?\d+)\]/', '$1', $this->id ); return $exported; } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Section](wp_customize_section) wp-includes/class-wp-customize-section.php | Customize Section class. | | Version | Description | | --- | --- | | [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. | wordpress class WP_Customize_Themes_Panel {} class WP\_Customize\_Themes\_Panel {} ===================================== Customize Themes Panel Class * [WP\_Customize\_Panel](wp_customize_panel) * [content\_template](wp_customize_themes_panel/content_template) β€” An Underscore (JS) template for this panel's content (but not its container). * [render\_template](wp_customize_themes_panel/render_template) β€” An Underscore (JS) template for rendering this panel's container. File: `wp-includes/customize/class-wp-customize-themes-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-themes-panel.php/) ``` class WP_Customize_Themes_Panel extends WP_Customize_Panel { /** * Panel type. * * @since 4.9.0 * @var string */ public $type = 'themes'; /** * An Underscore (JS) template for rendering this panel's container. * * The themes panel renders a custom panel heading with the active theme and a switch themes button. * * @see WP_Customize_Panel::print_template() * * @since 4.9.0 */ protected function render_template() { ?> <li id="accordion-section-{{ data.id }}" class="accordion-section control-panel-themes"> <h3 class="accordion-section-title"> <?php if ( $this->manager->is_theme_active() ) { echo '<span class="customize-action">' . __( 'Active theme' ) . '</span> {{ data.title }}'; } else { echo '<span class="customize-action">' . __( 'Previewing theme' ) . '</span> {{ data.title }}'; } ?> <?php if ( current_user_can( 'switch_themes' ) ) : ?> <button type="button" class="button change-theme" aria-label="<?php esc_attr_e( 'Change theme' ); ?>"><?php _ex( 'Change', 'theme' ); ?></button> <?php endif; ?> </h3> <ul class="accordion-sub-container control-panel-content"></ul> </li> <?php } /** * An Underscore (JS) template for this panel's content (but not its container). * * Class variables for this panel class are available in the `data` JS object; * export custom variables by overriding WP_Customize_Panel::json(). * * @since 4.9.0 * * @see WP_Customize_Panel::print_template() */ protected function content_template() { ?> <li class="panel-meta customize-info accordion-section <# if ( ! data.description ) { #> cannot-expand<# } #>"> <button class="customize-panel-back" tabindex="-1" type="button"><span class="screen-reader-text"><?php _e( 'Back' ); ?></span></button> <div class="accordion-section-title"> <span class="preview-notice"> <?php printf( /* translators: %s: Themes panel title in the Customizer. */ __( 'You are browsing %s' ), '<strong class="panel-title">' . __( 'Themes' ) . '</strong>' ); // Separate strings for consistency with other panels. ?> </span> <?php if ( current_user_can( 'install_themes' ) && ! is_multisite() ) : ?> <# if ( data.description ) { #> <button class="customize-help-toggle dashicons dashicons-editor-help" type="button" aria-expanded="false"><span class="screen-reader-text"><?php _e( 'Help' ); ?></span></button> <# } #> <?php endif; ?> </div> <?php if ( current_user_can( 'install_themes' ) && ! is_multisite() ) : ?> <# if ( data.description ) { #> <div class="description customize-panel-description"> {{{ data.description }}} </div> <# } #> <?php endif; ?> <div class="customize-control-notifications-container"></div> </li> <li class="customize-themes-full-container-container"> <div class="customize-themes-full-container"> <div class="customize-themes-notifications"></div> </div> </li> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Panel](wp_customize_panel) wp-includes/class-wp-customize-panel.php | Customize Panel class. | | Version | Description | | --- | --- | | [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
programming_docs
wordpress class WP_Widget_Media_Video {} class WP\_Widget\_Media\_Video {} ================================= Core class that implements a video widget. * [WP\_Widget\_Media](wp_widget_media) * [WP\_Widget](wp_widget) * [\_\_construct](wp_widget_media_video/__construct) β€” Constructor. * [enqueue\_admin\_scripts](wp_widget_media_video/enqueue_admin_scripts) β€” Loads the required scripts and styles for the widget control. * [enqueue\_preview\_scripts](wp_widget_media_video/enqueue_preview_scripts) β€” Enqueue preview scripts. * [get\_instance\_schema](wp_widget_media_video/get_instance_schema) β€” Get schema for properties of a widget instance (item). * [inject\_video\_max\_width\_style](wp_widget_media_video/inject_video_max_width_style) β€” Inject max-width and remove height for videos too constrained to fit inside sidebars on frontend. * [render\_control\_template\_scripts](wp_widget_media_video/render_control_template_scripts) β€” Render form template scripts. * [render\_media](wp_widget_media_video/render_media) β€” Render the media on the frontend. File: `wp-includes/widgets/class-wp-widget-media-video.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-video.php/) ``` class WP_Widget_Media_Video extends WP_Widget_Media { /** * Constructor. * * @since 4.8.0 */ public function __construct() { parent::__construct( 'media_video', __( 'Video' ), array( 'description' => __( 'Displays a video from the media library or from YouTube, Vimeo, or another provider.' ), 'mime_type' => 'video', ) ); $this->l10n = array_merge( $this->l10n, array( 'no_media_selected' => __( 'No video selected' ), 'add_media' => _x( 'Add Video', 'label for button in the video widget' ), 'replace_media' => _x( 'Replace Video', 'label for button in the video widget; should preferably not be longer than ~13 characters long' ), 'edit_media' => _x( 'Edit Video', 'label for button in the video widget; should preferably not be longer than ~13 characters long' ), 'missing_attachment' => sprintf( /* translators: %s: URL to media library. */ __( 'That video cannot be found. Check your <a href="%s">media library</a> and make sure it was not deleted.' ), esc_url( admin_url( 'upload.php' ) ) ), /* translators: %d: Widget count. */ 'media_library_state_multi' => _n_noop( 'Video Widget (%d)', 'Video Widget (%d)' ), 'media_library_state_single' => __( 'Video Widget' ), /* translators: %s: A list of valid video file extensions. */ 'unsupported_file_type' => sprintf( __( 'Sorry, the video at the supplied URL cannot be loaded. Please check that the URL is for a supported video file (%s) or stream (e.g. YouTube and Vimeo).' ), '<code>.' . implode( '</code>, <code>.', wp_get_video_extensions() ) . '</code>' ), ) ); } /** * Get schema for properties of a widget instance (item). * * @since 4.8.0 * * @see WP_REST_Controller::get_item_schema() * @see WP_REST_Controller::get_additional_fields() * @link https://core.trac.wordpress.org/ticket/35574 * * @return array Schema for properties. */ public function get_instance_schema() { $schema = array( 'preload' => array( 'type' => 'string', 'enum' => array( 'none', 'auto', 'metadata' ), 'default' => 'metadata', 'description' => __( 'Preload' ), 'should_preview_update' => false, ), 'loop' => array( 'type' => 'boolean', 'default' => false, 'description' => __( 'Loop' ), 'should_preview_update' => false, ), 'content' => array( 'type' => 'string', 'default' => '', 'sanitize_callback' => 'wp_kses_post', 'description' => __( 'Tracks (subtitles, captions, descriptions, chapters, or metadata)' ), 'should_preview_update' => false, ), ); foreach ( wp_get_video_extensions() as $video_extension ) { $schema[ $video_extension ] = array( 'type' => 'string', 'default' => '', 'format' => 'uri', /* translators: %s: Video extension. */ 'description' => sprintf( __( 'URL to the %s video source file' ), $video_extension ), ); } return array_merge( $schema, parent::get_instance_schema() ); } /** * Render the media on the frontend. * * @since 4.8.0 * * @param array $instance Widget instance props. */ public function render_media( $instance ) { $instance = array_merge( wp_list_pluck( $this->get_instance_schema(), 'default' ), $instance ); $attachment = null; if ( $this->is_attachment_with_mime_type( $instance['attachment_id'], $this->widget_options['mime_type'] ) ) { $attachment = get_post( $instance['attachment_id'] ); } $src = $instance['url']; if ( $attachment ) { $src = wp_get_attachment_url( $attachment->ID ); } if ( empty( $src ) ) { return; } $youtube_pattern = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#'; $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#'; if ( $attachment || preg_match( $youtube_pattern, $src ) || preg_match( $vimeo_pattern, $src ) ) { add_filter( 'wp_video_shortcode', array( $this, 'inject_video_max_width_style' ) ); echo wp_video_shortcode( array_merge( $instance, compact( 'src' ) ), $instance['content'] ); remove_filter( 'wp_video_shortcode', array( $this, 'inject_video_max_width_style' ) ); } else { echo $this->inject_video_max_width_style( wp_oembed_get( $src ) ); } } /** * Inject max-width and remove height for videos too constrained to fit inside sidebars on frontend. * * @since 4.8.0 * * @param string $html Video shortcode HTML output. * @return string HTML Output. */ public function inject_video_max_width_style( $html ) { $html = preg_replace( '/\sheight="\d+"/', '', $html ); $html = preg_replace( '/\swidth="\d+"/', '', $html ); $html = preg_replace( '/(?<=width:)\s*\d+px(?=;?)/', '100%', $html ); return $html; } /** * Enqueue preview scripts. * * These scripts normally are enqueued just-in-time when a video shortcode is used. * In the customizer, however, widgets can be dynamically added and rendered via * selective refresh, and so it is important to unconditionally enqueue them in * case a widget does get added. * * @since 4.8.0 */ public function enqueue_preview_scripts() { /** This filter is documented in wp-includes/media.php */ if ( 'mediaelement' === apply_filters( 'wp_video_shortcode_library', 'mediaelement' ) ) { wp_enqueue_style( 'wp-mediaelement' ); wp_enqueue_script( 'mediaelement-vimeo' ); wp_enqueue_script( 'wp-mediaelement' ); } } /** * Loads the required scripts and styles for the widget control. * * @since 4.8.0 */ public function enqueue_admin_scripts() { parent::enqueue_admin_scripts(); $handle = 'media-video-widget'; wp_enqueue_script( $handle ); $exported_schema = array(); foreach ( $this->get_instance_schema() as $field => $field_schema ) { $exported_schema[ $field ] = wp_array_slice_assoc( $field_schema, array( 'type', 'default', 'enum', 'minimum', 'format', 'media_prop', 'should_preview_update' ) ); } wp_add_inline_script( $handle, sprintf( 'wp.mediaWidgets.modelConstructors[ %s ].prototype.schema = %s;', wp_json_encode( $this->id_base ), wp_json_encode( $exported_schema ) ) ); wp_add_inline_script( $handle, sprintf( ' wp.mediaWidgets.controlConstructors[ %1$s ].prototype.mime_type = %2$s; wp.mediaWidgets.controlConstructors[ %1$s ].prototype.l10n = _.extend( {}, wp.mediaWidgets.controlConstructors[ %1$s ].prototype.l10n, %3$s ); ', wp_json_encode( $this->id_base ), wp_json_encode( $this->widget_options['mime_type'] ), wp_json_encode( $this->l10n ) ) ); } /** * Render form template scripts. * * @since 4.8.0 */ public function render_control_template_scripts() { parent::render_control_template_scripts() ?> <script type="text/html" id="tmpl-wp-media-widget-video-preview"> <# if ( data.error && 'missing_attachment' === data.error ) { #> <div class="notice notice-error notice-alt notice-missing-attachment"> <p><?php echo $this->l10n['missing_attachment']; ?></p> </div> <# } else if ( data.error && 'unsupported_file_type' === data.error ) { #> <div class="notice notice-error notice-alt notice-missing-attachment"> <p><?php echo $this->l10n['unsupported_file_type']; ?></p> </div> <# } else if ( data.error ) { #> <div class="notice notice-error notice-alt"> <p><?php _e( 'Unable to preview media due to an unknown error.' ); ?></p> </div> <# } else if ( data.is_oembed && data.model.poster ) { #> <a href="{{ data.model.src }}" target="_blank" class="media-widget-video-link"> <img src="{{ data.model.poster }}" /> </a> <# } else if ( data.is_oembed ) { #> <a href="{{ data.model.src }}" target="_blank" class="media-widget-video-link no-poster"> <span class="dashicons dashicons-format-video"></span> </a> <# } else if ( data.model.src ) { #> <?php wp_underscore_video_template(); ?> <# } #> </script> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Widget\_Media](wp_widget_media) wp-includes/widgets/class-wp-widget-media.php | Core class that implements a media widget. | | Version | Description | | --- | --- | | [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. | wordpress class WP_Privacy_Data_Export_Requests_List_Table {} class WP\_Privacy\_Data\_Export\_Requests\_List\_Table {} ========================================================= [WP\_Privacy\_Data\_Export\_Requests\_Table](wp_privacy_data_export_requests_table) class. * [column\_email](wp_privacy_data_export_requests_list_table/column_email) β€” Actions column. * [column\_next\_steps](wp_privacy_data_export_requests_list_table/column_next_steps) β€” Displays the next steps column. File: `wp-admin/includes/class-wp-privacy-data-export-requests-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-data-export-requests-list-table.php/) ``` class WP_Privacy_Data_Export_Requests_List_Table extends WP_Privacy_Requests_Table { /** * Action name for the requests this table will work with. * * @since 4.9.6 * * @var string $request_type Name of action. */ protected $request_type = 'export_personal_data'; /** * Post type for the requests. * * @since 4.9.6 * * @var string $post_type The post type. */ protected $post_type = 'user_request'; /** * Actions column. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. * @return string Email column markup. */ public function column_email( $item ) { /** This filter is documented in wp-admin/includes/ajax-actions.php */ $exporters = apply_filters( 'wp_privacy_personal_data_exporters', array() ); $exporters_count = count( $exporters ); $status = $item->status; $request_id = $item->ID; $nonce = wp_create_nonce( 'wp-privacy-export-personal-data-' . $request_id ); $download_data_markup = '<span class="export-personal-data" ' . 'data-exporters-count="' . esc_attr( $exporters_count ) . '" ' . 'data-request-id="' . esc_attr( $request_id ) . '" ' . 'data-nonce="' . esc_attr( $nonce ) . '">'; $download_data_markup .= '<span class="export-personal-data-idle"><button type="button" class="button-link export-personal-data-handle">' . __( 'Download personal data' ) . '</button></span>' . '<span class="export-personal-data-processing hidden">' . __( 'Downloading data...' ) . ' <span class="export-progress"></span></span>' . '<span class="export-personal-data-success hidden"><button type="button" class="button-link export-personal-data-handle">' . __( 'Download personal data again' ) . '</button></span>' . '<span class="export-personal-data-failed hidden">' . __( 'Download failed.' ) . ' <button type="button" class="button-link export-personal-data-handle">' . __( 'Retry' ) . '</button></span>'; $download_data_markup .= '</span>'; $row_actions['download-data'] = $download_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( 'export-personal-data.php' ) ), 'bulk-privacy_requests' ) ), esc_attr( sprintf( /* translators: %s: Request email. */ __( 'Mark export request for &#8220;%s&#8221; 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 ) ); } /** * Displays the next steps column. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. */ 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 */ $exporters = apply_filters( 'wp_privacy_personal_data_exporters', array() ); $exporters_count = count( $exporters ); $request_id = $item->ID; $nonce = wp_create_nonce( 'wp-privacy-export-personal-data-' . $request_id ); echo '<div class="export-personal-data" ' . 'data-send-as-email="1" ' . 'data-exporters-count="' . esc_attr( $exporters_count ) . '" ' . 'data-request-id="' . esc_attr( $request_id ) . '" ' . 'data-nonce="' . esc_attr( $nonce ) . '">'; ?> <span class="export-personal-data-idle"><button type="button" class="button-link export-personal-data-handle"><?php _e( 'Send export link' ); ?></button></span> <span class="export-personal-data-processing hidden"><?php _e( 'Sending email...' ); ?> <span class="export-progress"></span></span> <span class="export-personal-data-success success-message hidden"><?php _e( 'Email sent.' ); ?></span> <span class="export-personal-data-failed hidden"><?php _e( 'Email could not be sent.' ); ?> <button type="button" class="button-link export-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( 'export-personal-data.php' ) ), 'bulk-privacy_requests' ) ) . '">' . esc_html__( 'Remove request' ) . '</a>'; break; } } } ``` | Uses | Description | | --- | --- | | [WP\_Privacy\_Requests\_Table](wp_privacy_requests_table) wp-admin/includes/class-wp-privacy-requests-table.php | List Table API: [WP\_Privacy\_Requests\_Table](wp_privacy_requests_table) class | | Used By | Description | | --- | --- | | [WP\_Privacy\_Data\_Export\_Requests\_Table](wp_privacy_data_export_requests_table) wp-admin/includes/deprecated.php | Previous class for list table for privacy data export requests. | | Version | Description | | --- | --- | | [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. | wordpress class Translation_Entry {} class Translation\_Entry {} =========================== * [\_\_construct](translation_entry/__construct) * [key](translation_entry/key) β€” Generates a unique key for this entry. * [merge\_with](translation_entry/merge_with) * [Translation\_Entry](translation_entry/translation_entry) β€” PHP4 constructor. β€” deprecated File: `wp-includes/pomo/entry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/entry.php/) ``` class Translation_Entry { /** * Whether the entry contains a string and its plural form, default is false. * * @var bool */ public $is_plural = false; public $context = null; public $singular = null; public $plural = null; public $translations = array(); public $translator_comments = ''; public $extracted_comments = ''; public $references = array(); public $flags = array(); /** * @param array $args { * Arguments array, supports the following keys: * * @type string $singular The string to translate, if omitted an * empty entry will be created. * @type string $plural The plural form of the string, setting * this will set `$is_plural` to true. * @type array $translations Translations of the string and possibly * its plural forms. * @type string $context A string differentiating two equal strings * used in different contexts. * @type string $translator_comments Comments left by translators. * @type string $extracted_comments Comments left by developers. * @type array $references Places in the code this string is used, in * relative_to_root_path/file.php:linenum form. * @type array $flags Flags like php-format. * } */ 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(); } } /** * PHP4 constructor. * * @deprecated 5.4.0 Use __construct() instead. * * @see Translation_Entry::__construct() */ public function Translation_Entry( $args = array() ) { _deprecated_constructor( self::class, '5.4.0', static::class ); self::__construct( $args ); } /** * Generates a unique key for this entry. * * @return string|false The key or false if the entry is null. */ 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; } /** * @param object $other */ 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; } } } ```
programming_docs
wordpress class WP_Image_Editor_Imagick {} class WP\_Image\_Editor\_Imagick {} =================================== WordPress Image Editor Class for Image Manipulation through Imagick PHP Module * [WP\_Image\_Editor](wp_image_editor) * [\_\_destruct](wp_image_editor_imagick/__destruct) * [\_save](wp_image_editor_imagick/_save) * [crop](wp_image_editor_imagick/crop) β€” Crops Image. * [flip](wp_image_editor_imagick/flip) β€” Flips current image. * [load](wp_image_editor_imagick/load) β€” Loads image from $this->file into new Imagick Object. * [make\_subsize](wp_image_editor_imagick/make_subsize) β€” Create an image sub-size and return the image meta data value for it. * [maybe\_exif\_rotate](wp_image_editor_imagick/maybe_exif_rotate) β€” Check if a JPEG image has EXIF Orientation tag and rotate it if needed. * [multi\_resize](wp_image_editor_imagick/multi_resize) β€” Create multiple smaller images from a single source. * [pdf\_load\_source](wp_image_editor_imagick/pdf_load_source) β€” Load the image produced by Ghostscript. * [pdf\_setup](wp_image_editor_imagick/pdf_setup) β€” Sets up Imagick for PDF processing. * [resize](wp_image_editor_imagick/resize) β€” Resizes current image. * [rotate](wp_image_editor_imagick/rotate) β€” Rotates current image counter-clockwise by $angle. * [save](wp_image_editor_imagick/save) β€” Saves current image to file. * [set\_quality](wp_image_editor_imagick/set_quality) β€” Sets Image Compression quality on a 1-100% scale. * [stream](wp_image_editor_imagick/stream) β€” Streams current image to browser. * [strip\_meta](wp_image_editor_imagick/strip_meta) β€” Strips all image meta except color profiles from an image. * [supports\_mime\_type](wp_image_editor_imagick/supports_mime_type) β€” Checks to see if editor supports the mime-type specified. * [test](wp_image_editor_imagick/test) β€” Checks to see if current environment supports Imagick. * [thumbnail\_image](wp_image_editor_imagick/thumbnail_image) β€” Efficiently resize the current image * [update\_size](wp_image_editor_imagick/update_size) β€” Sets or updates current image size. * [write\_image](wp_image_editor_imagick/write_image) β€” Writes an image to a file or stream. 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/) ``` class WP_Image_Editor_Imagick extends WP_Image_Editor { /** * Imagick object. * * @var Imagick */ protected $image; public function __destruct() { if ( $this->image instanceof Imagick ) { // We don't need the original in memory anymore. $this->image->clear(); $this->image->destroy(); } } /** * 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. * * @since 3.5.0 * * @param array $args * @return bool */ 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; } /** * Checks to see if editor supports the mime-type specified. * * @since 3.5.0 * * @param string $mime_type * @return bool */ 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; } } /** * Loads image from $this->file into new Imagick Object. * * @since 3.5.0 * * @return true|WP_Error True if loaded; WP_Error on failure. */ 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(); } /** * Sets Image Compression quality on a 1-100% scale. * * @since 3.5.0 * * @param int $quality Compression Quality. Range: [1,100] * @return true|WP_Error True if set successfully; WP_Error on failure. */ 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; } /** * Sets or updates current image size. * * @since 3.5.0 * * @param int $width * @param int $height * @return true|WP_Error */ 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 ); } /** * 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. * * @since 3.5.0 * * @param int|null $max_w Image width. * @param int|null $max_h Image height. * @param bool $crop * @return true|WP_Error */ 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 ); } /** * 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. * * @since 4.5.0 * * @param int $dst_w The destination width. * @param int $dst_h The destination height. * @param string $filter_name Optional. The Imagick filter to use when resizing. Default 'FILTER_TRIANGLE'. * @param bool $strip_meta Optional. Strip all profiles, excluding color profiles, from the image. Default true. * @return void|WP_Error */ 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() ); } } /** * 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. * * @since 3.5.0 * * @param array $sizes { * 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. * * @type array ...$0 { * Array of height, width values, and whether to crop. * * @type int $width Image width. Optional if `$height` is specified. * @type int $height Image height. Optional if `$width` is specified. * @type bool $crop Optional. Whether to crop the image. Default false. * } * } * @return array An array of resized images' metadata by size. */ 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; } /** * Create an image sub-size and return the image meta data value for it. * * @since 5.3.0 * * @param array $size_data { * Array of size data. * * @type int $width The maximum width in pixels. * @type int $height The maximum height in pixels. * @type bool $crop Whether to crop the image to exact dimensions. * } * @return array|WP_Error The image data array for inclusion in the `sizes` array in the image meta, * WP_Error object on error. */ 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; } /** * Crops Image. * * @since 3.5.0 * * @param int $src_x The start x position to crop from. * @param int $src_y The start y position to crop from. * @param int $src_w The width to crop. * @param int $src_h The height to crop. * @param int $dst_w Optional. The destination width. * @param int $dst_h Optional. The destination height. * @param bool $src_abs Optional. If the source crop points are absolute. * @return true|WP_Error */ 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(); } /** * Rotates current image counter-clockwise by $angle. * * @since 3.5.0 * * @param float $angle * @return true|WP_Error */ 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; } /** * Flips current image. * * @since 3.5.0 * * @param bool $horz Flip along Horizontal Axis * @param bool $vert Flip along Vertical Axis * @return true|WP_Error */ 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; } /** * 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. * * @since 5.3.0 * * @return bool|WP_Error True if the image was rotated. False if no EXIF data or if the image doesn't need rotation. * WP_Error if error while rotating. */ 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.' ) ); } } /** * Saves current image to file. * * @since 3.5.0 * @since 6.0.0 The `$filesize` value was added to the returned array. * * @param string $destfilename Optional. Destination filename. Default null. * @param string $mime_type Optional. The mime-type. Default null. * @return array|WP_Error { * Array on success or WP_Error if the file failed to save. * * @type string $path Path to the image file. * @type string $file Name of the image file. * @type int $width Image width. * @type int $height Image height. * @type string $mime-type The mime type of the image. * @type int $filesize File size of the image. * } */ 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; } /** * @since 3.5.0 * @since 6.0.0 The `$filesize` value was added to the returned array. * * @param Imagick $image * @param string $filename * @param string $mime_type * @return array|WP_Error { * Array on success or WP_Error if the file failed to save. * * @type string $path Path to the image file. * @type string $file Name of the image file. * @type int $width Image width. * @type int $height Image height. * @type string $mime-type The mime type of the image. * @type int $filesize File size of the image. * } */ 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 ), ); } /** * Writes an image to a file or stream. * * @since 5.6.0 * * @param Imagick $image * @param string $filename The destination filename or stream URL. * @return true|WP_Error */ 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 ); } } } /** * Streams current image to browser. * * @since 3.5.0 * * @param string $mime_type The mime type of the image. * @return true|WP_Error True on success, WP_Error object on failure. */ 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; } /** * Strips all image meta except color profiles from an image. * * @since 4.5.0 * * @return true|WP_Error True if stripping metadata was successful. WP_Error object on error. */ 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; } /** * Sets up Imagick for PDF processing. * Increases rendering DPI and only loads first page. * * @since 4.7.0 * * @return string|WP_Error File to load or WP_Error on failure. */ 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 ); } } /** * 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. * * @since 5.6.0 * * @return true|WP_Error */ 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](wp_image_editor) wp-includes/class-wp-image-editor.php | Base image editor class from which implementations extend | | Version | Description | | --- | --- | | [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
programming_docs
wordpress class WP_HTTP_Response {} class WP\_HTTP\_Response {} =========================== Core class used to prepare HTTP responses. * [\_\_construct](wp_http_response/__construct) β€” Constructor. * [get\_data](wp_http_response/get_data) β€” Retrieves the response data. * [get\_headers](wp_http_response/get_headers) β€” Retrieves headers associated with the response. * [get\_status](wp_http_response/get_status) β€” Retrieves the HTTP return code for the response. * [header](wp_http_response/header) β€” Sets a single HTTP header. * [jsonSerialize](wp_http_response/jsonserialize) β€” Retrieves the response data for JSON serialization. * [set\_data](wp_http_response/set_data) β€” Sets the response data. * [set\_headers](wp_http_response/set_headers) β€” Sets all header values. * [set\_status](wp_http_response/set_status) β€” Sets the 3-digit HTTP status code. File: `wp-includes/class-wp-http-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-response.php/) ``` class WP_HTTP_Response { /** * Response data. * * @since 4.4.0 * @var mixed */ public $data; /** * Response headers. * * @since 4.4.0 * @var array */ public $headers; /** * Response status. * * @since 4.4.0 * @var int */ public $status; /** * Constructor. * * @since 4.4.0 * * @param mixed $data Response data. Default null. * @param int $status Optional. HTTP status code. Default 200. * @param array $headers Optional. HTTP header map. Default empty array. */ public function __construct( $data = null, $status = 200, $headers = array() ) { $this->set_data( $data ); $this->set_status( $status ); $this->set_headers( $headers ); } /** * Retrieves headers associated with the response. * * @since 4.4.0 * * @return array Map of header name to header value. */ public function get_headers() { return $this->headers; } /** * Sets all header values. * * @since 4.4.0 * * @param array $headers Map of header name to header value. */ public function set_headers( $headers ) { $this->headers = $headers; } /** * Sets a single HTTP header. * * @since 4.4.0 * * @param string $key Header name. * @param string $value Header value. * @param bool $replace Optional. Whether to replace an existing header of the same name. * Default true. */ public function header( $key, $value, $replace = true ) { if ( $replace || ! isset( $this->headers[ $key ] ) ) { $this->headers[ $key ] = $value; } else { $this->headers[ $key ] .= ', ' . $value; } } /** * Retrieves the HTTP return code for the response. * * @since 4.4.0 * * @return int The 3-digit HTTP status code. */ public function get_status() { return $this->status; } /** * Sets the 3-digit HTTP status code. * * @since 4.4.0 * * @param int $code HTTP status. */ public function set_status( $code ) { $this->status = absint( $code ); } /** * Retrieves the response data. * * @since 4.4.0 * * @return mixed Response data. */ public function get_data() { return $this->data; } /** * Sets the response data. * * @since 4.4.0 * * @param mixed $data Response data. */ public function set_data( $data ) { $this->data = $data; } /** * Retrieves the response data for JSON serialization. * * It is expected that in most implementations, this will return the same as get_data(), * however this may be different if you want to do custom JSON data handling. * * @since 4.4.0 * * @return mixed Any JSON-serializable value. */ public function jsonSerialize() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid return $this->get_data(); } } ``` | Used By | Description | | --- | --- | | [WP\_HTTP\_Requests\_Response](wp_http_requests_response) wp-includes/class-wp-http-requests-response.php | Core wrapper object for a [Requests\_Response](requests_response) for standardisation. | | [WP\_REST\_Response](wp_rest_response) wp-includes/rest-api/class-wp-rest-response.php | Core class used to implement a REST response object. | | Version | Description | | --- | --- | | [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. | wordpress class WP_Privacy_Data_Removal_Requests_List_Table {} class WP\_Privacy\_Data\_Removal\_Requests\_List\_Table {} ========================================================== [WP\_Privacy\_Data\_Removal\_Requests\_List\_Table](wp_privacy_data_removal_requests_list_table) class. * [column\_email](wp_privacy_data_removal_requests_list_table/column_email) β€” Actions column. * [column\_next\_steps](wp_privacy_data_removal_requests_list_table/column_next_steps) β€” Next steps column. 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/) ``` class WP_Privacy_Data_Removal_Requests_List_Table extends WP_Privacy_Requests_Table { /** * Action name for the requests this table will work with. * * @since 4.9.6 * * @var string $request_type Name of action. */ protected $request_type = 'remove_personal_data'; /** * Post type for the requests. * * @since 4.9.6 * * @var string $post_type The post type. */ protected $post_type = 'user_request'; /** * Actions column. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. * @return string Email column markup. */ 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 &#8220;%s&#8221; 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 ) ); } /** * Next steps column. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. */ 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; } } } ``` | Uses | Description | | --- | --- | | [WP\_Privacy\_Requests\_Table](wp_privacy_requests_table) wp-admin/includes/class-wp-privacy-requests-table.php | List Table API: [WP\_Privacy\_Requests\_Table](wp_privacy_requests_table) class | | Used By | Description | | --- | --- | | [WP\_Privacy\_Data\_Removal\_Requests\_Table](wp_privacy_data_removal_requests_table) wp-admin/includes/deprecated.php | Previous class for list table for privacy data erasure requests. | | Version | Description | | --- | --- | | [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. | wordpress class Plugin_Upgrader {} class Plugin\_Upgrader {} ========================= Core class used for upgrading/installing plugins. It is designed to upgrade/install plugins from a local zip, remote zip URL, or uploaded zip file. * [WP\_Upgrader](wp_upgrader) * [active\_after](plugin_upgrader/active_after) β€” Turns off maintenance mode after upgrading an active plugin. * [active\_before](plugin_upgrader/active_before) β€” Turns on maintenance mode before attempting to background update an active plugin. * [bulk\_upgrade](plugin_upgrader/bulk_upgrade) β€” Bulk upgrade several plugins at once. * [check\_package](plugin_upgrader/check_package) β€” Checks that the source package contains a valid plugin. * [deactivate\_plugin\_before\_upgrade](plugin_upgrader/deactivate_plugin_before_upgrade) β€” Deactivates a plugin before it is upgraded. * [delete\_old\_plugin](plugin_upgrader/delete_old_plugin) β€” Deletes the old plugin during an upgrade. * [install](plugin_upgrader/install) β€” Install a plugin package. * [install\_strings](plugin_upgrader/install_strings) β€” Initialize the installation strings. * [plugin\_info](plugin_upgrader/plugin_info) β€” Retrieve the path to the file that contains the plugin info. * [upgrade](plugin_upgrader/upgrade) β€” Upgrade a plugin. * [upgrade\_strings](plugin_upgrader/upgrade_strings) β€” Initialize the upgrade strings. File: `wp-admin/includes/class-plugin-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-plugin-upgrader.php/) ``` class Plugin_Upgrader extends WP_Upgrader { /** * Plugin upgrade result. * * @since 2.8.0 * @var array|WP_Error $result * * @see WP_Upgrader::$result */ public $result; /** * Whether a bulk upgrade/installation is being performed. * * @since 2.9.0 * @var bool $bulk */ public $bulk = false; /** * New plugin info. * * @since 5.5.0 * @var array $new_plugin_data * * @see check_package() */ public $new_plugin_data = array(); /** * Initialize the upgrade strings. * * @since 2.8.0 */ public function upgrade_strings() { $this->strings['up_to_date'] = __( 'The plugin is at the latest version.' ); $this->strings['no_package'] = __( 'Update package not available.' ); /* translators: %s: Package URL. */ $this->strings['downloading_package'] = sprintf( __( 'Downloading update from %s&#8230;' ), '<span class="code">%s</span>' ); $this->strings['unpack_package'] = __( 'Unpacking the update&#8230;' ); $this->strings['remove_old'] = __( 'Removing the old version of the plugin&#8230;' ); $this->strings['remove_old_failed'] = __( 'Could not remove the old plugin.' ); $this->strings['process_failed'] = __( 'Plugin update failed.' ); $this->strings['process_success'] = __( 'Plugin updated successfully.' ); $this->strings['process_bulk_success'] = __( 'Plugins updated successfully.' ); } /** * Initialize the installation strings. * * @since 2.8.0 */ public function install_strings() { $this->strings['no_package'] = __( 'Installation package not available.' ); /* translators: %s: Package URL. */ $this->strings['downloading_package'] = sprintf( __( 'Downloading installation package from %s&#8230;' ), '<span class="code">%s</span>' ); $this->strings['unpack_package'] = __( 'Unpacking the package&#8230;' ); $this->strings['installing_package'] = __( 'Installing the plugin&#8230;' ); $this->strings['remove_old'] = __( 'Removing the current plugin&#8230;' ); $this->strings['remove_old_failed'] = __( 'Could not remove the current plugin.' ); $this->strings['no_files'] = __( 'The plugin contains no files.' ); $this->strings['process_failed'] = __( 'Plugin installation failed.' ); $this->strings['process_success'] = __( 'Plugin installed successfully.' ); /* translators: 1: Plugin name, 2: Plugin version. */ $this->strings['process_success_specific'] = __( 'Successfully installed the plugin <strong>%1$s %2$s</strong>.' ); if ( ! empty( $this->skin->overwrite ) ) { if ( 'update-plugin' === $this->skin->overwrite ) { $this->strings['installing_package'] = __( 'Updating the plugin&#8230;' ); $this->strings['process_failed'] = __( 'Plugin update failed.' ); $this->strings['process_success'] = __( 'Plugin updated successfully.' ); } if ( 'downgrade-plugin' === $this->skin->overwrite ) { $this->strings['installing_package'] = __( 'Downgrading the plugin&#8230;' ); $this->strings['process_failed'] = __( 'Plugin downgrade failed.' ); $this->strings['process_success'] = __( 'Plugin downgraded successfully.' ); } } } /** * Install a plugin package. * * @since 2.8.0 * @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional. * * @param string $package The full local path or URI of the package. * @param array $args { * Optional. Other arguments for installing a plugin package. Default empty array. * * @type bool $clear_update_cache Whether to clear the plugin updates cache if successful. * Default true. * } * @return bool|WP_Error True if the installation was successful, false or a WP_Error otherwise. */ public function install( $package, $args = array() ) { $defaults = array( 'clear_update_cache' => true, 'overwrite_package' => false, // Do not overwrite files. ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->install_strings(); add_filter( 'upgrader_source_selection', array( $this, 'check_package' ) ); if ( $parsed_args['clear_update_cache'] ) { // Clear cache so wp_update_plugins() knows about the new plugin. add_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9, 0 ); } $this->run( array( 'package' => $package, 'destination' => WP_PLUGIN_DIR, 'clear_destination' => $parsed_args['overwrite_package'], 'clear_working' => true, 'hook_extra' => array( 'type' => 'plugin', 'action' => 'install', ), ) ); remove_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9 ); remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) ); if ( ! $this->result || is_wp_error( $this->result ) ) { return $this->result; } // Force refresh of plugin update information. wp_clean_plugins_cache( $parsed_args['clear_update_cache'] ); if ( $parsed_args['overwrite_package'] ) { /** * Fires when the upgrader has successfully overwritten a currently installed * plugin or theme with an uploaded zip package. * * @since 5.5.0 * * @param string $package The package file. * @param array $data The new plugin or theme data. * @param string $package_type The package type ('plugin' or 'theme'). */ do_action( 'upgrader_overwrote_package', $package, $this->new_plugin_data, 'plugin' ); } return true; } /** * Upgrade a plugin. * * @since 2.8.0 * @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional. * * @param string $plugin Path to the plugin file relative to the plugins directory. * @param array $args { * Optional. Other arguments for upgrading a plugin package. Default empty array. * * @type bool $clear_update_cache Whether to clear the plugin updates cache if successful. * Default true. * } * @return bool|WP_Error True if the upgrade was successful, false or a WP_Error object otherwise. */ public function upgrade( $plugin, $args = array() ) { $defaults = array( 'clear_update_cache' => true, ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->upgrade_strings(); $current = get_site_transient( 'update_plugins' ); if ( ! isset( $current->response[ $plugin ] ) ) { $this->skin->before(); $this->skin->set_result( false ); $this->skin->error( 'up_to_date' ); $this->skin->after(); return false; } // Get the URL to the zip file. $r = $current->response[ $plugin ]; add_filter( 'upgrader_pre_install', array( $this, 'deactivate_plugin_before_upgrade' ), 10, 2 ); add_filter( 'upgrader_pre_install', array( $this, 'active_before' ), 10, 2 ); add_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ), 10, 4 ); add_filter( 'upgrader_post_install', array( $this, 'active_after' ), 10, 2 ); // There's a Trac ticket to move up the directory for zips which are made a bit differently, useful for non-.org plugins. // 'source_selection' => array( $this, 'source_selection' ), if ( $parsed_args['clear_update_cache'] ) { // Clear cache so wp_update_plugins() knows about the new plugin. add_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9, 0 ); } $this->run( array( 'package' => $r->package, 'destination' => WP_PLUGIN_DIR, 'clear_destination' => true, 'clear_working' => true, 'hook_extra' => array( 'plugin' => $plugin, 'type' => 'plugin', 'action' => 'update', ), ) ); // Cleanup our hooks, in case something else does a upgrade on this connection. remove_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9 ); remove_filter( 'upgrader_pre_install', array( $this, 'deactivate_plugin_before_upgrade' ) ); remove_filter( 'upgrader_pre_install', array( $this, 'active_before' ) ); remove_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ) ); remove_filter( 'upgrader_post_install', array( $this, 'active_after' ) ); if ( ! $this->result || is_wp_error( $this->result ) ) { return $this->result; } // Force refresh of plugin update information. wp_clean_plugins_cache( $parsed_args['clear_update_cache'] ); // Ensure any future auto-update failures trigger a failure email by removing // the last failure notification from the list when plugins update successfully. $past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() ); if ( isset( $past_failure_emails[ $plugin ] ) ) { unset( $past_failure_emails[ $plugin ] ); update_option( 'auto_plugin_theme_update_emails', $past_failure_emails ); } return true; } /** * Bulk upgrade several plugins at once. * * @since 2.8.0 * @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional. * * @param string[] $plugins Array of paths to plugin files relative to the plugins directory. * @param array $args { * Optional. Other arguments for upgrading several plugins at once. * * @type bool $clear_update_cache Whether to clear the plugin updates cache if successful. Default true. * } * @return array|false An array of results indexed by plugin file, or false if unable to connect to the filesystem. */ public function bulk_upgrade( $plugins, $args = array() ) { $defaults = array( 'clear_update_cache' => true, ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->bulk = true; $this->upgrade_strings(); $current = get_site_transient( 'update_plugins' ); add_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ), 10, 4 ); $this->skin->header(); // Connect to the filesystem first. $res = $this->fs_connect( array( WP_CONTENT_DIR, WP_PLUGIN_DIR ) ); if ( ! $res ) { $this->skin->footer(); return false; } $this->skin->bulk_header(); /* * Only start maintenance mode if: * - running Multisite and there are one or more plugins specified, OR * - a plugin with an update available is currently active. * @todo For multisite, maintenance mode should only kick in for individual sites if at all possible. */ $maintenance = ( is_multisite() && ! empty( $plugins ) ); foreach ( $plugins as $plugin ) { $maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin ] ) ); } if ( $maintenance ) { $this->maintenance_mode( true ); } $results = array(); $this->update_count = count( $plugins ); $this->update_current = 0; foreach ( $plugins as $plugin ) { $this->update_current++; $this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true ); if ( ! isset( $current->response[ $plugin ] ) ) { $this->skin->set_result( 'up_to_date' ); $this->skin->before(); $this->skin->feedback( 'up_to_date' ); $this->skin->after(); $results[ $plugin ] = true; continue; } // Get the URL to the zip file. $r = $current->response[ $plugin ]; $this->skin->plugin_active = is_plugin_active( $plugin ); $result = $this->run( array( 'package' => $r->package, 'destination' => WP_PLUGIN_DIR, 'clear_destination' => true, 'clear_working' => true, 'is_multi' => true, 'hook_extra' => array( 'plugin' => $plugin, ), ) ); $results[ $plugin ] = $result; // Prevent credentials auth screen from displaying multiple times. if ( false === $result ) { break; } } // End foreach $plugins. $this->maintenance_mode( false ); // Force refresh of plugin update information. wp_clean_plugins_cache( $parsed_args['clear_update_cache'] ); /** This action is documented in wp-admin/includes/class-wp-upgrader.php */ do_action( 'upgrader_process_complete', $this, array( 'action' => 'update', 'type' => 'plugin', 'bulk' => true, 'plugins' => $plugins, ) ); $this->skin->bulk_footer(); $this->skin->footer(); // Cleanup our hooks, in case something else does a upgrade on this connection. remove_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ) ); // Ensure any future auto-update failures trigger a failure email by removing // the last failure notification from the list when plugins update successfully. $past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() ); foreach ( $results as $plugin => $result ) { // Maintain last failure notification when plugins failed to update manually. if ( ! $result || is_wp_error( $result ) || ! isset( $past_failure_emails[ $plugin ] ) ) { continue; } unset( $past_failure_emails[ $plugin ] ); } update_option( 'auto_plugin_theme_update_emails', $past_failure_emails ); return $results; } /** * Checks that the source package contains a valid plugin. * * Hooked to the {@see 'upgrader_source_selection'} filter by Plugin_Upgrader::install(). * * @since 3.3.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * @global string $wp_version The WordPress version string. * * @param string $source The path to the downloaded package source. * @return string|WP_Error The source as passed, or a WP_Error object on failure. */ public function check_package( $source ) { global $wp_filesystem, $wp_version; $this->new_plugin_data = array(); if ( is_wp_error( $source ) ) { return $source; } $working_directory = str_replace( $wp_filesystem->wp_content_dir(), trailingslashit( WP_CONTENT_DIR ), $source ); if ( ! is_dir( $working_directory ) ) { // Sanity check, if the above fails, let's not prevent installation. return $source; } // Check that the folder contains at least 1 valid plugin. $files = glob( $working_directory . '*.php' ); if ( $files ) { foreach ( $files as $file ) { $info = get_plugin_data( $file, false, false ); if ( ! empty( $info['Name'] ) ) { $this->new_plugin_data = $info; break; } } } if ( empty( $this->new_plugin_data ) ) { return new WP_Error( 'incompatible_archive_no_plugins', $this->strings['incompatible_archive'], __( 'No valid plugins were found.' ) ); } $requires_php = isset( $info['RequiresPHP'] ) ? $info['RequiresPHP'] : null; $requires_wp = isset( $info['RequiresWP'] ) ? $info['RequiresWP'] : null; if ( ! is_php_version_compatible( $requires_php ) ) { $error = sprintf( /* translators: 1: Current PHP version, 2: Version required by the uploaded plugin. */ __( 'The PHP version on your server is %1$s, however the uploaded plugin requires %2$s.' ), PHP_VERSION, $requires_php ); return new WP_Error( 'incompatible_php_required_version', $this->strings['incompatible_archive'], $error ); } if ( ! is_wp_version_compatible( $requires_wp ) ) { $error = sprintf( /* translators: 1: Current WordPress version, 2: Version required by the uploaded plugin. */ __( 'Your WordPress version is %1$s, however the uploaded plugin requires %2$s.' ), $wp_version, $requires_wp ); return new WP_Error( 'incompatible_wp_required_version', $this->strings['incompatible_archive'], $error ); } return $source; } /** * Retrieve the path to the file that contains the plugin info. * * This isn't used internally in the class, but is called by the skins. * * @since 2.8.0 * * @return string|false The full path to the main plugin file, or false. */ public function plugin_info() { if ( ! is_array( $this->result ) ) { return false; } if ( empty( $this->result['destination_name'] ) ) { return false; } // Ensure to pass with leading slash. $plugin = get_plugins( '/' . $this->result['destination_name'] ); if ( empty( $plugin ) ) { return false; } // Assume the requested plugin is the first in the list. $pluginfiles = array_keys( $plugin ); return $this->result['destination_name'] . '/' . $pluginfiles[0]; } /** * Deactivates a plugin before it is upgraded. * * Hooked to the {@see 'upgrader_pre_install'} filter by Plugin_Upgrader::upgrade(). * * @since 2.8.0 * @since 4.1.0 Added a return value. * * @param bool|WP_Error $response The installation response before the installation has started. * @param array $plugin Plugin package arguments. * @return bool|WP_Error The original `$response` parameter or WP_Error. */ public function deactivate_plugin_before_upgrade( $response, $plugin ) { if ( is_wp_error( $response ) ) { // Bypass. return $response; } // When in cron (background updates) don't deactivate the plugin, as we require a browser to reactivate it. if ( wp_doing_cron() ) { return $response; } $plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : ''; if ( empty( $plugin ) ) { return new WP_Error( 'bad_request', $this->strings['bad_request'] ); } if ( is_plugin_active( $plugin ) ) { // Deactivate the plugin silently, Prevent deactivation hooks from running. deactivate_plugins( $plugin, true ); } return $response; } /** * Turns on maintenance mode before attempting to background update an active plugin. * * Hooked to the {@see 'upgrader_pre_install'} filter by Plugin_Upgrader::upgrade(). * * @since 5.4.0 * * @param bool|WP_Error $response The installation response before the installation has started. * @param array $plugin Plugin package arguments. * @return bool|WP_Error The original `$response` parameter or WP_Error. */ public function active_before( $response, $plugin ) { if ( is_wp_error( $response ) ) { return $response; } // Only enable maintenance mode when in cron (background update). if ( ! wp_doing_cron() ) { return $response; } $plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : ''; // Only run if plugin is active. if ( ! is_plugin_active( $plugin ) ) { return $response; } // Change to maintenance mode. Bulk edit handles this separately. if ( ! $this->bulk ) { $this->maintenance_mode( true ); } return $response; } /** * Turns off maintenance mode after upgrading an active plugin. * * Hooked to the {@see 'upgrader_post_install'} filter by Plugin_Upgrader::upgrade(). * * @since 5.4.0 * * @param bool|WP_Error $response The installation response after the installation has finished. * @param array $plugin Plugin package arguments. * @return bool|WP_Error The original `$response` parameter or WP_Error. */ public function active_after( $response, $plugin ) { if ( is_wp_error( $response ) ) { return $response; } // Only disable maintenance mode when in cron (background update). if ( ! wp_doing_cron() ) { return $response; } $plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : ''; // Only run if plugin is active. if ( ! is_plugin_active( $plugin ) ) { return $response; } // Time to remove maintenance mode. Bulk edit handles this separately. if ( ! $this->bulk ) { $this->maintenance_mode( false ); } return $response; } /** * Deletes the old plugin during an upgrade. * * Hooked to the {@see 'upgrader_clear_destination'} filter by * Plugin_Upgrader::upgrade() and Plugin_Upgrader::bulk_upgrade(). * * @since 2.8.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param bool|WP_Error $removed Whether the destination was cleared. * True on success, WP_Error on failure. * @param string $local_destination The local package destination. * @param string $remote_destination The remote package destination. * @param array $plugin Extra arguments passed to hooked filters. * @return bool|WP_Error */ public function delete_old_plugin( $removed, $local_destination, $remote_destination, $plugin ) { global $wp_filesystem; if ( is_wp_error( $removed ) ) { return $removed; // Pass errors through. } $plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : ''; if ( empty( $plugin ) ) { return new WP_Error( 'bad_request', $this->strings['bad_request'] ); } $plugins_dir = $wp_filesystem->wp_plugins_dir(); $this_plugin_dir = trailingslashit( dirname( $plugins_dir . $plugin ) ); if ( ! $wp_filesystem->exists( $this_plugin_dir ) ) { // If it's already vanished. return $removed; } // If plugin is in its own directory, recursively delete the directory. // Base check on if plugin includes directory separator AND that it's not the root plugin folder. if ( strpos( $plugin, '/' ) && $this_plugin_dir !== $plugins_dir ) { $deleted = $wp_filesystem->delete( $this_plugin_dir, true ); } else { $deleted = $wp_filesystem->delete( $plugins_dir . $plugin ); } if ( ! $deleted ) { return new WP_Error( 'remove_old_failed', $this->strings['remove_old_failed'] ); } return true; } } ``` | Uses | Description | | --- | --- | | [WP\_Upgrader](wp_upgrader) wp-admin/includes/class-wp-upgrader.php | | | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Moved to its own file from wp-admin/includes/class-wp-upgrader.php. | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
programming_docs
wordpress class WP_User_Request {} class WP\_User\_Request {} ========================== [WP\_User\_Request](wp_user_request) class. Represents user request data loaded from a [WP\_Post](wp_post) object. * [\_\_construct](wp_user_request/__construct) β€” Constructor. File: `wp-includes/class-wp-user-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user-request.php/) ``` final class WP_User_Request { /** * Request ID. * * @since 4.9.6 * @var int */ public $ID = 0; /** * User ID. * * @since 4.9.6 * @var int */ public $user_id = 0; /** * User email. * * @since 4.9.6 * @var string */ public $email = ''; /** * Action name. * * @since 4.9.6 * @var string */ public $action_name = ''; /** * Current status. * * @since 4.9.6 * @var string */ public $status = ''; /** * Timestamp this request was created. * * @since 4.9.6 * @var int|null */ public $created_timestamp = null; /** * Timestamp this request was last modified. * * @since 4.9.6 * @var int|null */ public $modified_timestamp = null; /** * Timestamp this request was confirmed. * * @since 4.9.6 * @var int|null */ public $confirmed_timestamp = null; /** * Timestamp this request was completed. * * @since 4.9.6 * @var int|null */ public $completed_timestamp = null; /** * Misc data assigned to this request. * * @since 4.9.6 * @var array */ public $request_data = array(); /** * Key used to confirm this request. * * @since 4.9.6 * @var string */ public $confirm_key = ''; /** * Constructor. * * @since 4.9.6 * * @param WP_Post|object $post Post object. */ 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; } } ``` | Version | Description | | --- | --- | | [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. | wordpress class WP_Customize_Header_Image_Setting {} class WP\_Customize\_Header\_Image\_Setting {} ============================================== A setting that is used to filter a value, but will not save the results. Results should be properly handled using another setting or callback. * [WP\_Customize\_Setting](wp_customize_setting) * [update](wp_customize_header_image_setting/update) File: `wp-includes/customize/class-wp-customize-header-image-setting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-header-image-setting.php/) ``` final class WP_Customize_Header_Image_Setting extends WP_Customize_Setting { /** * Unique string identifier for the setting. * * @since 3.4.0 * @var string */ public $id = 'header_image_data'; /** * @since 3.4.0 * * @global Custom_Image_Header $custom_image_header * * @param mixed $value The value to update. */ public function update( $value ) { global $custom_image_header; // If _custom_header_background_just_in_time() fails to initialize $custom_image_header when not is_admin(). if ( empty( $custom_image_header ) ) { require_once ABSPATH . 'wp-admin/includes/class-custom-image-header.php'; $args = get_theme_support( 'custom-header' ); $admin_head_callback = isset( $args[0]['admin-head-callback'] ) ? $args[0]['admin-head-callback'] : null; $admin_preview_callback = isset( $args[0]['admin-preview-callback'] ) ? $args[0]['admin-preview-callback'] : null; $custom_image_header = new Custom_Image_Header( $admin_head_callback, $admin_preview_callback ); } // If the value doesn't exist (removed or random), // use the header_image value. if ( ! $value ) { $value = $this->manager->get_setting( 'header_image' )->post_value(); } if ( is_array( $value ) && isset( $value['choice'] ) ) { $custom_image_header->set_header_image( $value['choice'] ); } else { $custom_image_header->set_header_image( $value ); } } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Setting](wp_customize_setting) wp-includes/class-wp-customize-setting.php | Customize Setting class. | | Version | Description | | --- | --- | | [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. | wordpress class _WP_List_Table_Compat {} class \_WP\_List\_Table\_Compat {} ================================== Helper class to be used only by back compat functions. * [\_\_construct](_wp_list_table_compat/__construct) β€” Constructor. * [get\_column\_info](_wp_list_table_compat/get_column_info) β€” Gets a list of all, hidden, and sortable columns. * [get\_columns](_wp_list_table_compat/get_columns) β€” Gets a list of columns. File: `wp-admin/includes/class-wp-list-table-compat.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-list-table-compat.php/) ``` class _WP_List_Table_Compat extends WP_List_Table { public $_screen; public $_columns; /** * Constructor. * * @since 3.1.0 * * @param string|WP_Screen $screen The screen hook name or screen object. * @param string[] $columns An array of columns with column IDs as the keys * and translated column names as the values. */ public function __construct( $screen, $columns = array() ) { if ( is_string( $screen ) ) { $screen = convert_to_screen( $screen ); } $this->_screen = $screen; if ( ! empty( $columns ) ) { $this->_columns = $columns; add_filter( 'manage_' . $screen->id . '_columns', array( $this, 'get_columns' ), 0 ); } } /** * Gets a list of all, hidden, and sortable columns. * * @since 3.1.0 * * @return array */ protected function get_column_info() { $columns = get_column_headers( $this->_screen ); $hidden = get_hidden_columns( $this->_screen ); $sortable = array(); $primary = $this->get_default_primary_column_name(); return array( $columns, $hidden, $sortable, $primary ); } /** * Gets a list of columns. * * @since 3.1.0 * * @return array */ public function get_columns() { return $this->_columns; } } ``` | Uses | Description | | --- | --- | | [WP\_List\_Table](wp_list_table) wp-admin/includes/class-wp-list-table.php | Base class for displaying a list of items in an ajaxified HTML table. | | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. | wordpress class Requests_Exception_HTTP_503 {} class Requests\_Exception\_HTTP\_503 {} ======================================= Exception for 503 Service Unavailable responses File: `wp-includes/Requests/Exception/HTTP/503.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/503.php/) ``` class Requests_Exception_HTTP_503 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 503; /** * Reason phrase * * @var string */ protected $reason = 'Service Unavailable'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_Http {} class WP\_Http {} ================= * [\_dispatch\_request](wp_http/_dispatch_request) β€” Dispatches a HTTP request to a supporting transport. β€” deprecated * [\_get\_first\_available\_transport](wp_http/_get_first_available_transport) β€” Tests which transports are capable of supporting the request. * [block\_request](wp_http/block_request) β€” Determines whether an HTTP API request to the given URL should be blocked. * [browser\_redirect\_compatibility](wp_http/browser_redirect_compatibility) β€” Match redirect behaviour to browser handling. * [buildCookieHeader](wp_http/buildcookieheader) β€” Takes the arguments for a ::request() and checks for the cookie array. * [chunkTransferDecode](wp_http/chunktransferdecode) β€” Decodes chunk transfer-encoding, based off the HTTP 1.1 specification. * [get](wp_http/get) β€” Uses the GET HTTP method. * [handle\_redirects](wp_http/handle_redirects) β€” Handles an HTTP redirect and follows it if appropriate. * [head](wp_http/head) β€” Uses the HEAD HTTP method. * [is\_ip\_address](wp_http/is_ip_address) β€” Determines if a specified string represents an IP address or not. * [make\_absolute\_url](wp_http/make_absolute_url) β€” Converts a relative URL to an absolute URL relative to a given URL. * [normalize\_cookies](wp_http/normalize_cookies) β€” Normalizes cookies for using in Requests. * [parse\_url](wp_http/parse_url) β€” Used as a wrapper for PHP's parse\_url() function that handles edgecases in < PHP 5.4.7. β€” deprecated * [post](wp_http/post) β€” Uses the POST HTTP method. * [processHeaders](wp_http/processheaders) β€” Transforms header string into an array. * [processResponse](wp_http/processresponse) β€” Parses the responses and splits the parts into headers and body. * [request](wp_http/request) β€” Send an HTTP request to a URI. * [validate\_redirects](wp_http/validate_redirects) β€” Validate redirected URLs. File: `wp-includes/class-wp-http.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http.php/) ``` class WP_Http { // Aliases for HTTP response codes. const HTTP_CONTINUE = 100; const SWITCHING_PROTOCOLS = 101; const PROCESSING = 102; const EARLY_HINTS = 103; const OK = 200; const CREATED = 201; const ACCEPTED = 202; const NON_AUTHORITATIVE_INFORMATION = 203; const NO_CONTENT = 204; const RESET_CONTENT = 205; const PARTIAL_CONTENT = 206; const MULTI_STATUS = 207; const IM_USED = 226; const MULTIPLE_CHOICES = 300; const MOVED_PERMANENTLY = 301; const FOUND = 302; const SEE_OTHER = 303; const NOT_MODIFIED = 304; const USE_PROXY = 305; const RESERVED = 306; const TEMPORARY_REDIRECT = 307; const PERMANENT_REDIRECT = 308; const BAD_REQUEST = 400; const UNAUTHORIZED = 401; const PAYMENT_REQUIRED = 402; const FORBIDDEN = 403; const NOT_FOUND = 404; const METHOD_NOT_ALLOWED = 405; const NOT_ACCEPTABLE = 406; const PROXY_AUTHENTICATION_REQUIRED = 407; const REQUEST_TIMEOUT = 408; const CONFLICT = 409; const GONE = 410; const LENGTH_REQUIRED = 411; const PRECONDITION_FAILED = 412; const REQUEST_ENTITY_TOO_LARGE = 413; const REQUEST_URI_TOO_LONG = 414; const UNSUPPORTED_MEDIA_TYPE = 415; const REQUESTED_RANGE_NOT_SATISFIABLE = 416; const EXPECTATION_FAILED = 417; const IM_A_TEAPOT = 418; const MISDIRECTED_REQUEST = 421; const UNPROCESSABLE_ENTITY = 422; const LOCKED = 423; const FAILED_DEPENDENCY = 424; const UPGRADE_REQUIRED = 426; const PRECONDITION_REQUIRED = 428; const TOO_MANY_REQUESTS = 429; const REQUEST_HEADER_FIELDS_TOO_LARGE = 431; const UNAVAILABLE_FOR_LEGAL_REASONS = 451; const INTERNAL_SERVER_ERROR = 500; const NOT_IMPLEMENTED = 501; const BAD_GATEWAY = 502; const SERVICE_UNAVAILABLE = 503; const GATEWAY_TIMEOUT = 504; const HTTP_VERSION_NOT_SUPPORTED = 505; const VARIANT_ALSO_NEGOTIATES = 506; const INSUFFICIENT_STORAGE = 507; const NOT_EXTENDED = 510; const NETWORK_AUTHENTICATION_REQUIRED = 511; /** * Send an HTTP request to a URI. * * Please note: The only URI that are supported in the HTTP Transport implementation * are the HTTP and HTTPS protocols. * * @since 2.7.0 * * @param string $url The request URL. * @param string|array $args { * Optional. Array or string of HTTP request arguments. * * @type string $method Request method. Accepts 'GET', 'POST', 'HEAD', 'PUT', 'DELETE', * 'TRACE', 'OPTIONS', or 'PATCH'. * Some transports technically allow others, but should not be * assumed. Default 'GET'. * @type float $timeout How long the connection should stay open in seconds. Default 5. * @type int $redirection Number of allowed redirects. Not supported by all transports. * Default 5. * @type string $httpversion Version of the HTTP protocol to use. Accepts '1.0' and '1.1'. * Default '1.0'. * @type string $user-agent User-agent value sent. * Default 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ). * @type bool $reject_unsafe_urls Whether to pass URLs through wp_http_validate_url(). * Default false. * @type bool $blocking Whether the calling code requires the result of the request. * If set to false, the request will be sent to the remote server, * and processing returned to the calling code immediately, the caller * will know if the request succeeded or failed, but will not receive * any response from the remote server. Default true. * @type string|array $headers Array or string of headers to send with the request. * Default empty array. * @type array $cookies List of cookies to send with the request. Default empty array. * @type string|array $body Body to send with the request. Default null. * @type bool $compress Whether to compress the $body when sending the request. * Default false. * @type bool $decompress Whether to decompress a compressed response. If set to false and * compressed content is returned in the response anyway, it will * need to be separately decompressed. Default true. * @type bool $sslverify Whether to verify SSL for the request. Default true. * @type string $sslcertificates Absolute path to an SSL certificate .crt file. * Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'. * @type bool $stream Whether to stream to a file. If set to true and no filename was * given, it will be dropped it in the WP temp dir and its name will * be set using the basename of the URL. Default false. * @type string $filename Filename of the file to write to when streaming. $stream must be * set to true. Default null. * @type int $limit_response_size Size in bytes to limit the response to. Default null. * * } * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. * A WP_Error instance upon error. */ public function request( $url, $args = array() ) { $defaults = array( 'method' => 'GET', /** * Filters the timeout value for an HTTP request. * * @since 2.7.0 * @since 5.1.0 The `$url` parameter was added. * * @param float $timeout_value Time in seconds until a request times out. Default 5. * @param string $url The request URL. */ 'timeout' => apply_filters( 'http_request_timeout', 5, $url ), /** * Filters the number of redirects allowed during an HTTP request. * * @since 2.7.0 * @since 5.1.0 The `$url` parameter was added. * * @param int $redirect_count Number of redirects allowed. Default 5. * @param string $url The request URL. */ 'redirection' => apply_filters( 'http_request_redirection_count', 5, $url ), /** * Filters the version of the HTTP protocol used in a request. * * @since 2.7.0 * @since 5.1.0 The `$url` parameter was added. * * @param string $version Version of HTTP used. Accepts '1.0' and '1.1'. Default '1.0'. * @param string $url The request URL. */ 'httpversion' => apply_filters( 'http_request_version', '1.0', $url ), /** * Filters the user agent value sent with an HTTP request. * * @since 2.7.0 * @since 5.1.0 The `$url` parameter was added. * * @param string $user_agent WordPress user agent string. * @param string $url The request URL. */ 'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ), $url ), /** * Filters whether to pass URLs through wp_http_validate_url() in an HTTP request. * * @since 3.6.0 * @since 5.1.0 The `$url` parameter was added. * * @param bool $pass_url Whether to pass URLs through wp_http_validate_url(). Default false. * @param string $url The request URL. */ 'reject_unsafe_urls' => apply_filters( 'http_request_reject_unsafe_urls', false, $url ), 'blocking' => true, 'headers' => array(), 'cookies' => array(), 'body' => null, 'compress' => false, 'decompress' => true, 'sslverify' => true, 'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt', 'stream' => false, 'filename' => null, 'limit_response_size' => null, ); // Pre-parse for the HEAD checks. $args = wp_parse_args( $args ); // By default, HEAD requests do not cause redirections. if ( isset( $args['method'] ) && 'HEAD' === $args['method'] ) { $defaults['redirection'] = 0; } $parsed_args = wp_parse_args( $args, $defaults ); /** * Filters the arguments used in an HTTP request. * * @since 2.7.0 * * @param array $parsed_args An array of HTTP request arguments. * @param string $url The request URL. */ $parsed_args = apply_filters( 'http_request_args', $parsed_args, $url ); // The transports decrement this, store a copy of the original value for loop purposes. if ( ! isset( $parsed_args['_redirection'] ) ) { $parsed_args['_redirection'] = $parsed_args['redirection']; } /** * Filters the preemptive return value of an HTTP request. * * Returning a non-false value from the filter will short-circuit the HTTP request and return * early with that value. A filter should return one of: * * - An array containing 'headers', 'body', 'response', 'cookies', and 'filename' elements * - A WP_Error instance * - boolean false to avoid short-circuiting the response * * Returning any other value may result in unexpected behaviour. * * @since 2.9.0 * * @param false|array|WP_Error $preempt A preemptive return value of an HTTP request. Default false. * @param array $parsed_args HTTP request arguments. * @param string $url The request URL. */ $pre = apply_filters( 'pre_http_request', false, $parsed_args, $url ); if ( false !== $pre ) { return $pre; } if ( function_exists( 'wp_kses_bad_protocol' ) ) { if ( $parsed_args['reject_unsafe_urls'] ) { $url = wp_http_validate_url( $url ); } if ( $url ) { $url = wp_kses_bad_protocol( $url, array( 'http', 'https', 'ssl' ) ); } } $parsed_url = parse_url( $url ); if ( empty( $url ) || empty( $parsed_url['scheme'] ) ) { $response = new WP_Error( 'http_request_failed', __( 'A valid URL was not provided.' ) ); /** This action is documented in wp-includes/class-wp-http.php */ do_action( 'http_api_debug', $response, 'response', 'Requests', $parsed_args, $url ); return $response; } if ( $this->block_request( $url ) ) { $response = new WP_Error( 'http_request_not_executed', __( 'User has blocked requests through HTTP.' ) ); /** This action is documented in wp-includes/class-wp-http.php */ do_action( 'http_api_debug', $response, 'response', 'Requests', $parsed_args, $url ); return $response; } // If we are streaming to a file but no filename was given drop it in the WP temp dir // and pick its name using the basename of the $url. if ( $parsed_args['stream'] ) { if ( empty( $parsed_args['filename'] ) ) { $parsed_args['filename'] = get_temp_dir() . basename( $url ); } // Force some settings if we are streaming to a file and check for existence // and perms of destination directory. $parsed_args['blocking'] = true; if ( ! wp_is_writable( dirname( $parsed_args['filename'] ) ) ) { $response = new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) ); /** This action is documented in wp-includes/class-wp-http.php */ do_action( 'http_api_debug', $response, 'response', 'Requests', $parsed_args, $url ); return $response; } } if ( is_null( $parsed_args['headers'] ) ) { $parsed_args['headers'] = array(); } // WP allows passing in headers as a string, weirdly. if ( ! is_array( $parsed_args['headers'] ) ) { $processed_headers = WP_Http::processHeaders( $parsed_args['headers'] ); $parsed_args['headers'] = $processed_headers['headers']; } // Setup arguments. $headers = $parsed_args['headers']; $data = $parsed_args['body']; $type = $parsed_args['method']; $options = array( 'timeout' => $parsed_args['timeout'], 'useragent' => $parsed_args['user-agent'], 'blocking' => $parsed_args['blocking'], 'hooks' => new WP_HTTP_Requests_Hooks( $url, $parsed_args ), ); // Ensure redirects follow browser behaviour. $options['hooks']->register( 'requests.before_redirect', array( get_class(), 'browser_redirect_compatibility' ) ); // Validate redirected URLs. if ( function_exists( 'wp_kses_bad_protocol' ) && $parsed_args['reject_unsafe_urls'] ) { $options['hooks']->register( 'requests.before_redirect', array( get_class(), 'validate_redirects' ) ); } if ( $parsed_args['stream'] ) { $options['filename'] = $parsed_args['filename']; } if ( empty( $parsed_args['redirection'] ) ) { $options['follow_redirects'] = false; } else { $options['redirects'] = $parsed_args['redirection']; } // Use byte limit, if we can. if ( isset( $parsed_args['limit_response_size'] ) ) { $options['max_bytes'] = $parsed_args['limit_response_size']; } // If we've got cookies, use and convert them to Requests_Cookie. if ( ! empty( $parsed_args['cookies'] ) ) { $options['cookies'] = WP_Http::normalize_cookies( $parsed_args['cookies'] ); } // SSL certificate handling. if ( ! $parsed_args['sslverify'] ) { $options['verify'] = false; $options['verifyname'] = false; } else { $options['verify'] = $parsed_args['sslcertificates']; } // All non-GET/HEAD requests should put the arguments in the form body. if ( 'HEAD' !== $type && 'GET' !== $type ) { $options['data_format'] = 'body'; } /** * Filters whether SSL should be verified for non-local requests. * * @since 2.8.0 * @since 5.1.0 The `$url` parameter was added. * * @param bool $ssl_verify Whether to verify the SSL connection. Default true. * @param string $url The request URL. */ $options['verify'] = apply_filters( 'https_ssl_verify', $options['verify'], $url ); // Check for proxies. $proxy = new WP_HTTP_Proxy(); if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) { $options['proxy'] = new Requests_Proxy_HTTP( $proxy->host() . ':' . $proxy->port() ); if ( $proxy->use_authentication() ) { $options['proxy']->use_authentication = true; $options['proxy']->user = $proxy->username(); $options['proxy']->pass = $proxy->password(); } } // Avoid issues where mbstring.func_overload is enabled. mbstring_binary_safe_encoding(); try { $requests_response = Requests::request( $url, $headers, $data, $type, $options ); // Convert the response into an array. $http_response = new WP_HTTP_Requests_Response( $requests_response, $parsed_args['filename'] ); $response = $http_response->to_array(); // Add the original object to the array. $response['http_response'] = $http_response; } catch ( Requests_Exception $e ) { $response = new WP_Error( 'http_request_failed', $e->getMessage() ); } reset_mbstring_encoding(); /** * Fires after an HTTP API response is received and before the response is returned. * * @since 2.8.0 * * @param array|WP_Error $response HTTP response or WP_Error object. * @param string $context Context under which the hook is fired. * @param string $class HTTP transport used. * @param array $parsed_args HTTP request arguments. * @param string $url The request URL. */ do_action( 'http_api_debug', $response, 'response', 'Requests', $parsed_args, $url ); if ( is_wp_error( $response ) ) { return $response; } if ( ! $parsed_args['blocking'] ) { return array( 'headers' => array(), 'body' => '', 'response' => array( 'code' => false, 'message' => false, ), 'cookies' => array(), 'http_response' => null, ); } /** * Filters a successful HTTP API response immediately before the response is returned. * * @since 2.9.0 * * @param array $response HTTP response. * @param array $parsed_args HTTP request arguments. * @param string $url The request URL. */ return apply_filters( 'http_response', $response, $parsed_args, $url ); } /** * Normalizes cookies for using in Requests. * * @since 4.6.0 * * @param array $cookies Array of cookies to send with the request. * @return Requests_Cookie_Jar Cookie holder object. */ public static function normalize_cookies( $cookies ) { $cookie_jar = new Requests_Cookie_Jar(); foreach ( $cookies as $name => $value ) { if ( $value instanceof WP_Http_Cookie ) { $attributes = array_filter( $value->get_attributes(), static function( $attr ) { return null !== $attr; } ); $cookie_jar[ $value->name ] = new Requests_Cookie( $value->name, $value->value, $attributes, array( 'host-only' => $value->host_only ) ); } elseif ( is_scalar( $value ) ) { $cookie_jar[ $name ] = new Requests_Cookie( $name, $value ); } } return $cookie_jar; } /** * Match redirect behaviour to browser handling. * * Changes 302 redirects from POST to GET to match browser handling. Per * RFC 7231, user agents can deviate from the strict reading of the * specification for compatibility purposes. * * @since 4.6.0 * * @param string $location URL to redirect to. * @param array $headers Headers for the redirect. * @param string|array $data Body to send with the request. * @param array $options Redirect request options. * @param Requests_Response $original Response object. */ public static function browser_redirect_compatibility( $location, $headers, $data, &$options, $original ) { // Browser compatibility. if ( 302 === $original->status_code ) { $options['type'] = Requests::GET; } } /** * Validate redirected URLs. * * @since 4.7.5 * * @throws Requests_Exception On unsuccessful URL validation. * @param string $location URL to redirect to. */ public static function validate_redirects( $location ) { if ( ! wp_http_validate_url( $location ) ) { throw new Requests_Exception( __( 'A valid URL was not provided.' ), 'wp_http.redirect_failed_validation' ); } } /** * Tests which transports are capable of supporting the request. * * @since 3.2.0 * * @param array $args Request arguments. * @param string $url URL to request. * @return string|false Class name for the first transport that claims to support the request. * False if no transport claims to support the request. */ public function _get_first_available_transport( $args, $url = null ) { $transports = array( 'curl', 'streams' ); /** * Filters which HTTP transports are available and in what order. * * @since 3.7.0 * * @param string[] $transports Array of HTTP transports to check. Default array contains * 'curl' and 'streams', in that order. * @param array $args HTTP request arguments. * @param string $url The URL to request. */ $request_order = apply_filters( 'http_api_transports', $transports, $args, $url ); // Loop over each transport on each HTTP request looking for one which will serve this request's needs. foreach ( $request_order as $transport ) { if ( in_array( $transport, $transports, true ) ) { $transport = ucfirst( $transport ); } $class = 'WP_Http_' . $transport; // Check to see if this transport is a possibility, calls the transport statically. if ( ! call_user_func( array( $class, 'test' ), $args, $url ) ) { continue; } return $class; } return false; } /** * Dispatches a HTTP request to a supporting transport. * * Tests each transport in order to find a transport which matches the request arguments. * Also caches the transport instance to be used later. * * The order for requests is cURL, and then PHP Streams. * * @since 3.2.0 * @deprecated 5.1.0 Use WP_Http::request() * @see WP_Http::request() * * @param string $url URL to request. * @param array $args Request arguments. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. * A WP_Error instance upon error. */ private function _dispatch_request( $url, $args ) { static $transports = array(); $class = $this->_get_first_available_transport( $args, $url ); if ( ! $class ) { return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) ); } // Transport claims to support request, instantiate it and give it a whirl. if ( empty( $transports[ $class ] ) ) { $transports[ $class ] = new $class; } $response = $transports[ $class ]->request( $url, $args ); /** This action is documented in wp-includes/class-wp-http.php */ do_action( 'http_api_debug', $response, 'response', $class, $args, $url ); if ( is_wp_error( $response ) ) { return $response; } /** This filter is documented in wp-includes/class-wp-http.php */ return apply_filters( 'http_response', $response, $args, $url ); } /** * Uses the POST HTTP method. * * Used for sending data that is expected to be in the body. * * @since 2.7.0 * * @param string $url The request URL. * @param string|array $args Optional. Override the defaults. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. * A WP_Error instance upon error. */ public function post( $url, $args = array() ) { $defaults = array( 'method' => 'POST' ); $parsed_args = wp_parse_args( $args, $defaults ); return $this->request( $url, $parsed_args ); } /** * Uses the GET HTTP method. * * Used for sending data that is expected to be in the body. * * @since 2.7.0 * * @param string $url The request URL. * @param string|array $args Optional. Override the defaults. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. * A WP_Error instance upon error. */ public function get( $url, $args = array() ) { $defaults = array( 'method' => 'GET' ); $parsed_args = wp_parse_args( $args, $defaults ); return $this->request( $url, $parsed_args ); } /** * Uses the HEAD HTTP method. * * Used for sending data that is expected to be in the body. * * @since 2.7.0 * * @param string $url The request URL. * @param string|array $args Optional. Override the defaults. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. * A WP_Error instance upon error. */ public function head( $url, $args = array() ) { $defaults = array( 'method' => 'HEAD' ); $parsed_args = wp_parse_args( $args, $defaults ); return $this->request( $url, $parsed_args ); } /** * Parses the responses and splits the parts into headers and body. * * @since 2.7.0 * * @param string $response The full response string. * @return array { * Array with response headers and body. * * @type string $headers HTTP response headers. * @type string $body HTTP response body. * } */ public static function processResponse( $response ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid $response = explode( "\r\n\r\n", $response, 2 ); return array( 'headers' => $response[0], 'body' => isset( $response[1] ) ? $response[1] : '', ); } /** * Transforms header string into an array. * * @since 2.7.0 * * @param string|array $headers The original headers. If a string is passed, it will be converted * to an array. If an array is passed, then it is assumed to be * raw header data with numeric keys with the headers as the values. * No headers must be passed that were already processed. * @param string $url Optional. The URL that was requested. Default empty. * @return array { * Processed string headers. If duplicate headers are encountered, * then a numbered array is returned as the value of that header-key. * * @type array $response { * @type int $code The response status code. Default 0. * @type string $message The response message. Default empty. * } * @type array $newheaders The processed header data as a multidimensional array. * @type WP_Http_Cookie[] $cookies If the original headers contain the 'Set-Cookie' key, * an array containing `WP_Http_Cookie` objects is returned. * } */ public static function processHeaders( $headers, $url = '' ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid // Split headers, one per array element. if ( is_string( $headers ) ) { // Tolerate line terminator: CRLF = LF (RFC 2616 19.3). $headers = str_replace( "\r\n", "\n", $headers ); /* * Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>, * <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2). */ $headers = preg_replace( '/\n[ \t]/', ' ', $headers ); // Create the headers array. $headers = explode( "\n", $headers ); } $response = array( 'code' => 0, 'message' => '', ); /* * If a redirection has taken place, The headers for each page request may have been passed. * In this case, determine the final HTTP header and parse from there. */ for ( $i = count( $headers ) - 1; $i >= 0; $i-- ) { if ( ! empty( $headers[ $i ] ) && false === strpos( $headers[ $i ], ':' ) ) { $headers = array_splice( $headers, $i ); break; } } $cookies = array(); $newheaders = array(); foreach ( (array) $headers as $tempheader ) { if ( empty( $tempheader ) ) { continue; } if ( false === strpos( $tempheader, ':' ) ) { $stack = explode( ' ', $tempheader, 3 ); $stack[] = ''; list( , $response['code'], $response['message']) = $stack; continue; } list($key, $value) = explode( ':', $tempheader, 2 ); $key = strtolower( $key ); $value = trim( $value ); if ( isset( $newheaders[ $key ] ) ) { if ( ! is_array( $newheaders[ $key ] ) ) { $newheaders[ $key ] = array( $newheaders[ $key ] ); } $newheaders[ $key ][] = $value; } else { $newheaders[ $key ] = $value; } if ( 'set-cookie' === $key ) { $cookies[] = new WP_Http_Cookie( $value, $url ); } } // Cast the Response Code to an int. $response['code'] = (int) $response['code']; return array( 'response' => $response, 'headers' => $newheaders, 'cookies' => $cookies, ); } /** * Takes the arguments for a ::request() and checks for the cookie array. * * If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances, * which are each parsed into strings and added to the Cookie: header (within the arguments array). * Edits the array by reference. * * @since 2.8.0 * * @param array $r Full array of args passed into ::request() */ public static function buildCookieHeader( &$r ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid if ( ! empty( $r['cookies'] ) ) { // Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances. foreach ( $r['cookies'] as $name => $value ) { if ( ! is_object( $value ) ) { $r['cookies'][ $name ] = new WP_Http_Cookie( array( 'name' => $name, 'value' => $value, ) ); } } $cookies_header = ''; foreach ( (array) $r['cookies'] as $cookie ) { $cookies_header .= $cookie->getHeaderValue() . '; '; } $cookies_header = substr( $cookies_header, 0, -2 ); $r['headers']['cookie'] = $cookies_header; } } /** * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification. * * Based off the HTTP http_encoding_dechunk function. * * @link https://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding. * * @since 2.7.0 * * @param string $body Body content. * @return string Chunked decoded body on success or raw body on failure. */ public static function chunkTransferDecode( $body ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid // The body is not chunked encoded or is malformed. if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) ) { return $body; } $parsed_body = ''; // We'll be altering $body, so need a backup in case of error. $body_original = $body; while ( true ) { $has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match ); if ( ! $has_chunk || empty( $match[1] ) ) { return $body_original; } $length = hexdec( $match[1] ); $chunk_length = strlen( $match[0] ); // Parse out the chunk of data. $parsed_body .= substr( $body, $chunk_length, $length ); // Remove the chunk from the raw data. $body = substr( $body, $length + $chunk_length ); // End of the document. if ( '0' === trim( $body ) ) { return $parsed_body; } } } /** * Determines whether an HTTP API request to the given URL should be blocked. * * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will * prevent plugins from working and core functionality, if you don't include `api.wordpress.org`. * * You block external URL requests by defining `WP_HTTP_BLOCK_EXTERNAL` as true in your `wp-config.php` * file and this will only allow localhost and your site to make requests. The constant * `WP_ACCESSIBLE_HOSTS` will allow additional hosts to go through for requests. The format of the * `WP_ACCESSIBLE_HOSTS` constant is a comma separated list of hostnames to allow, wildcard domains * are supported, eg `*.wordpress.org` will allow for all subdomains of `wordpress.org` to be contacted. * * @since 2.8.0 * * @link https://core.trac.wordpress.org/ticket/8927 Allow preventing external requests. * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS * * @param string $uri URI of url. * @return bool True to block, false to allow. */ public function block_request( $uri ) { // We don't need to block requests, because nothing is blocked. if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL ) { return false; } $check = parse_url( $uri ); if ( ! $check ) { return true; } $home = parse_url( get_option( 'siteurl' ) ); // Don't block requests back to ourselves by default. if ( 'localhost' === $check['host'] || ( isset( $home['host'] ) && $home['host'] === $check['host'] ) ) { /** * Filters whether to block local HTTP API requests. * * A local request is one to `localhost` or to the same host as the site itself. * * @since 2.8.0 * * @param bool $block Whether to block local requests. Default false. */ return apply_filters( 'block_local_requests', false ); } if ( ! defined( 'WP_ACCESSIBLE_HOSTS' ) ) { return true; } static $accessible_hosts = null; static $wildcard_regex = array(); if ( null === $accessible_hosts ) { $accessible_hosts = preg_split( '|,\s*|', WP_ACCESSIBLE_HOSTS ); if ( false !== strpos( WP_ACCESSIBLE_HOSTS, '*' ) ) { $wildcard_regex = array(); foreach ( $accessible_hosts as $host ) { $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) ); } $wildcard_regex = '/^(' . implode( '|', $wildcard_regex ) . ')$/i'; } } if ( ! empty( $wildcard_regex ) ) { return ! preg_match( $wildcard_regex, $check['host'] ); } else { return ! in_array( $check['host'], $accessible_hosts, true ); // Inverse logic, if it's in the array, then don't block it. } } /** * Used as a wrapper for PHP's parse_url() function that handles edgecases in < PHP 5.4.7. * * @deprecated 4.4.0 Use wp_parse_url() * @see wp_parse_url() * * @param string $url The URL to parse. * @return bool|array False on failure; Array of URL components on success; * See parse_url()'s return values. */ protected static function parse_url( $url ) { _deprecated_function( __METHOD__, '4.4.0', 'wp_parse_url()' ); return wp_parse_url( $url ); } /** * Converts a relative URL to an absolute URL relative to a given URL. * * If an Absolute URL is provided, no processing of that URL is done. * * @since 3.4.0 * * @param string $maybe_relative_path The URL which might be relative. * @param string $url The URL which $maybe_relative_path is relative to. * @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned. */ public static function make_absolute_url( $maybe_relative_path, $url ) { if ( empty( $url ) ) { return $maybe_relative_path; } $url_parts = wp_parse_url( $url ); if ( ! $url_parts ) { return $maybe_relative_path; } $relative_url_parts = wp_parse_url( $maybe_relative_path ); if ( ! $relative_url_parts ) { return $maybe_relative_path; } // Check for a scheme on the 'relative' URL. if ( ! empty( $relative_url_parts['scheme'] ) ) { return $maybe_relative_path; } $absolute_path = $url_parts['scheme'] . '://'; // Schemeless URLs will make it this far, so we check for a host in the relative URL // and convert it to a protocol-URL. if ( isset( $relative_url_parts['host'] ) ) { $absolute_path .= $relative_url_parts['host']; if ( isset( $relative_url_parts['port'] ) ) { $absolute_path .= ':' . $relative_url_parts['port']; } } else { $absolute_path .= $url_parts['host']; if ( isset( $url_parts['port'] ) ) { $absolute_path .= ':' . $url_parts['port']; } } // Start off with the absolute URL path. $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/'; // If it's a root-relative path, then great. if ( ! empty( $relative_url_parts['path'] ) && '/' === $relative_url_parts['path'][0] ) { $path = $relative_url_parts['path']; // Else it's a relative path. } elseif ( ! empty( $relative_url_parts['path'] ) ) { // Strip off any file components from the absolute path. $path = substr( $path, 0, strrpos( $path, '/' ) + 1 ); // Build the new path. $path .= $relative_url_parts['path']; // Strip all /path/../ out of the path. while ( strpos( $path, '../' ) > 1 ) { $path = preg_replace( '![^/]+/\.\./!', '', $path ); } // Strip any final leading ../ from the path. $path = preg_replace( '!^/(\.\./)+!', '', $path ); } // Add the query string. if ( ! empty( $relative_url_parts['query'] ) ) { $path .= '?' . $relative_url_parts['query']; } return $absolute_path . '/' . ltrim( $path, '/' ); } /** * Handles an HTTP redirect and follows it if appropriate. * * @since 3.7.0 * * @param string $url The URL which was requested. * @param array $args The arguments which were used to make the request. * @param array $response The response of the HTTP request. * @return array|false|WP_Error An HTTP API response array if the redirect is successfully followed, * false if no redirect is present, or a WP_Error object if there's an error. */ public static function handle_redirects( $url, $args, $response ) { // If no redirects are present, or, redirects were not requested, perform no action. if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] ) { return false; } // Only perform redirections on redirection http codes. if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 ) { return false; } // Don't redirect if we've run out of redirects. if ( $args['redirection']-- <= 0 ) { return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) ); } $redirect_location = $response['headers']['location']; // If there were multiple Location headers, use the last header specified. if ( is_array( $redirect_location ) ) { $redirect_location = array_pop( $redirect_location ); } $redirect_location = WP_Http::make_absolute_url( $redirect_location, $url ); // POST requests should not POST to a redirected location. if ( 'POST' === $args['method'] ) { if ( in_array( $response['response']['code'], array( 302, 303 ), true ) ) { $args['method'] = 'GET'; } } // Include valid cookies in the redirect process. if ( ! empty( $response['cookies'] ) ) { foreach ( $response['cookies'] as $cookie ) { if ( $cookie->test( $redirect_location ) ) { $args['cookies'][] = $cookie; } } } return wp_remote_request( $redirect_location, $args ); } /** * Determines if a specified string represents an IP address or not. * * This function also detects the type of the IP address, returning either * '4' or '6' to represent a IPv4 and IPv6 address respectively. * This does not verify if the IP is a valid IP, only that it appears to be * an IP address. * * @link http://home.deds.nl/~aeron/regex/ for IPv6 regex. * * @since 3.7.0 * * @param string $maybe_ip A suspected IP address. * @return int|false Upon success, '4' or '6' to represent a IPv4 or IPv6 address, false upon failure */ public static function is_ip_address( $maybe_ip ) { if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) ) { return 4; } if ( false !== strpos( $maybe_ip, ':' ) && preg_match( '/^(((?=.*(::))(?!.*\3.+\3))\3?|([\dA-F]{1,4}(\3|:\b|$)|\2))(?4){5}((?4){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i', trim( $maybe_ip, ' []' ) ) ) { return 6; } return false; } } ```
programming_docs
wordpress class Walker_Comment {} class Walker\_Comment {} ======================== Core walker class used to create an HTML list of comments. * [Walker](walker) * [comment](walker_comment/comment) β€” Outputs a single comment. * [display\_element](walker_comment/display_element) β€” Traverses elements to create list from elements. * [end\_el](walker_comment/end_el) β€” Ends the element output, if needed. * [end\_lvl](walker_comment/end_lvl) β€” Ends the list of items after the elements are added. * [filter\_comment\_text](walker_comment/filter_comment_text) β€” Filters the comment text. * [html5\_comment](walker_comment/html5_comment) β€” Outputs a comment in the HTML5 format. * [ping](walker_comment/ping) β€” Outputs a pingback comment. * [start\_el](walker_comment/start_el) β€” Starts the element output. * [start\_lvl](walker_comment/start_lvl) β€” Starts the list before the elements are added. File: `wp-includes/class-walker-comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-comment.php/) ``` class Walker_Comment extends Walker { /** * What the class handles. * * @since 2.7.0 * @var string * * @see Walker::$tree_type */ public $tree_type = 'comment'; /** * Database fields to use. * * @since 2.7.0 * @var string[] * * @see Walker::$db_fields * @todo Decouple this */ public $db_fields = array( 'parent' => 'comment_parent', 'id' => 'comment_ID', ); /** * Starts the list before the elements are added. * * @since 2.7.0 * * @see Walker::start_lvl() * @global int $comment_depth * * @param string $output Used to append additional content (passed by reference). * @param int $depth Optional. Depth of the current comment. Default 0. * @param array $args Optional. Uses 'style' argument for type of HTML list. Default empty array. */ public function start_lvl( &$output, $depth = 0, $args = array() ) { $GLOBALS['comment_depth'] = $depth + 1; switch ( $args['style'] ) { case 'div': break; case 'ol': $output .= '<ol class="children">' . "\n"; break; case 'ul': default: $output .= '<ul class="children">' . "\n"; break; } } /** * Ends the list of items after the elements are added. * * @since 2.7.0 * * @see Walker::end_lvl() * @global int $comment_depth * * @param string $output Used to append additional content (passed by reference). * @param int $depth Optional. Depth of the current comment. Default 0. * @param array $args Optional. Will only append content if style argument value is 'ol' or 'ul'. * Default empty array. */ public function end_lvl( &$output, $depth = 0, $args = array() ) { $GLOBALS['comment_depth'] = $depth + 1; switch ( $args['style'] ) { case 'div': break; case 'ol': $output .= "</ol><!-- .children -->\n"; break; case 'ul': default: $output .= "</ul><!-- .children -->\n"; break; } } /** * Traverses elements to create list from elements. * * This function is designed to enhance Walker::display_element() to * display children of higher nesting levels than selected inline on * the highest depth level displayed. This prevents them being orphaned * at the end of the comment list. * * Example: max_depth = 2, with 5 levels of nested content. * 1 * 1.1 * 1.1.1 * 1.1.1.1 * 1.1.1.1.1 * 1.1.2 * 1.1.2.1 * 2 * 2.2 * * @since 2.7.0 * * @see Walker::display_element() * @see wp_list_comments() * * @param WP_Comment $element Comment data object. * @param array $children_elements List of elements to continue traversing. Passed by reference. * @param int $max_depth Max depth to traverse. * @param int $depth Depth of the current element. * @param array $args An array of arguments. * @param string $output Used to append additional content. Passed by reference. */ public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) { if ( ! $element ) { return; } $id_field = $this->db_fields['id']; $id = $element->$id_field; parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output ); /* * If at the max depth, and the current element still has children, loop over those * and display them at this level. This is to prevent them being orphaned to the end * of the list. */ if ( $max_depth <= $depth + 1 && isset( $children_elements[ $id ] ) ) { foreach ( $children_elements[ $id ] as $child ) { $this->display_element( $child, $children_elements, $max_depth, $depth, $args, $output ); } unset( $children_elements[ $id ] ); } } /** * Starts the element output. * * @since 2.7.0 * @since 5.9.0 Renamed `$comment` to `$data_object` and `$id` to `$current_object_id` * to match parent class for PHP 8 named parameter support. * * @see Walker::start_el() * @see wp_list_comments() * @global int $comment_depth * @global WP_Comment $comment Global comment object. * * @param string $output Used to append additional content. Passed by reference. * @param WP_Comment $data_object Comment data object. * @param int $depth Optional. Depth of the current comment in reference to parents. Default 0. * @param array $args Optional. An array of arguments. Default empty array. * @param int $current_object_id Optional. ID of the current comment. Default 0. */ 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. $comment = $data_object; $depth++; $GLOBALS['comment_depth'] = $depth; $GLOBALS['comment'] = $comment; if ( ! empty( $args['callback'] ) ) { ob_start(); call_user_func( $args['callback'], $comment, $args, $depth ); $output .= ob_get_clean(); return; } if ( 'comment' === $comment->comment_type ) { add_filter( 'comment_text', array( $this, 'filter_comment_text' ), 40, 2 ); } if ( ( 'pingback' === $comment->comment_type || 'trackback' === $comment->comment_type ) && $args['short_ping'] ) { ob_start(); $this->ping( $comment, $depth, $args ); $output .= ob_get_clean(); } elseif ( 'html5' === $args['format'] ) { ob_start(); $this->html5_comment( $comment, $depth, $args ); $output .= ob_get_clean(); } else { ob_start(); $this->comment( $comment, $depth, $args ); $output .= ob_get_clean(); } if ( 'comment' === $comment->comment_type ) { remove_filter( 'comment_text', array( $this, 'filter_comment_text' ), 40 ); } } /** * Ends the element output, if needed. * * @since 2.7.0 * @since 5.9.0 Renamed `$comment` to `$data_object` to match parent class for PHP 8 named parameter support. * * @see Walker::end_el() * @see wp_list_comments() * * @param string $output Used to append additional content. Passed by reference. * @param WP_Comment $data_object Comment data object. * @param int $depth Optional. Depth of the current comment. Default 0. * @param array $args Optional. An array of arguments. Default empty array. */ public function end_el( &$output, $data_object, $depth = 0, $args = array() ) { if ( ! empty( $args['end-callback'] ) ) { ob_start(); call_user_func( $args['end-callback'], $data_object, // The current comment object. $args, $depth ); $output .= ob_get_clean(); return; } if ( 'div' === $args['style'] ) { $output .= "</div><!-- #comment-## -->\n"; } else { $output .= "</li><!-- #comment-## -->\n"; } } /** * Outputs a pingback comment. * * @since 3.6.0 * * @see wp_list_comments() * * @param WP_Comment $comment The comment object. * @param int $depth Depth of the current comment. * @param array $args An array of arguments. */ protected function ping( $comment, $depth, $args ) { $tag = ( 'div' === $args['style'] ) ? 'div' : 'li'; ?> <<?php echo $tag; ?> id="comment-<?php comment_ID(); ?>" <?php comment_class( '', $comment ); ?>> <div class="comment-body"> <?php _e( 'Pingback:' ); ?> <?php comment_author_link( $comment ); ?> <?php edit_comment_link( __( 'Edit' ), '<span class="edit-link">', '</span>' ); ?> </div> <?php } /** * Filters the comment text. * * Removes links from the pending comment's text if the commenter did not consent * to the comment cookies. * * @since 5.4.2 * * @param string $comment_text Text of the current comment. * @param WP_Comment|null $comment The comment object. Null if not found. * @return string Filtered text of the current comment. */ public function filter_comment_text( $comment_text, $comment ) { $commenter = wp_get_current_commenter(); $show_pending_links = ! empty( $commenter['comment_author'] ); if ( $comment && '0' == $comment->comment_approved && ! $show_pending_links ) { $comment_text = wp_kses( $comment_text, array() ); } return $comment_text; } /** * Outputs a single comment. * * @since 3.6.0 * * @see wp_list_comments() * * @param WP_Comment $comment Comment to display. * @param int $depth Depth of the current comment. * @param array $args An array of arguments. */ protected function comment( $comment, $depth, $args ) { if ( 'div' === $args['style'] ) { $tag = 'div'; $add_below = 'comment'; } else { $tag = 'li'; $add_below = 'div-comment'; } $commenter = wp_get_current_commenter(); $show_pending_links = isset( $commenter['comment_author'] ) && $commenter['comment_author']; if ( $commenter['comment_author_email'] ) { $moderation_note = __( 'Your comment is awaiting moderation.' ); } else { $moderation_note = __( 'Your comment is awaiting moderation. This is a preview; your comment will be visible after it has been approved.' ); } ?> <<?php echo $tag; ?> <?php comment_class( $this->has_children ? 'parent' : '', $comment ); ?> id="comment-<?php comment_ID(); ?>"> <?php if ( 'div' !== $args['style'] ) : ?> <div id="div-comment-<?php comment_ID(); ?>" class="comment-body"> <?php endif; ?> <div class="comment-author vcard"> <?php if ( 0 != $args['avatar_size'] ) { echo get_avatar( $comment, $args['avatar_size'] ); } ?> <?php $comment_author = get_comment_author_link( $comment ); if ( '0' == $comment->comment_approved && ! $show_pending_links ) { $comment_author = get_comment_author( $comment ); } printf( /* translators: %s: Comment author link. */ __( '%s <span class="says">says:</span>' ), sprintf( '<cite class="fn">%s</cite>', $comment_author ) ); ?> </div> <?php if ( '0' == $comment->comment_approved ) : ?> <em class="comment-awaiting-moderation"><?php echo $moderation_note; ?></em> <br /> <?php endif; ?> <div class="comment-meta commentmetadata"> <?php printf( '<a href="%s">%s</a>', esc_url( get_comment_link( $comment, $args ) ), sprintf( /* translators: 1: Comment date, 2: Comment time. */ __( '%1$s at %2$s' ), get_comment_date( '', $comment ), get_comment_time() ) ); edit_comment_link( __( '(Edit)' ), ' &nbsp;&nbsp;', '' ); ?> </div> <?php comment_text( $comment, array_merge( $args, array( 'add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth'], ) ) ); ?> <?php comment_reply_link( array_merge( $args, array( 'add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth'], 'before' => '<div class="reply">', 'after' => '</div>', ) ) ); ?> <?php if ( 'div' !== $args['style'] ) : ?> </div> <?php endif; ?> <?php } /** * Outputs a comment in the HTML5 format. * * @since 3.6.0 * * @see wp_list_comments() * * @param WP_Comment $comment Comment to display. * @param int $depth Depth of the current comment. * @param array $args An array of arguments. */ protected function html5_comment( $comment, $depth, $args ) { $tag = ( 'div' === $args['style'] ) ? 'div' : 'li'; $commenter = wp_get_current_commenter(); $show_pending_links = ! empty( $commenter['comment_author'] ); if ( $commenter['comment_author_email'] ) { $moderation_note = __( 'Your comment is awaiting moderation.' ); } else { $moderation_note = __( 'Your comment is awaiting moderation. This is a preview; your comment will be visible after it has been approved.' ); } ?> <<?php echo $tag; ?> id="comment-<?php comment_ID(); ?>" <?php comment_class( $this->has_children ? 'parent' : '', $comment ); ?>> <article id="div-comment-<?php comment_ID(); ?>" class="comment-body"> <footer class="comment-meta"> <div class="comment-author vcard"> <?php if ( 0 != $args['avatar_size'] ) { echo get_avatar( $comment, $args['avatar_size'] ); } ?> <?php $comment_author = get_comment_author_link( $comment ); if ( '0' == $comment->comment_approved && ! $show_pending_links ) { $comment_author = get_comment_author( $comment ); } printf( /* translators: %s: Comment author link. */ __( '%s <span class="says">says:</span>' ), sprintf( '<b class="fn">%s</b>', $comment_author ) ); ?> </div><!-- .comment-author --> <div class="comment-metadata"> <?php printf( '<a href="%s"><time datetime="%s">%s</time></a>', esc_url( get_comment_link( $comment, $args ) ), get_comment_time( 'c' ), sprintf( /* translators: 1: Comment date, 2: Comment time. */ __( '%1$s at %2$s' ), get_comment_date( '', $comment ), get_comment_time() ) ); edit_comment_link( __( 'Edit' ), ' <span class="edit-link">', '</span>' ); ?> </div><!-- .comment-metadata --> <?php if ( '0' == $comment->comment_approved ) : ?> <em class="comment-awaiting-moderation"><?php echo $moderation_note; ?></em> <?php endif; ?> </footer><!-- .comment-meta --> <div class="comment-content"> <?php comment_text(); ?> </div><!-- .comment-content --> <?php if ( '1' == $comment->comment_approved || $show_pending_links ) { comment_reply_link( array_merge( $args, array( 'add_below' => 'div-comment', 'depth' => $depth, 'max_depth' => $args['max_depth'], 'before' => '<div class="reply">', 'after' => '</div>', ) ) ); } ?> </article><!-- .comment-body --> <?php } } ``` | Uses | Description | | --- | --- | | [Walker](walker) wp-includes/class-wp-walker.php | A class for displaying various tree-like structures. | | Version | Description | | --- | --- | | [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. | wordpress class WP_Privacy_Policy_Content {} class WP\_Privacy\_Policy\_Content {} ===================================== [WP\_Privacy\_Policy\_Content](wp_privacy_policy_content) class. * [\_\_construct](wp_privacy_policy_content/__construct) β€” Constructor * [\_policy\_page\_updated](wp_privacy_policy_content/_policy_page_updated) β€” Update the cached policy info when the policy page is updated. * [add](wp_privacy_policy_content/add) β€” Add content to the postbox shown when editing the privacy policy. * [add\_suggested\_content](wp_privacy_policy_content/add_suggested_content) β€” Add the suggested privacy policy text to the policy postbox. * [get\_default\_content](wp_privacy_policy_content/get_default_content) β€” Return the default suggested privacy policy content. * [get\_suggested\_policy\_text](wp_privacy_policy_content/get_suggested_policy_text) β€” Check for updated, added or removed privacy policy information from plugins. * [notice](wp_privacy_policy_content/notice) β€” Add a notice with a link to the guide when editing the privacy policy page. * [policy\_text\_changed\_notice](wp_privacy_policy_content/policy_text_changed_notice) β€” Output a warning when some privacy info has changed. * [privacy\_policy\_guide](wp_privacy_policy_content/privacy_policy_guide) β€” Output the privacy policy guide together with content from the theme and plugins. * [text\_change\_check](wp_privacy_policy_content/text_change_check) β€” Quick check if any privacy info has changed. File: `wp-admin/includes/class-wp-privacy-policy-content.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-privacy-policy-content.php/) ``` final class WP_Privacy_Policy_Content { private static $policy_content = array(); /** * Constructor * * @since 4.9.6 */ private function __construct() {} /** * Add content to the postbox shown when editing the privacy policy. * * Plugins and themes should suggest text for inclusion in the site's privacy policy. * The suggested text should contain information about any functionality that affects user privacy, * and will be shown in the Suggested Privacy Policy Content postbox. * * Intended for use from `wp_add_privacy_policy_content()`. * * @since 4.9.6 * * @param string $plugin_name The name of the plugin or theme that is suggesting content for the site's privacy policy. * @param string $policy_text The suggested content for inclusion in the policy. */ public static function add( $plugin_name, $policy_text ) { if ( empty( $plugin_name ) || empty( $policy_text ) ) { return; } $data = array( 'plugin_name' => $plugin_name, 'policy_text' => $policy_text, ); if ( ! in_array( $data, self::$policy_content, true ) ) { self::$policy_content[] = $data; } } /** * Quick check if any privacy info has changed. * * @since 4.9.6 */ public static function text_change_check() { $policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' ); // The site doesn't have a privacy policy. if ( empty( $policy_page_id ) ) { return false; } if ( ! current_user_can( 'edit_post', $policy_page_id ) ) { return false; } $old = (array) get_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' ); // Updates are not relevant if the user has not reviewed any suggestions yet. if ( empty( $old ) ) { return false; } $cached = get_option( '_wp_suggested_policy_text_has_changed' ); /* * When this function is called before `admin_init`, `self::$policy_content` * has not been populated yet, so use the cached result from the last * execution instead. */ if ( ! did_action( 'admin_init' ) ) { return 'changed' === $cached; } $new = self::$policy_content; // Remove the extra values added to the meta. foreach ( $old as $key => $data ) { if ( ! is_array( $data ) || ! empty( $data['removed'] ) ) { unset( $old[ $key ] ); continue; } $old[ $key ] = array( 'plugin_name' => $data['plugin_name'], 'policy_text' => $data['policy_text'], ); } // Normalize the order of texts, to facilitate comparison. sort( $old ); sort( $new ); // The == operator (equal, not identical) was used intentionally. // See http://php.net/manual/en/language.operators.array.php if ( $new != $old ) { // A plugin was activated or deactivated, or some policy text has changed. // Show a notice on the relevant screens to inform the admin. add_action( 'admin_notices', array( 'WP_Privacy_Policy_Content', 'policy_text_changed_notice' ) ); $state = 'changed'; } else { $state = 'not-changed'; } // Cache the result for use before `admin_init` (see above). if ( $cached !== $state ) { update_option( '_wp_suggested_policy_text_has_changed', $state ); } return 'changed' === $state; } /** * Output a warning when some privacy info has changed. * * @since 4.9.6 * * @global WP_Post $post Global post object. */ public static function policy_text_changed_notice() { global $post; $screen = get_current_screen()->id; if ( 'privacy' !== $screen ) { return; } ?> <div class="policy-text-updated notice notice-warning is-dismissible"> <p> <?php printf( /* translators: %s: Privacy Policy Guide URL. */ __( 'The suggested privacy policy text has changed. Please <a href="%s">review the guide</a> and update your privacy policy.' ), esc_url( admin_url( 'privacy-policy-guide.php?tab=policyguide' ) ) ); ?> </p> </div> <?php } /** * Update the cached policy info when the policy page is updated. * * @since 4.9.6 * @access private * * @param int $post_id The ID of the updated post. */ public static function _policy_page_updated( $post_id ) { $policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' ); if ( ! $policy_page_id || $policy_page_id !== (int) $post_id ) { return; } // Remove updated|removed status. $old = (array) get_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' ); $done = array(); $update_cache = false; foreach ( $old as $old_key => $old_data ) { if ( ! empty( $old_data['removed'] ) ) { // Remove the old policy text. $update_cache = true; continue; } if ( ! empty( $old_data['updated'] ) ) { // 'updated' is now 'added'. $done[] = array( 'plugin_name' => $old_data['plugin_name'], 'policy_text' => $old_data['policy_text'], 'added' => $old_data['updated'], ); $update_cache = true; } else { $done[] = $old_data; } } if ( $update_cache ) { delete_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' ); // Update the cache. foreach ( $done as $data ) { add_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content', $data ); } } } /** * Check for updated, added or removed privacy policy information from plugins. * * Caches the current info in post_meta of the policy page. * * @since 4.9.6 * * @return array The privacy policy text/information added by core and plugins. */ public static function get_suggested_policy_text() { $policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' ); $checked = array(); $time = time(); $update_cache = false; $new = self::$policy_content; $old = array(); if ( $policy_page_id ) { $old = (array) get_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' ); } // Check for no-changes and updates. foreach ( $new as $new_key => $new_data ) { foreach ( $old as $old_key => $old_data ) { $found = false; if ( $new_data['policy_text'] === $old_data['policy_text'] ) { // Use the new plugin name in case it was changed, translated, etc. if ( $old_data['plugin_name'] !== $new_data['plugin_name'] ) { $old_data['plugin_name'] = $new_data['plugin_name']; $update_cache = true; } // A plugin was re-activated. if ( ! empty( $old_data['removed'] ) ) { unset( $old_data['removed'] ); $old_data['added'] = $time; $update_cache = true; } $checked[] = $old_data; $found = true; } elseif ( $new_data['plugin_name'] === $old_data['plugin_name'] ) { // The info for the policy was updated. $checked[] = array( 'plugin_name' => $new_data['plugin_name'], 'policy_text' => $new_data['policy_text'], 'updated' => $time, ); $found = true; $update_cache = true; } if ( $found ) { unset( $new[ $new_key ], $old[ $old_key ] ); continue 2; } } } if ( ! empty( $new ) ) { // A plugin was activated. foreach ( $new as $new_data ) { if ( ! empty( $new_data['plugin_name'] ) && ! empty( $new_data['policy_text'] ) ) { $new_data['added'] = $time; $checked[] = $new_data; } } $update_cache = true; } if ( ! empty( $old ) ) { // A plugin was deactivated. foreach ( $old as $old_data ) { if ( ! empty( $old_data['plugin_name'] ) && ! empty( $old_data['policy_text'] ) ) { $data = array( 'plugin_name' => $old_data['plugin_name'], 'policy_text' => $old_data['policy_text'], 'removed' => $time, ); $checked[] = $data; } } $update_cache = true; } if ( $update_cache && $policy_page_id ) { delete_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' ); // Update the cache. foreach ( $checked as $data ) { add_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content', $data ); } } return $checked; } /** * Add a notice with a link to the guide when editing the privacy policy page. * * @since 4.9.6 * @since 5.0.0 The `$post` parameter was made optional. * * @global WP_Post $post Global post object. * * @param WP_Post|null $post The currently edited post. Default null. */ public static function notice( $post = null ) { if ( is_null( $post ) ) { global $post; } else { $post = get_post( $post ); } if ( ! ( $post instanceof WP_Post ) ) { return; } if ( ! current_user_can( 'manage_privacy_options' ) ) { return; } $current_screen = get_current_screen(); $policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' ); if ( 'post' !== $current_screen->base || $policy_page_id !== $post->ID ) { return; } $message = __( 'Need help putting together your new Privacy Policy page? Check out our guide for recommendations on what content to include, along with policies suggested by your plugins and theme.' ); $url = esc_url( admin_url( 'options-privacy.php?tab=policyguide' ) ); $label = __( 'View Privacy Policy Guide.' ); if ( get_current_screen()->is_block_editor() ) { wp_enqueue_script( 'wp-notices' ); $action = array( 'url' => $url, 'label' => $label, ); wp_add_inline_script( 'wp-notices', sprintf( 'wp.data.dispatch( "core/notices" ).createWarningNotice( "%s", { actions: [ %s ], isDismissible: false } )', $message, wp_json_encode( $action ) ), 'after' ); } else { ?> <div class="notice notice-warning inline wp-pp-notice"> <p> <?php echo $message; printf( ' <a href="%s" target="_blank">%s <span class="screen-reader-text">%s</span></a>', $url, $label, /* translators: Accessibility text. */ __( '(opens in a new tab)' ) ); ?> </p> </div> <?php } } /** * Output the privacy policy guide together with content from the theme and plugins. * * @since 4.9.6 */ public static function privacy_policy_guide() { $content_array = self::get_suggested_policy_text(); $content = ''; $date_format = __( 'F j, Y' ); foreach ( $content_array as $section ) { $class = ''; $meta = ''; $removed = ''; if ( ! empty( $section['removed'] ) ) { $badge_class = ' red'; $date = date_i18n( $date_format, $section['removed'] ); /* translators: %s: Date of plugin deactivation. */ $badge_title = sprintf( __( 'Removed %s.' ), $date ); /* translators: %s: Date of plugin deactivation. */ $removed = __( 'You deactivated this plugin on %s and may no longer need this policy.' ); $removed = '<div class="notice notice-info inline"><p>' . sprintf( $removed, $date ) . '</p></div>'; } elseif ( ! empty( $section['updated'] ) ) { $badge_class = ' blue'; $date = date_i18n( $date_format, $section['updated'] ); /* translators: %s: Date of privacy policy text update. */ $badge_title = sprintf( __( 'Updated %s.' ), $date ); } $plugin_name = esc_html( $section['plugin_name'] ); $sanitized_policy_name = sanitize_title_with_dashes( $plugin_name ); ?> <h4 class="privacy-settings-accordion-heading"> <button aria-expanded="false" class="privacy-settings-accordion-trigger" aria-controls="privacy-settings-accordion-block-<?php echo $sanitized_policy_name; ?>" type="button"> <span class="title"><?php echo $plugin_name; ?></span> <?php if ( ! empty( $section['removed'] ) || ! empty( $section['updated'] ) ) : ?> <span class="badge <?php echo $badge_class; ?>"> <?php echo $badge_title; ?></span> <?php endif; ?> <span class="icon"></span> </button> </h4> <div id="privacy-settings-accordion-block-<?php echo $sanitized_policy_name; ?>" class="privacy-settings-accordion-panel privacy-text-box-body" hidden="hidden"> <?php echo $removed; echo $section['policy_text']; ?> <?php if ( empty( $section['removed'] ) ) : ?> <div class="privacy-settings-accordion-actions"> <span class="success" aria-hidden="true"><?php _e( 'Copied!' ); ?></span> <button type="button" class="privacy-text-copy button"> <span aria-hidden="true"><?php _e( 'Copy suggested policy text to clipboard' ); ?></span> <span class="screen-reader-text"> <?php /* translators: %s: Plugin name. */ printf( __( 'Copy suggested policy text from %s.' ), $plugin_name ); ?> </span> </button> </div> <?php endif; ?> </div> <?php } } /** * Return the default suggested privacy policy content. * * @since 4.9.6 * @since 5.0.0 Added the `$blocks` parameter. * * @param bool $description Whether to include the descriptions under the section headings. Default false. * @param bool $blocks Whether to format the content for the block editor. Default true. * @return string The default policy content. */ public static function get_default_content( $description = false, $blocks = true ) { $suggested_text = '<strong class="privacy-policy-tutorial">' . __( 'Suggested text:' ) . ' </strong>'; $content = ''; $strings = array(); // Start of the suggested privacy policy text. if ( $description ) { $strings[] = '<div class="wp-suggested-text">'; } /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'Who we are' ) . '</h2>'; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should note your site URL, as well as the name of the company, organization, or individual behind it, and some accurate contact information.' ) . '</p>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'The amount of information you may be required to show will vary depending on your local or national business regulations. You may, for example, be required to display a physical address, a registered address, or your company registration number.' ) . '</p>'; } else { /* translators: Default privacy policy text. %s: Site URL. */ $strings[] = '<p>' . $suggested_text . sprintf( __( 'Our website address is: %s.' ), get_bloginfo( 'url', 'display' ) ) . '</p>'; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'What personal data we collect and why we collect it' ) . '</h2>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should note what personal data you collect from users and site visitors. This may include personal data, such as name, email address, personal account preferences; transactional data, such as purchase information; and technical data, such as information about cookies.' ) . '</p>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'You should also note any collection and retention of sensitive personal data, such as data concerning health.' ) . '</p>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'In addition to listing what personal data you collect, you need to note why you collect it. These explanations must note either the legal basis for your data collection and retention or the active consent the user has given.' ) . '</p>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'Personal data is not just created by a user&#8217;s interactions with your site. Personal data is also generated from technical processes such as contact forms, comments, cookies, analytics, and third party embeds.' ) . '</p>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'By default WordPress does not collect any personal data about visitors, and only collects the data shown on the User Profile screen from registered users. However some of your plugins may collect personal data. You should add the relevant information below.' ) . '</p>'; } /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'Comments' ) . '</h2>'; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this subsection you should note what information is captured through comments. We have noted the data which WordPress collects by default.' ) . '</p>'; } else { /* translators: Default privacy policy text. */ $strings[] = '<p>' . $suggested_text . __( 'When visitors leave comments on the site we collect the data shown in the comments form, and also the visitor&#8217;s IP address and browser user agent string to help spam detection.' ) . '</p>'; /* translators: Default privacy policy text. */ $strings[] = '<p>' . __( 'An anonymized string created from your email address (also called a hash) may be provided to the Gravatar service to see if you are using it. The Gravatar service privacy policy is available here: https://automattic.com/privacy/. After approval of your comment, your profile picture is visible to the public in the context of your comment.' ) . '</p>'; } /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'Media' ) . '</h2>'; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this subsection you should note what information may be disclosed by users who can upload media files. All uploaded files are usually publicly accessible.' ) . '</p>'; } else { /* translators: Default privacy policy text. */ $strings[] = '<p>' . $suggested_text . __( 'If you upload images to the website, you should avoid uploading images with embedded location data (EXIF GPS) included. Visitors to the website can download and extract any location data from images on the website.' ) . '</p>'; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'Contact forms' ) . '</h2>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'By default, WordPress does not include a contact form. If you use a contact form plugin, use this subsection to note what personal data is captured when someone submits a contact form, and how long you keep it. For example, you may note that you keep contact form submissions for a certain period for customer service purposes, but you do not use the information submitted through them for marketing purposes.' ) . '</p>'; } /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'Cookies' ) . '</h2>'; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this subsection you should list the cookies your web site uses, including those set by your plugins, social media, and analytics. We have provided the cookies which WordPress installs by default.' ) . '</p>'; } else { /* translators: Default privacy policy text. */ $strings[] = '<p>' . $suggested_text . __( 'If you leave a comment on our site you may opt-in to saving your name, email address and website in cookies. These are for your convenience so that you do not have to fill in your details again when you leave another comment. These cookies will last for one year.' ) . '</p>'; /* translators: Default privacy policy text. */ $strings[] = '<p>' . __( 'If you visit our login page, we will set a temporary cookie to determine if your browser accepts cookies. This cookie contains no personal data and is discarded when you close your browser.' ) . '</p>'; /* translators: Default privacy policy text. */ $strings[] = '<p>' . __( 'When you log in, we will also set up several cookies to save your login information and your screen display choices. Login cookies last for two days, and screen options cookies last for a year. If you select &quot;Remember Me&quot;, your login will persist for two weeks. If you log out of your account, the login cookies will be removed.' ) . '</p>'; /* translators: Default privacy policy text. */ $strings[] = '<p>' . __( 'If you edit or publish an article, an additional cookie will be saved in your browser. This cookie includes no personal data and simply indicates the post ID of the article you just edited. It expires after 1 day.' ) . '</p>'; } if ( ! $description ) { /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'Embedded content from other websites' ) . '</h2>'; /* translators: Default privacy policy text. */ $strings[] = '<p>' . $suggested_text . __( 'Articles on this site may include embedded content (e.g. videos, images, articles, etc.). Embedded content from other websites behaves in the exact same way as if the visitor has visited the other website.' ) . '</p>'; /* translators: Default privacy policy text. */ $strings[] = '<p>' . __( 'These websites may collect data about you, use cookies, embed additional third-party tracking, and monitor your interaction with that embedded content, including tracking your interaction with the embedded content if you have an account and are logged in to that website.' ) . '</p>'; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'Analytics' ) . '</h2>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this subsection you should note what analytics package you use, how users can opt out of analytics tracking, and a link to your analytics provider&#8217;s privacy policy, if any.' ) . '</p>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'By default WordPress does not collect any analytics data. However, many web hosting accounts collect some anonymous analytics data. You may also have installed a WordPress plugin that provides analytics services. In that case, add information from that plugin here.' ) . '</p>'; } /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'Who we share your data with' ) . '</h2>'; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should name and list all third party providers with whom you share site data, including partners, cloud-based services, payment processors, and third party service providers, and note what data you share with them and why. Link to their own privacy policies if possible.' ) . '</p>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'By default WordPress does not share any personal data with anyone.' ) . '</p>'; } else { /* translators: Default privacy policy text. */ $strings[] = '<p>' . $suggested_text . __( 'If you request a password reset, your IP address will be included in the reset email.' ) . '</p>'; } /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'How long we retain your data' ) . '</h2>'; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should explain how long you retain personal data collected or processed by the web site. While it is your responsibility to come up with the schedule of how long you keep each dataset for and why you keep it, that information does need to be listed here. For example, you may want to say that you keep contact form entries for six months, analytics records for a year, and customer purchase records for ten years.' ) . '</p>'; } else { /* translators: Default privacy policy text. */ $strings[] = '<p>' . $suggested_text . __( 'If you leave a comment, the comment and its metadata are retained indefinitely. This is so we can recognize and approve any follow-up comments automatically instead of holding them in a moderation queue.' ) . '</p>'; /* translators: Default privacy policy text. */ $strings[] = '<p>' . __( 'For users that register on our website (if any), we also store the personal information they provide in their user profile. All users can see, edit, or delete their personal information at any time (except they cannot change their username). Website administrators can also see and edit that information.' ) . '</p>'; } /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'What rights you have over your data' ) . '</h2>'; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should explain what rights your users have over their data and how they can invoke those rights.' ) . '</p>'; } else { /* translators: Default privacy policy text. */ $strings[] = '<p>' . $suggested_text . __( 'If you have an account on this site, or have left comments, you can request to receive an exported file of the personal data we hold about you, including any data you have provided to us. You can also request that we erase any personal data we hold about you. This does not include any data we are obliged to keep for administrative, legal, or security purposes.' ) . '</p>'; } /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'Where your data is sent' ) . '</h2>'; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should list all transfers of your site data outside the European Union and describe the means by which that data is safeguarded to European data protection standards. This could include your web hosting, cloud storage, or other third party services.' ) . '</p>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'European data protection law requires data about European residents which is transferred outside the European Union to be safeguarded to the same standards as if the data was in Europe. So in addition to listing where data goes, you should describe how you ensure that these standards are met either by yourself or by your third party providers, whether that is through an agreement such as Privacy Shield, model clauses in your contracts, or binding corporate rules.' ) . '</p>'; } else { /* translators: Default privacy policy text. */ $strings[] = '<p>' . $suggested_text . __( 'Visitor comments may be checked through an automated spam detection service.' ) . '</p>'; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'Contact information' ) . '</h2>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should provide a contact method for privacy-specific concerns. If you are required to have a Data Protection Officer, list their name and full contact details here as well.' ) . '</p>'; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'Additional information' ) . '</h2>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'If you use your site for commercial purposes and you engage in more complex collection or processing of personal data, you should note the following information in your privacy policy in addition to the information we have already discussed.' ) . '</p>'; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'How we protect your data' ) . '</h2>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should explain what measures you have taken to protect your users&#8217; data. This could include technical measures such as encryption; security measures such as two factor authentication; and measures such as staff training in data protection. If you have carried out a Privacy Impact Assessment, you can mention it here too.' ) . '</p>'; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'What data breach procedures we have in place' ) . '</h2>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should explain what procedures you have in place to deal with data breaches, either potential or real, such as internal reporting systems, contact mechanisms, or bug bounties.' ) . '</p>'; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'What third parties we receive data from' ) . '</h2>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'If your web site receives data about users from third parties, including advertisers, this information must be included within the section of your privacy policy dealing with third party data.' ) . '</p>'; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'What automated decision making and/or profiling we do with user data' ) . '</h2>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'If your web site provides a service which includes automated decision making - for example, allowing customers to apply for credit, or aggregating their data into an advertising profile - you must note that this is taking place, and include information about how that information is used, what decisions are made with that aggregated data, and what rights users have over decisions made without human intervention.' ) . '</p>'; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '<h2>' . __( 'Industry regulatory disclosure requirements' ) . '</h2>'; /* translators: Privacy policy tutorial. */ $strings[] = '<p class="privacy-policy-tutorial">' . __( 'If you are a member of a regulated industry, or if you are subject to additional privacy laws, you may be required to disclose that information here.' ) . '</p>'; $strings[] = '</div>'; } if ( $blocks ) { foreach ( $strings as $key => $string ) { if ( 0 === strpos( $string, '<p>' ) ) { $strings[ $key ] = '<!-- wp:paragraph -->' . $string . '<!-- /wp:paragraph -->'; } if ( 0 === strpos( $string, '<h2>' ) ) { $strings[ $key ] = '<!-- wp:heading -->' . $string . '<!-- /wp:heading -->'; } } } $content = implode( '', $strings ); // End of the suggested privacy policy text. /** * Filters the default content suggested for inclusion in a privacy policy. * * @since 4.9.6 * @since 5.0.0 Added the `$strings`, `$description`, and `$blocks` parameters. * @deprecated 5.7.0 Use wp_add_privacy_policy_content() instead. * * @param string $content The default policy content. * @param string[] $strings An array of privacy policy content strings. * @param bool $description Whether policy descriptions should be included. * @param bool $blocks Whether the content should be formatted for the block editor. */ return apply_filters_deprecated( 'wp_get_default_privacy_policy_content', array( $content, $strings, $description, $blocks ), '5.7.0', 'wp_add_privacy_policy_content()' ); } /** * Add the suggested privacy policy text to the policy postbox. * * @since 4.9.6 */ public static function add_suggested_content() { $content = self::get_default_content( false, false ); wp_add_privacy_policy_content( __( 'WordPress' ), $content ); } } ``` | Version | Description | | --- | --- | | [4.9.6](https://developer.wordpress.org/reference/since/4.9.6/) | Introduced. |
programming_docs
wordpress class WP_Customize_Color_Control {} class WP\_Customize\_Color\_Control {} ====================================== Customize Color Control class. * [WP\_Customize\_Control](wp_customize_control) * [\_\_construct](wp_customize_color_control/__construct) β€” Constructor. * [content\_template](wp_customize_color_control/content_template) β€” Render a JS template for the content of the color picker control. * [enqueue](wp_customize_color_control/enqueue) β€” Enqueue scripts/styles for the color picker. * [render\_content](wp_customize_color_control/render_content) β€” Don't render the control content from PHP, as it's rendered via JS on load. * [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/) ``` class WP_Customize_Color_Control extends WP_Customize_Control { /** * Type. * * @var string */ public $type = 'color'; /** * Statuses. * * @var array */ public $statuses; /** * Mode. * * @since 4.7.0 * @var string */ public $mode = 'full'; /** * Constructor. * * @since 3.4.0 * * @see WP_Customize_Control::__construct() * * @param WP_Customize_Manager $manager Customizer bootstrap instance. * @param string $id Control ID. * @param array $args Optional. Arguments to override class property defaults. * See WP_Customize_Control::__construct() for information * on accepted arguments. Default empty array. */ public function __construct( $manager, $id, $args = array() ) { $this->statuses = array( '' => __( 'Default' ) ); parent::__construct( $manager, $id, $args ); } /** * Enqueue scripts/styles for the color picker. * * @since 3.4.0 */ public function enqueue() { wp_enqueue_script( 'wp-color-picker' ); wp_enqueue_style( 'wp-color-picker' ); } /** * Refresh the parameters passed to the JavaScript via JSON. * * @since 3.4.0 * @uses WP_Customize_Control::to_json() */ public function to_json() { parent::to_json(); $this->json['statuses'] = $this->statuses; $this->json['defaultValue'] = $this->setting->default; $this->json['mode'] = $this->mode; } /** * Don't render the control content from PHP, as it's rendered via JS on load. * * @since 3.4.0 */ public function render_content() {} /** * Render a JS template for the content of the color picker control. * * @since 4.1.0 */ 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 } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Control](wp_customize_control) wp-includes/class-wp-customize-control.php | Customize Control class. | | Version | Description | | --- | --- | | [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. | wordpress class Requests_Hooks {} class Requests\_Hooks {} ======================== Handles adding and dispatching events * [\_\_construct](requests_hooks/__construct) β€” Constructor * [dispatch](requests_hooks/dispatch) β€” Dispatch a message * [register](requests_hooks/register) β€” Register a callback for a hook File: `wp-includes/Requests/Hooks.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/hooks.php/) ``` class Requests_Hooks implements Requests_Hooker { /** * Registered callbacks for each hook * * @var array */ protected $hooks = array(); /** * Constructor */ public function __construct() { // pass } /** * Register a callback for a hook * * @param string $hook Hook name * @param callback $callback Function/method to call on event * @param int $priority Priority number. <0 is executed earlier, >0 is executed later */ public function register($hook, $callback, $priority = 0) { if (!isset($this->hooks[$hook])) { $this->hooks[$hook] = array(); } if (!isset($this->hooks[$hook][$priority])) { $this->hooks[$hook][$priority] = array(); } $this->hooks[$hook][$priority][] = $callback; } /** * Dispatch a message * * @param string $hook Hook name * @param array $parameters Parameters to pass to callbacks * @return boolean Successfulness */ public function dispatch($hook, $parameters = array()) { if (empty($this->hooks[$hook])) { return false; } foreach ($this->hooks[$hook] as $priority => $hooked) { foreach ($hooked as $callback) { call_user_func_array($callback, $parameters); } } return true; } } ``` | Used By | Description | | --- | --- | | [WP\_HTTP\_Requests\_Hooks](wp_http_requests_hooks) wp-includes/class-wp-http-requests-hooks.php | Bridge to connect Requests internal hooks to WordPress actions. | wordpress class Requests_Exception_HTTP_428 {} class Requests\_Exception\_HTTP\_428 {} ======================================= Exception for 428 Precondition Required responses * <https://tools.ietf.org/html/rfc6585> File: `wp-includes/Requests/Exception/HTTP/428.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/428.php/) ``` class Requests_Exception_HTTP_428 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 428; /** * Reason phrase * * @var string */ protected $reason = 'Precondition Required'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_Site_Health {} class WP\_Site\_Health {} ========================= Class for looking up a site’s health based on a user’s WordPress environment. * [\_\_construct](wp_site_health/__construct) β€” WP\_Site\_Health constructor. * [admin\_body\_class](wp_site_health/admin_body_class) β€” Adds a class to the body HTML tag. * [available\_object\_cache\_services](wp_site_health/available_object_cache_services) β€” Returns a list of available persistent object cache services. * [can\_perform\_loopback](wp_site_health/can_perform_loopback) β€” Runs a loopback test on the site. * [check\_for\_page\_caching](wp_site_health/check_for_page_caching) β€” Checks if site has page cache enabled or not. * [check\_wp\_version\_check\_exists](wp_site_health/check_wp_version_check_exists) β€” Tests whether `wp\_version\_check` is blocked. * [detect\_plugin\_theme\_auto\_update\_issues](wp_site_health/detect_plugin_theme_auto_update_issues) β€” Checks for potential issues with plugin and theme auto-updates. * [enqueue\_scripts](wp_site_health/enqueue_scripts) β€” Enqueues the site health scripts. * [get\_cron\_tasks](wp_site_health/get_cron_tasks) β€” Populates the list of cron events and store them to a class-wide variable. * [get\_good\_response\_time\_threshold](wp_site_health/get_good_response_time_threshold) β€” Gets the threshold below which a response time is considered good. * [get\_instance](wp_site_health/get_instance) β€” Returns an instance of the WP\_Site\_Health class, or create one if none exist yet. * [get\_page\_cache\_detail](wp_site_health/get_page_cache_detail) β€” Gets page cache details. * [get\_page\_cache\_headers](wp_site_health/get_page_cache_headers) β€” Returns a list of headers and its verification callback to verify if page cache is enabled or not. * [get\_test\_authorization\_header](wp_site_health/get_test_authorization_header) β€” Tests if the Authorization header has the expected values. * [get\_test\_background\_updates](wp_site_health/get_test_background_updates) β€” Tests if WordPress can run automated background updates. * [get\_test\_dotorg\_communication](wp_site_health/get_test_dotorg_communication) β€” Tests if the site can communicate with WordPress.org. * [get\_test\_file\_uploads](wp_site_health/get_test_file_uploads) β€” Tests if 'file\_uploads' directive in PHP.ini is turned off. * [get\_test\_http\_requests](wp_site_health/get_test_http_requests) β€” Tests if HTTP requests are blocked. * [get\_test\_https\_status](wp_site_health/get_test_https_status) β€” Tests if the site is serving content over HTTPS. * [get\_test\_is\_in\_debug\_mode](wp_site_health/get_test_is_in_debug_mode) β€” Tests if debug information is enabled. * [get\_test\_loopback\_requests](wp_site_health/get_test_loopback_requests) β€” Tests if loopbacks work as expected. * [get\_test\_page\_cache](wp_site_health/get_test_page_cache) β€” Tests if a full page cache is available. * [get\_test\_persistent\_object\_cache](wp_site_health/get_test_persistent_object_cache) β€” Tests if the site uses persistent object cache and recommends to use it if not. * [get\_test\_php\_default\_timezone](wp_site_health/get_test_php_default_timezone) β€” Tests if the PHP default timezone is set to UTC. * [get\_test\_php\_extensions](wp_site_health/get_test_php_extensions) β€” Tests if required PHP modules are installed on the host. * [get\_test\_php\_sessions](wp_site_health/get_test_php_sessions) β€” Tests if there's an active PHP session that can affect loopback requests. * [get\_test\_php\_version](wp_site_health/get_test_php_version) β€” Tests if the supplied PHP version is supported. * [get\_test\_plugin\_theme\_auto\_updates](wp_site_health/get_test_plugin_theme_auto_updates) β€” Tests if plugin and theme auto-updates appear to be configured correctly. * [get\_test\_plugin\_version](wp_site_health/get_test_plugin_version) β€” Tests if plugins are outdated, or unnecessary. * [get\_test\_rest\_availability](wp_site_health/get_test_rest_availability) β€” Tests if the REST API is accessible. * [get\_test\_scheduled\_events](wp_site_health/get_test_scheduled_events) β€” Tests if scheduled events run as intended. * [get\_test\_sql\_server](wp_site_health/get_test_sql_server) β€” Tests if the SQL server is up to date. * [get\_test\_ssl\_support](wp_site_health/get_test_ssl_support) β€” Checks if the HTTP API can handle SSL/TLS requests. * [get\_test\_theme\_version](wp_site_health/get_test_theme_version) β€” Tests if themes are outdated, or unnecessary. * [get\_test\_utf8mb4\_support](wp_site_health/get_test_utf8mb4_support) β€” Tests if the database server is capable of using utf8mb4. * [get\_test\_wordpress\_version](wp_site_health/get_test_wordpress_version) β€” Tests for WordPress version and outputs it. * [get\_tests](wp_site_health/get_tests) β€” Returns a set of tests that belong to the site status page. * [has\_late\_cron](wp_site_health/has_late_cron) β€” Checks if any scheduled tasks are late. * [has\_missed\_cron](wp_site_health/has_missed_cron) β€” Checks if any scheduled tasks have been missed. * [is\_development\_environment](wp_site_health/is_development_environment) β€” Checks if the current environment type is set to 'development' or 'local'. * [maybe\_create\_scheduled\_event](wp_site_health/maybe_create_scheduled_event) β€” Creates a weekly cron event, if one does not already exist. * [perform\_test](wp_site_health/perform_test) β€” Runs a Site Health test directly. * [prepare\_sql\_data](wp_site_health/prepare_sql_data) β€” Runs the SQL version checks. * [should\_suggest\_persistent\_object\_cache](wp_site_health/should_suggest_persistent_object_cache) β€” Determines whether to suggest using a persistent object cache. * [show\_site\_health\_tab](wp_site_health/show_site_health_tab) β€” Outputs the content of a tab in the Site Health screen. * [test\_php\_extension\_availability](wp_site_health/test_php_extension_availability) β€” Checks if the passed extension or function are available. * [wp\_cron\_scheduled\_check](wp_site_health/wp_cron_scheduled_check) β€” Runs the scheduled event to check and update the latest site health status for the website. * [wp\_schedule\_test\_init](wp_site_health/wp_schedule_test_init) β€” Initiates the WP\_Cron schedule test cases. File: `wp-admin/includes/class-wp-site-health.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-site-health.php/) ``` class WP_Site_Health { private static $instance = null; private $is_acceptable_mysql_version; private $is_recommended_mysql_version; public $is_mariadb = false; private $mysql_server_version = ''; private $mysql_required_version = '5.5'; private $mysql_recommended_version = '5.7'; private $mariadb_recommended_version = '10.3'; public $php_memory_limit; public $schedules; public $crons; public $last_missed_cron = null; public $last_late_cron = null; private $timeout_missed_cron = null; private $timeout_late_cron = null; /** * WP_Site_Health constructor. * * @since 5.2.0 */ public function __construct() { $this->maybe_create_scheduled_event(); // Save memory limit before it's affected by wp_raise_memory_limit( 'admin' ). $this->php_memory_limit = ini_get( 'memory_limit' ); $this->timeout_late_cron = 0; $this->timeout_missed_cron = - 5 * MINUTE_IN_SECONDS; if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) { $this->timeout_late_cron = - 15 * MINUTE_IN_SECONDS; $this->timeout_missed_cron = - 1 * HOUR_IN_SECONDS; } add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); add_action( 'wp_site_health_scheduled_check', array( $this, 'wp_cron_scheduled_check' ) ); add_action( 'site_health_tab_content', array( $this, 'show_site_health_tab' ) ); } /** * Outputs the content of a tab in the Site Health screen. * * @since 5.8.0 * * @param string $tab Slug of the current tab being displayed. */ public function show_site_health_tab( $tab ) { if ( 'debug' === $tab ) { require_once ABSPATH . '/wp-admin/site-health-info.php'; } } /** * Returns an instance of the WP_Site_Health class, or create one if none exist yet. * * @since 5.4.0 * * @return WP_Site_Health|null */ public static function get_instance() { if ( null === self::$instance ) { self::$instance = new WP_Site_Health(); } return self::$instance; } /** * Enqueues the site health scripts. * * @since 5.2.0 */ public function enqueue_scripts() { $screen = get_current_screen(); if ( 'site-health' !== $screen->id && 'dashboard' !== $screen->id ) { return; } $health_check_js_variables = array( 'screen' => $screen->id, 'nonce' => array( 'site_status' => wp_create_nonce( 'health-check-site-status' ), 'site_status_result' => wp_create_nonce( 'health-check-site-status-result' ), ), 'site_status' => array( 'direct' => array(), 'async' => array(), 'issues' => array( 'good' => 0, 'recommended' => 0, 'critical' => 0, ), ), ); $issue_counts = get_transient( 'health-check-site-status-result' ); if ( false !== $issue_counts ) { $issue_counts = json_decode( $issue_counts ); $health_check_js_variables['site_status']['issues'] = $issue_counts; } if ( 'site-health' === $screen->id && ( ! isset( $_GET['tab'] ) || empty( $_GET['tab'] ) ) ) { $tests = WP_Site_Health::get_tests(); // Don't run https test on development environments. if ( $this->is_development_environment() ) { unset( $tests['async']['https_status'] ); } foreach ( $tests['direct'] as $test ) { if ( is_string( $test['test'] ) ) { $test_function = sprintf( 'get_test_%s', $test['test'] ); if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) { $health_check_js_variables['site_status']['direct'][] = $this->perform_test( array( $this, $test_function ) ); continue; } } if ( is_callable( $test['test'] ) ) { $health_check_js_variables['site_status']['direct'][] = $this->perform_test( $test['test'] ); } } foreach ( $tests['async'] as $test ) { if ( is_string( $test['test'] ) ) { $health_check_js_variables['site_status']['async'][] = array( 'test' => $test['test'], 'has_rest' => ( isset( $test['has_rest'] ) ? $test['has_rest'] : false ), 'completed' => false, 'headers' => isset( $test['headers'] ) ? $test['headers'] : array(), ); } } } wp_localize_script( 'site-health', 'SiteHealth', $health_check_js_variables ); } /** * Runs a Site Health test directly. * * @since 5.4.0 * * @param callable $callback * @return mixed|void */ private function perform_test( $callback ) { /** * Filters the output of a finished Site Health test. * * @since 5.3.0 * * @param array $test_result { * An associative array of test result data. * * @type string $label A label describing the test, and is used as a header in the output. * @type string $status The status of the test, which can be a value of `good`, `recommended` or `critical`. * @type array $badge { * Tests are put into categories which have an associated badge shown, these can be modified and assigned here. * * @type string $label The test label, for example `Performance`. * @type string $color Default `blue`. A string representing a color to use for the label. * } * @type string $description A more descriptive explanation of what the test looks for, and why it is important for the end user. * @type string $actions An action to direct the user to where they can resolve the issue, if one exists. * @type string $test The name of the test being ran, used as a reference point. * } */ return apply_filters( 'site_status_test_result', call_user_func( $callback ) ); } /** * Runs the SQL version checks. * * These values are used in later tests, but the part of preparing them is more easily managed * early in the class for ease of access and discovery. * * @since 5.2.0 * * @global wpdb $wpdb WordPress database abstraction object. */ private function prepare_sql_data() { global $wpdb; $mysql_server_type = $wpdb->db_server_info(); $this->mysql_server_version = $wpdb->get_var( 'SELECT VERSION()' ); if ( stristr( $mysql_server_type, 'mariadb' ) ) { $this->is_mariadb = true; $this->mysql_recommended_version = $this->mariadb_recommended_version; } $this->is_acceptable_mysql_version = version_compare( $this->mysql_required_version, $this->mysql_server_version, '<=' ); $this->is_recommended_mysql_version = version_compare( $this->mysql_recommended_version, $this->mysql_server_version, '<=' ); } /** * Tests whether `wp_version_check` is blocked. * * It's possible to block updates with the `wp_version_check` filter, but this can't be checked * during an Ajax call, as the filter is never introduced then. * * This filter overrides a standard page request if it's made by an admin through the Ajax call * with the right query argument to check for this. * * @since 5.2.0 */ public function check_wp_version_check_exists() { if ( ! is_admin() || ! is_user_logged_in() || ! current_user_can( 'update_core' ) || ! isset( $_GET['health-check-test-wp_version_check'] ) ) { return; } echo ( has_filter( 'wp_version_check', 'wp_version_check' ) ? 'yes' : 'no' ); die(); } /** * Tests for WordPress version and outputs it. * * Gives various results depending on what kind of updates are available, if any, to encourage * the user to install security updates as a priority. * * @since 5.2.0 * * @return array The test result. */ public function get_test_wordpress_version() { $result = array( 'label' => '', 'status' => '', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => '', 'actions' => '', 'test' => 'wordpress_version', ); $core_current_version = get_bloginfo( 'version' ); $core_updates = get_core_updates(); if ( ! is_array( $core_updates ) ) { $result['status'] = 'recommended'; $result['label'] = sprintf( /* translators: %s: Your current version of WordPress. */ __( 'WordPress version %s' ), $core_current_version ); $result['description'] = sprintf( '<p>%s</p>', __( 'Unable to check if any new versions of WordPress are available.' ) ); $result['actions'] = sprintf( '<a href="%s">%s</a>', esc_url( admin_url( 'update-core.php?force-check=1' ) ), __( 'Check for updates manually' ) ); } else { foreach ( $core_updates as $core => $update ) { if ( 'upgrade' === $update->response ) { $current_version = explode( '.', $core_current_version ); $new_version = explode( '.', $update->version ); $current_major = $current_version[0] . '.' . $current_version[1]; $new_major = $new_version[0] . '.' . $new_version[1]; $result['label'] = sprintf( /* translators: %s: The latest version of WordPress available. */ __( 'WordPress update available (%s)' ), $update->version ); $result['actions'] = sprintf( '<a href="%s">%s</a>', esc_url( admin_url( 'update-core.php' ) ), __( 'Install the latest version of WordPress' ) ); if ( $current_major !== $new_major ) { // This is a major version mismatch. $result['status'] = 'recommended'; $result['description'] = sprintf( '<p>%s</p>', __( 'A new version of WordPress is available.' ) ); } else { // This is a minor version, sometimes considered more critical. $result['status'] = 'critical'; $result['badge']['label'] = __( 'Security' ); $result['description'] = sprintf( '<p>%s</p>', __( 'A new minor update is available for your site. Because minor updates often address security, it&#8217;s important to install them.' ) ); } } else { $result['status'] = 'good'; $result['label'] = sprintf( /* translators: %s: The current version of WordPress installed on this site. */ __( 'Your version of WordPress (%s) is up to date' ), $core_current_version ); $result['description'] = sprintf( '<p>%s</p>', __( 'You are currently running the latest version of WordPress available, keep it up!' ) ); } } } return $result; } /** * Tests if plugins are outdated, or unnecessary. * * The test checks if your plugins are up to date, and encourages you to remove any * that are not in use. * * @since 5.2.0 * * @return array The test result. */ public function get_test_plugin_version() { $result = array( 'label' => __( 'Your plugins are all up to date' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'Plugins extend your site&#8217;s functionality with things like contact forms, ecommerce and much more. That means they have deep access to your site, so it&#8217;s vital to keep them up to date.' ) ), 'actions' => sprintf( '<p><a href="%s">%s</a></p>', esc_url( admin_url( 'plugins.php' ) ), __( 'Manage your plugins' ) ), 'test' => 'plugin_version', ); $plugins = get_plugins(); $plugin_updates = get_plugin_updates(); $plugins_active = 0; $plugins_total = 0; $plugins_need_update = 0; // Loop over the available plugins and check their versions and active state. foreach ( $plugins as $plugin_path => $plugin ) { $plugins_total++; if ( is_plugin_active( $plugin_path ) ) { $plugins_active++; } if ( array_key_exists( $plugin_path, $plugin_updates ) ) { $plugins_need_update++; } } // Add a notice if there are outdated plugins. if ( $plugins_need_update > 0 ) { $result['status'] = 'critical'; $result['label'] = __( 'You have plugins waiting to be updated' ); $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: %d: The number of outdated plugins. */ _n( 'Your site has %d plugin waiting to be updated.', 'Your site has %d plugins waiting to be updated.', $plugins_need_update ), $plugins_need_update ) ); $result['actions'] .= sprintf( '<p><a href="%s">%s</a></p>', esc_url( network_admin_url( 'plugins.php?plugin_status=upgrade' ) ), __( 'Update your plugins' ) ); } else { if ( 1 === $plugins_active ) { $result['description'] .= sprintf( '<p>%s</p>', __( 'Your site has 1 active plugin, and it is up to date.' ) ); } elseif ( $plugins_active > 0 ) { $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: %d: The number of active plugins. */ _n( 'Your site has %d active plugin, and it is up to date.', 'Your site has %d active plugins, and they are all up to date.', $plugins_active ), $plugins_active ) ); } else { $result['description'] .= sprintf( '<p>%s</p>', __( 'Your site does not have any active plugins.' ) ); } } // Check if there are inactive plugins. if ( $plugins_total > $plugins_active && ! is_multisite() ) { $unused_plugins = $plugins_total - $plugins_active; $result['status'] = 'recommended'; $result['label'] = __( 'You should remove inactive plugins' ); $result['description'] .= sprintf( '<p>%s %s</p>', sprintf( /* translators: %d: The number of inactive plugins. */ _n( 'Your site has %d inactive plugin.', 'Your site has %d inactive plugins.', $unused_plugins ), $unused_plugins ), __( 'Inactive plugins are tempting targets for attackers. If you are not going to use a plugin, you should consider removing it.' ) ); $result['actions'] .= sprintf( '<p><a href="%s">%s</a></p>', esc_url( admin_url( 'plugins.php?plugin_status=inactive' ) ), __( 'Manage inactive plugins' ) ); } return $result; } /** * Tests if themes are outdated, or unnecessary. * * Checks if your site has a default theme (to fall back on if there is a need), * if your themes are up to date and, finally, encourages you to remove any themes * that are not needed. * * @since 5.2.0 * * @return array The test results. */ public function get_test_theme_version() { $result = array( 'label' => __( 'Your themes are all up to date' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'Themes add your site&#8217;s look and feel. It&#8217;s important to keep them up to date, to stay consistent with your brand and keep your site secure.' ) ), 'actions' => sprintf( '<p><a href="%s">%s</a></p>', esc_url( admin_url( 'themes.php' ) ), __( 'Manage your themes' ) ), 'test' => 'theme_version', ); $theme_updates = get_theme_updates(); $themes_total = 0; $themes_need_updates = 0; $themes_inactive = 0; // This value is changed during processing to determine how many themes are considered a reasonable amount. $allowed_theme_count = 1; $has_default_theme = false; $has_unused_themes = false; $show_unused_themes = true; $using_default_theme = false; // Populate a list of all themes available in the install. $all_themes = wp_get_themes(); $active_theme = wp_get_theme(); // If WP_DEFAULT_THEME doesn't exist, fall back to the latest core default theme. $default_theme = wp_get_theme( WP_DEFAULT_THEME ); if ( ! $default_theme->exists() ) { $default_theme = WP_Theme::get_core_default_theme(); } if ( $default_theme ) { $has_default_theme = true; if ( $active_theme->get_stylesheet() === $default_theme->get_stylesheet() || is_child_theme() && $active_theme->get_template() === $default_theme->get_template() ) { $using_default_theme = true; } } foreach ( $all_themes as $theme_slug => $theme ) { $themes_total++; if ( array_key_exists( $theme_slug, $theme_updates ) ) { $themes_need_updates++; } } // If this is a child theme, increase the allowed theme count by one, to account for the parent. if ( is_child_theme() ) { $allowed_theme_count++; } // If there's a default theme installed and not in use, we count that as allowed as well. if ( $has_default_theme && ! $using_default_theme ) { $allowed_theme_count++; } if ( $themes_total > $allowed_theme_count ) { $has_unused_themes = true; $themes_inactive = ( $themes_total - $allowed_theme_count ); } // Check if any themes need to be updated. if ( $themes_need_updates > 0 ) { $result['status'] = 'critical'; $result['label'] = __( 'You have themes waiting to be updated' ); $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: %d: The number of outdated themes. */ _n( 'Your site has %d theme waiting to be updated.', 'Your site has %d themes waiting to be updated.', $themes_need_updates ), $themes_need_updates ) ); } else { // Give positive feedback about the site being good about keeping things up to date. if ( 1 === $themes_total ) { $result['description'] .= sprintf( '<p>%s</p>', __( 'Your site has 1 installed theme, and it is up to date.' ) ); } elseif ( $themes_total > 0 ) { $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: %d: The number of themes. */ _n( 'Your site has %d installed theme, and it is up to date.', 'Your site has %d installed themes, and they are all up to date.', $themes_total ), $themes_total ) ); } else { $result['description'] .= sprintf( '<p>%s</p>', __( 'Your site does not have any installed themes.' ) ); } } if ( $has_unused_themes && $show_unused_themes && ! is_multisite() ) { // This is a child theme, so we want to be a bit more explicit in our messages. if ( $active_theme->parent() ) { // Recommend removing inactive themes, except a default theme, your current one, and the parent theme. $result['status'] = 'recommended'; $result['label'] = __( 'You should remove inactive themes' ); if ( $using_default_theme ) { $result['description'] .= sprintf( '<p>%s %s</p>', sprintf( /* translators: %d: The number of inactive themes. */ _n( 'Your site has %d inactive theme.', 'Your site has %d inactive themes.', $themes_inactive ), $themes_inactive ), sprintf( /* translators: 1: The currently active theme. 2: The active theme's parent theme. */ __( 'To enhance your site&#8217;s security, you should consider removing any themes you are not using. You should keep your active theme, %1$s, and %2$s, its parent theme.' ), $active_theme->name, $active_theme->parent()->name ) ); } else { $result['description'] .= sprintf( '<p>%s %s</p>', sprintf( /* translators: %d: The number of inactive themes. */ _n( 'Your site has %d inactive theme.', 'Your site has %d inactive themes.', $themes_inactive ), $themes_inactive ), sprintf( /* translators: 1: The default theme for WordPress. 2: The currently active theme. 3: The active theme's parent theme. */ __( 'To enhance your site&#8217;s security, you should consider removing any themes you are not using. You should keep %1$s, the default WordPress theme, %2$s, your active theme, and %3$s, its parent theme.' ), $default_theme ? $default_theme->name : WP_DEFAULT_THEME, $active_theme->name, $active_theme->parent()->name ) ); } } else { // Recommend removing all inactive themes. $result['status'] = 'recommended'; $result['label'] = __( 'You should remove inactive themes' ); if ( $using_default_theme ) { $result['description'] .= sprintf( '<p>%s %s</p>', sprintf( /* translators: 1: The amount of inactive themes. 2: The currently active theme. */ _n( 'Your site has %1$d inactive theme, other than %2$s, your active theme.', 'Your site has %1$d inactive themes, other than %2$s, your active theme.', $themes_inactive ), $themes_inactive, $active_theme->name ), __( 'You should consider removing any unused themes to enhance your site&#8217;s security.' ) ); } else { $result['description'] .= sprintf( '<p>%s %s</p>', sprintf( /* translators: 1: The amount of inactive themes. 2: The default theme for WordPress. 3: The currently active theme. */ _n( 'Your site has %1$d inactive theme, other than %2$s, the default WordPress theme, and %3$s, your active theme.', 'Your site has %1$d inactive themes, other than %2$s, the default WordPress theme, and %3$s, your active theme.', $themes_inactive ), $themes_inactive, $default_theme ? $default_theme->name : WP_DEFAULT_THEME, $active_theme->name ), __( 'You should consider removing any unused themes to enhance your site&#8217;s security.' ) ); } } } // If no default Twenty* theme exists. if ( ! $has_default_theme ) { $result['status'] = 'recommended'; $result['label'] = __( 'Have a default theme available' ); $result['description'] .= sprintf( '<p>%s</p>', __( 'Your site does not have any default theme. Default themes are used by WordPress automatically if anything is wrong with your chosen theme.' ) ); } return $result; } /** * Tests if the supplied PHP version is supported. * * @since 5.2.0 * * @return array The test results. */ public function get_test_php_version() { $response = wp_check_php_version(); $result = array( 'label' => sprintf( /* translators: %s: The current PHP version. */ __( 'Your site is running the current version of PHP (%s)' ), PHP_VERSION ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', sprintf( /* translators: %s: The minimum recommended PHP version. */ __( 'PHP is one of the programming languages used to build WordPress. Newer versions of PHP receive regular security updates and may increase your site&#8217;s performance. The minimum recommended version of PHP is %s.' ), $response ? $response['recommended_version'] : '' ) ), 'actions' => sprintf( '<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>', esc_url( wp_get_update_php_url() ), __( 'Learn more about updating PHP' ), /* translators: Accessibility text. */ __( '(opens in a new tab)' ) ), 'test' => 'php_version', ); // PHP is up to date. if ( ! $response || version_compare( PHP_VERSION, $response['recommended_version'], '>=' ) ) { return $result; } // The PHP version is older than the recommended version, but still receiving active support. if ( $response['is_supported'] ) { $result['label'] = sprintf( /* translators: %s: The server PHP version. */ __( 'Your site is running on an older version of PHP (%s)' ), PHP_VERSION ); $result['status'] = 'recommended'; return $result; } // The PHP version is still receiving security fixes, but is lower than // the expected minimum version that will be required by WordPress in the near future. if ( $response['is_secure'] && $response['is_lower_than_future_minimum'] ) { // The `is_secure` array key name doesn't actually imply this is a secure version of PHP. It only means it receives security updates. $result['label'] = sprintf( /* translators: %s: The server PHP version. */ __( 'Your site is running on an outdated version of PHP (%s), which soon will not be supported by WordPress.' ), PHP_VERSION ); $result['status'] = 'critical'; $result['badge']['label'] = __( 'Requirements' ); return $result; } // The PHP version is only receiving security fixes. if ( $response['is_secure'] ) { $result['label'] = sprintf( /* translators: %s: The server PHP version. */ __( 'Your site is running on an older version of PHP (%s), which should be updated' ), PHP_VERSION ); $result['status'] = 'recommended'; return $result; } // No more security updates for the PHP version, and lower than the expected minimum version required by WordPress. if ( $response['is_lower_than_future_minimum'] ) { $message = sprintf( /* translators: %s: The server PHP version. */ __( 'Your site is running on an outdated version of PHP (%s), which does not receive security updates and soon will not be supported by WordPress.' ), PHP_VERSION ); } else { // No more security updates for the PHP version, must be updated. $message = sprintf( /* translators: %s: The server PHP version. */ __( 'Your site is running on an outdated version of PHP (%s), which does not receive security updates. It should be updated.' ), PHP_VERSION ); } $result['label'] = $message; $result['status'] = 'critical'; $result['badge']['label'] = __( 'Security' ); return $result; } /** * Checks if the passed extension or function are available. * * Make the check for available PHP modules into a simple boolean operator for a cleaner test runner. * * @since 5.2.0 * @since 5.3.0 The `$constant_name` and `$class_name` parameters were added. * * @param string $extension_name Optional. The extension name to test. Default null. * @param string $function_name Optional. The function name to test. Default null. * @param string $constant_name Optional. The constant name to test for. Default null. * @param string $class_name Optional. The class name to test for. Default null. * @return bool Whether or not the extension and function are available. */ private function test_php_extension_availability( $extension_name = null, $function_name = null, $constant_name = null, $class_name = null ) { // If no extension or function is passed, claim to fail testing, as we have nothing to test against. if ( ! $extension_name && ! $function_name && ! $constant_name && ! $class_name ) { return false; } if ( $extension_name && ! extension_loaded( $extension_name ) ) { return false; } if ( $function_name && ! function_exists( $function_name ) ) { return false; } if ( $constant_name && ! defined( $constant_name ) ) { return false; } if ( $class_name && ! class_exists( $class_name ) ) { return false; } return true; } /** * Tests if required PHP modules are installed on the host. * * This test builds on the recommendations made by the WordPress Hosting Team * as seen at https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions * * @since 5.2.0 * * @return array */ public function get_test_php_extensions() { $result = array( 'label' => __( 'Required and recommended modules are installed' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p><p>%s</p>', __( 'PHP modules perform most of the tasks on the server that make your site run. Any changes to these must be made by your server administrator.' ), sprintf( /* translators: 1: Link to the hosting group page about recommended PHP modules. 2: Additional link attributes. 3: Accessibility text. */ __( 'The WordPress Hosting Team maintains a list of those modules, both recommended and required, in <a href="%1$s" %2$s>the team handbook%3$s</a>.' ), /* translators: Localized team handbook, if one exists. */ esc_url( __( 'https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions' ) ), 'target="_blank" rel="noopener"', sprintf( ' <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span>', /* translators: Accessibility text. */ __( '(opens in a new tab)' ) ) ) ), 'actions' => '', 'test' => 'php_extensions', ); $modules = array( 'curl' => array( 'function' => 'curl_version', 'required' => false, ), 'dom' => array( 'class' => 'DOMNode', 'required' => false, ), 'exif' => array( 'function' => 'exif_read_data', 'required' => false, ), 'fileinfo' => array( 'function' => 'finfo_file', 'required' => false, ), 'hash' => array( 'function' => 'hash', 'required' => false, ), 'imagick' => array( 'extension' => 'imagick', 'required' => false, ), 'json' => array( 'function' => 'json_last_error', 'required' => true, ), 'mbstring' => array( 'function' => 'mb_check_encoding', 'required' => false, ), 'mysqli' => array( 'function' => 'mysqli_connect', 'required' => false, ), 'libsodium' => array( 'constant' => 'SODIUM_LIBRARY_VERSION', 'required' => false, 'php_bundled_version' => '7.2.0', ), 'openssl' => array( 'function' => 'openssl_encrypt', 'required' => false, ), 'pcre' => array( 'function' => 'preg_match', 'required' => false, ), 'mod_xml' => array( 'extension' => 'libxml', 'required' => false, ), 'zip' => array( 'class' => 'ZipArchive', 'required' => false, ), 'filter' => array( 'function' => 'filter_list', 'required' => false, ), 'gd' => array( 'extension' => 'gd', 'required' => false, 'fallback_for' => 'imagick', ), 'iconv' => array( 'function' => 'iconv', 'required' => false, ), 'intl' => array( 'extension' => 'intl', 'required' => false, ), 'mcrypt' => array( 'extension' => 'mcrypt', 'required' => false, 'fallback_for' => 'libsodium', ), 'simplexml' => array( 'extension' => 'simplexml', 'required' => false, 'fallback_for' => 'mod_xml', ), 'xmlreader' => array( 'extension' => 'xmlreader', 'required' => false, 'fallback_for' => 'mod_xml', ), 'zlib' => array( 'extension' => 'zlib', 'required' => false, 'fallback_for' => 'zip', ), ); /** * Filters the array representing all the modules we wish to test for. * * @since 5.2.0 * @since 5.3.0 The `$constant` and `$class` parameters were added. * * @param array $modules { * An associative array of modules to test for. * * @type array ...$0 { * An associative array of module properties used during testing. * One of either `$function` or `$extension` must be provided, or they will fail by default. * * @type string $function Optional. A function name to test for the existence of. * @type string $extension Optional. An extension to check if is loaded in PHP. * @type string $constant Optional. A constant name to check for to verify an extension exists. * @type string $class Optional. A class name to check for to verify an extension exists. * @type bool $required Is this a required feature or not. * @type string $fallback_for Optional. The module this module replaces as a fallback. * } * } */ $modules = apply_filters( 'site_status_test_php_modules', $modules ); $failures = array(); foreach ( $modules as $library => $module ) { $extension_name = ( isset( $module['extension'] ) ? $module['extension'] : null ); $function_name = ( isset( $module['function'] ) ? $module['function'] : null ); $constant_name = ( isset( $module['constant'] ) ? $module['constant'] : null ); $class_name = ( isset( $module['class'] ) ? $module['class'] : null ); // If this module is a fallback for another function, check if that other function passed. if ( isset( $module['fallback_for'] ) ) { /* * If that other function has a failure, mark this module as required for usual operations. * If that other function hasn't failed, skip this test as it's only a fallback. */ if ( isset( $failures[ $module['fallback_for'] ] ) ) { $module['required'] = true; } else { continue; } } if ( ! $this->test_php_extension_availability( $extension_name, $function_name, $constant_name, $class_name ) && ( ! isset( $module['php_bundled_version'] ) || version_compare( PHP_VERSION, $module['php_bundled_version'], '<' ) ) ) { if ( $module['required'] ) { $result['status'] = 'critical'; $class = 'error'; $screen_reader = __( 'Error' ); $message = sprintf( /* translators: %s: The module name. */ __( 'The required module, %s, is not installed, or has been disabled.' ), $library ); } else { $class = 'warning'; $screen_reader = __( 'Warning' ); $message = sprintf( /* translators: %s: The module name. */ __( 'The optional module, %s, is not installed, or has been disabled.' ), $library ); } if ( ! $module['required'] && 'good' === $result['status'] ) { $result['status'] = 'recommended'; } $failures[ $library ] = "<span class='dashicons $class'><span class='screen-reader-text'>$screen_reader</span></span> $message"; } } if ( ! empty( $failures ) ) { $output = '<ul>'; foreach ( $failures as $failure ) { $output .= sprintf( '<li>%s</li>', $failure ); } $output .= '</ul>'; } if ( 'good' !== $result['status'] ) { if ( 'recommended' === $result['status'] ) { $result['label'] = __( 'One or more recommended modules are missing' ); } if ( 'critical' === $result['status'] ) { $result['label'] = __( 'One or more required modules are missing' ); } $result['description'] .= $output; } return $result; } /** * Tests if the PHP default timezone is set to UTC. * * @since 5.3.1 * * @return array The test results. */ public function get_test_php_default_timezone() { $result = array( 'label' => __( 'PHP default timezone is valid' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'PHP default timezone was configured by WordPress on loading. This is necessary for correct calculations of dates and times.' ) ), 'actions' => '', 'test' => 'php_default_timezone', ); if ( 'UTC' !== date_default_timezone_get() ) { $result['status'] = 'critical'; $result['label'] = __( 'PHP default timezone is invalid' ); $result['description'] = sprintf( '<p>%s</p>', sprintf( /* translators: %s: date_default_timezone_set() */ __( 'PHP default timezone was changed after WordPress loading by a %s function call. This interferes with correct calculations of dates and times.' ), '<code>date_default_timezone_set()</code>' ) ); } return $result; } /** * Tests if there's an active PHP session that can affect loopback requests. * * @since 5.5.0 * * @return array The test results. */ public function get_test_php_sessions() { $result = array( 'label' => __( 'No PHP sessions detected' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', sprintf( /* translators: 1: session_start(), 2: session_write_close() */ __( 'PHP sessions created by a %1$s function call may interfere with REST API and loopback requests. An active session should be closed by %2$s before making any HTTP requests.' ), '<code>session_start()</code>', '<code>session_write_close()</code>' ) ), 'test' => 'php_sessions', ); if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) { $result['status'] = 'critical'; $result['label'] = __( 'An active PHP session was detected' ); $result['description'] = sprintf( '<p>%s</p>', sprintf( /* translators: 1: session_start(), 2: session_write_close() */ __( 'A PHP session was created by a %1$s function call. This interferes with REST API and loopback requests. The session should be closed by %2$s before making any HTTP requests.' ), '<code>session_start()</code>', '<code>session_write_close()</code>' ) ); } return $result; } /** * Tests if the SQL server is up to date. * * @since 5.2.0 * * @return array The test results. */ public function get_test_sql_server() { if ( ! $this->mysql_server_version ) { $this->prepare_sql_data(); } $result = array( 'label' => __( 'SQL server is up to date' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'The SQL server is a required piece of software for the database WordPress uses to store all your site&#8217;s content and settings.' ) ), 'actions' => sprintf( '<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>', /* translators: Localized version of WordPress requirements if one exists. */ esc_url( __( 'https://wordpress.org/about/requirements/' ) ), __( 'Learn more about what WordPress requires to run.' ), /* translators: Accessibility text. */ __( '(opens in a new tab)' ) ), 'test' => 'sql_server', ); $db_dropin = file_exists( WP_CONTENT_DIR . '/db.php' ); if ( ! $this->is_recommended_mysql_version ) { $result['status'] = 'recommended'; $result['label'] = __( 'Outdated SQL server' ); $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: 1: The database engine in use (MySQL or MariaDB). 2: Database server recommended version number. */ __( 'For optimal performance and security reasons, you should consider running %1$s version %2$s or higher. Contact your web hosting company to correct this.' ), ( $this->is_mariadb ? 'MariaDB' : 'MySQL' ), $this->mysql_recommended_version ) ); } if ( ! $this->is_acceptable_mysql_version ) { $result['status'] = 'critical'; $result['label'] = __( 'Severely outdated SQL server' ); $result['badge']['label'] = __( 'Security' ); $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: 1: The database engine in use (MySQL or MariaDB). 2: Database server minimum version number. */ __( 'WordPress requires %1$s version %2$s or higher. Contact your web hosting company to correct this.' ), ( $this->is_mariadb ? 'MariaDB' : 'MySQL' ), $this->mysql_required_version ) ); } if ( $db_dropin ) { $result['description'] .= sprintf( '<p>%s</p>', wp_kses( sprintf( /* translators: 1: The name of the drop-in. 2: The name of the database engine. */ __( 'You are using a %1$s drop-in which might mean that a %2$s database is not being used.' ), '<code>wp-content/db.php</code>', ( $this->is_mariadb ? 'MariaDB' : 'MySQL' ) ), array( 'code' => true, ) ) ); } return $result; } /** * Tests if the database server is capable of using utf8mb4. * * @since 5.2.0 * * @return array The test results. */ public function get_test_utf8mb4_support() { global $wpdb; if ( ! $this->mysql_server_version ) { $this->prepare_sql_data(); } $result = array( 'label' => __( 'UTF8MB4 is supported' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'UTF8MB4 is the character set WordPress prefers for database storage because it safely supports the widest set of characters and encodings, including Emoji, enabling better support for non-English languages.' ) ), 'actions' => '', 'test' => 'utf8mb4_support', ); if ( ! $this->is_mariadb ) { if ( version_compare( $this->mysql_server_version, '5.5.3', '<' ) ) { $result['status'] = 'recommended'; $result['label'] = __( 'utf8mb4 requires a MySQL update' ); $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: %s: Version number. */ __( 'WordPress&#8217; utf8mb4 support requires MySQL version %s or greater. Please contact your server administrator.' ), '5.5.3' ) ); } else { $result['description'] .= sprintf( '<p>%s</p>', __( 'Your MySQL version supports utf8mb4.' ) ); } } else { // MariaDB introduced utf8mb4 support in 5.5.0. if ( version_compare( $this->mysql_server_version, '5.5.0', '<' ) ) { $result['status'] = 'recommended'; $result['label'] = __( 'utf8mb4 requires a MariaDB update' ); $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: %s: Version number. */ __( 'WordPress&#8217; utf8mb4 support requires MariaDB version %s or greater. Please contact your server administrator.' ), '5.5.0' ) ); } else { $result['description'] .= sprintf( '<p>%s</p>', __( 'Your MariaDB version supports utf8mb4.' ) ); } } if ( $wpdb->use_mysqli ) { // phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysqli_get_client_info $mysql_client_version = mysqli_get_client_info(); } else { // phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysql_get_client_info,PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved $mysql_client_version = mysql_get_client_info(); } /* * libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server. * mysqlnd has supported utf8mb4 since 5.0.9. */ if ( false !== strpos( $mysql_client_version, 'mysqlnd' ) ) { $mysql_client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $mysql_client_version ); if ( version_compare( $mysql_client_version, '5.0.9', '<' ) ) { $result['status'] = 'recommended'; $result['label'] = __( 'utf8mb4 requires a newer client library' ); $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: 1: Name of the library, 2: Number of version. */ __( 'WordPress&#8217; utf8mb4 support requires MySQL client library (%1$s) version %2$s or newer. Please contact your server administrator.' ), 'mysqlnd', '5.0.9' ) ); } } else { if ( version_compare( $mysql_client_version, '5.5.3', '<' ) ) { $result['status'] = 'recommended'; $result['label'] = __( 'utf8mb4 requires a newer client library' ); $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: 1: Name of the library, 2: Number of version. */ __( 'WordPress&#8217; utf8mb4 support requires MySQL client library (%1$s) version %2$s or newer. Please contact your server administrator.' ), 'libmysql', '5.5.3' ) ); } } return $result; } /** * Tests if the site can communicate with WordPress.org. * * @since 5.2.0 * * @return array The test results. */ public function get_test_dotorg_communication() { $result = array( 'label' => __( 'Can communicate with WordPress.org' ), 'status' => '', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'Communicating with the WordPress servers is used to check for new versions, and to both install and update WordPress core, themes or plugins.' ) ), 'actions' => '', 'test' => 'dotorg_communication', ); $wp_dotorg = wp_remote_get( 'https://api.wordpress.org', array( 'timeout' => 10, ) ); if ( ! is_wp_error( $wp_dotorg ) ) { $result['status'] = 'good'; } else { $result['status'] = 'critical'; $result['label'] = __( 'Could not reach WordPress.org' ); $result['description'] .= sprintf( '<p>%s</p>', sprintf( '<span class="error"><span class="screen-reader-text">%s</span></span> %s', __( 'Error' ), sprintf( /* translators: 1: The IP address WordPress.org resolves to. 2: The error returned by the lookup. */ __( 'Your site is unable to reach WordPress.org at %1$s, and returned the error: %2$s' ), gethostbyname( 'api.wordpress.org' ), $wp_dotorg->get_error_message() ) ) ); $result['actions'] = sprintf( '<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>', /* translators: Localized Support reference. */ esc_url( __( 'https://wordpress.org/support' ) ), __( 'Get help resolving this issue.' ), /* translators: Accessibility text. */ __( '(opens in a new tab)' ) ); } return $result; } /** * Tests if debug information is enabled. * * When WP_DEBUG is enabled, errors and information may be disclosed to site visitors, * or logged to a publicly accessible file. * * Debugging is also frequently left enabled after looking for errors on a site, * as site owners do not understand the implications of this. * * @since 5.2.0 * * @return array The test results. */ public function get_test_is_in_debug_mode() { $result = array( 'label' => __( 'Your site is not set to output debug information' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'Debug mode is often enabled to gather more details about an error or site failure, but may contain sensitive information which should not be available on a publicly available website.' ) ), 'actions' => sprintf( '<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>', /* translators: Documentation explaining debugging in WordPress. */ esc_url( __( 'https://wordpress.org/support/article/debugging-in-wordpress/' ) ), __( 'Learn more about debugging in WordPress.' ), /* translators: Accessibility text. */ __( '(opens in a new tab)' ) ), 'test' => 'is_in_debug_mode', ); if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) { $result['label'] = __( 'Your site is set to log errors to a potentially public file' ); $result['status'] = ( 0 === strpos( ini_get( 'error_log' ), ABSPATH ) ) ? 'critical' : 'recommended'; $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: %s: WP_DEBUG_LOG */ __( 'The value, %s, has been added to this website&#8217;s configuration file. This means any errors on the site will be written to a file which is potentially available to all users.' ), '<code>WP_DEBUG_LOG</code>' ) ); } if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) { $result['label'] = __( 'Your site is set to display errors to site visitors' ); $result['status'] = 'critical'; // On development environments, set the status to recommended. if ( $this->is_development_environment() ) { $result['status'] = 'recommended'; } $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: 1: WP_DEBUG_DISPLAY, 2: WP_DEBUG */ __( 'The value, %1$s, has either been enabled by %2$s or added to your configuration file. This will make errors display on the front end of your site.' ), '<code>WP_DEBUG_DISPLAY</code>', '<code>WP_DEBUG</code>' ) ); } } return $result; } /** * Tests if the site is serving content over HTTPS. * * Many sites have varying degrees of HTTPS support, the most common of which is sites that have it * enabled, but only if you visit the right site address. * * @since 5.2.0 * @since 5.7.0 Updated to rely on {@see wp_is_using_https()} and {@see wp_is_https_supported()}. * * @return array The test results. */ public function get_test_https_status() { // Enforce fresh HTTPS detection results. This is normally invoked by using cron, // but for Site Health it should always rely on the latest results. wp_update_https_detection_errors(); $default_update_url = wp_get_default_update_https_url(); $result = array( 'label' => __( 'Your website is using an active HTTPS connection' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'An HTTPS connection is a more secure way of browsing the web. Many services now have HTTPS as a requirement. HTTPS allows you to take advantage of new features that can increase site speed, improve search rankings, and gain the trust of your visitors by helping to protect their online privacy.' ) ), 'actions' => sprintf( '<p><a href="%s" target="_blank" rel="noopener">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>', esc_url( $default_update_url ), __( 'Learn more about why you should use HTTPS' ), /* translators: Accessibility text. */ __( '(opens in a new tab)' ) ), 'test' => 'https_status', ); if ( ! wp_is_using_https() ) { // If the website is not using HTTPS, provide more information // about whether it is supported and how it can be enabled. $result['status'] = 'recommended'; $result['label'] = __( 'Your website does not use HTTPS' ); if ( wp_is_site_url_using_https() ) { if ( is_ssl() ) { $result['description'] = sprintf( '<p>%s</p>', sprintf( /* translators: %s: URL to Settings > General > Site Address. */ __( 'You are accessing this website using HTTPS, but your <a href="%s">Site Address</a> is not set up to use HTTPS by default.' ), esc_url( admin_url( 'options-general.php' ) . '#home' ) ) ); } else { $result['description'] = sprintf( '<p>%s</p>', sprintf( /* translators: %s: URL to Settings > General > Site Address. */ __( 'Your <a href="%s">Site Address</a> is not set up to use HTTPS.' ), esc_url( admin_url( 'options-general.php' ) . '#home' ) ) ); } } else { if ( is_ssl() ) { $result['description'] = sprintf( '<p>%s</p>', sprintf( /* translators: 1: URL to Settings > General > WordPress Address, 2: URL to Settings > General > Site Address. */ __( 'You are accessing this website using HTTPS, but your <a href="%1$s">WordPress Address</a> and <a href="%2$s">Site Address</a> are not set up to use HTTPS by default.' ), esc_url( admin_url( 'options-general.php' ) . '#siteurl' ), esc_url( admin_url( 'options-general.php' ) . '#home' ) ) ); } else { $result['description'] = sprintf( '<p>%s</p>', sprintf( /* translators: 1: URL to Settings > General > WordPress Address, 2: URL to Settings > General > Site Address. */ __( 'Your <a href="%1$s">WordPress Address</a> and <a href="%2$s">Site Address</a> are not set up to use HTTPS.' ), esc_url( admin_url( 'options-general.php' ) . '#siteurl' ), esc_url( admin_url( 'options-general.php' ) . '#home' ) ) ); } } if ( wp_is_https_supported() ) { $result['description'] .= sprintf( '<p>%s</p>', __( 'HTTPS is already supported for your website.' ) ); if ( defined( 'WP_HOME' ) || defined( 'WP_SITEURL' ) ) { $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: 1: wp-config.php, 2: WP_HOME, 3: WP_SITEURL */ __( 'However, your WordPress Address is currently controlled by a PHP constant and therefore cannot be updated. You need to edit your %1$s and remove or update the definitions of %2$s and %3$s.' ), '<code>wp-config.php</code>', '<code>WP_HOME</code>', '<code>WP_SITEURL</code>' ) ); } elseif ( current_user_can( 'update_https' ) ) { $default_direct_update_url = add_query_arg( 'action', 'update_https', wp_nonce_url( admin_url( 'site-health.php' ), 'wp_update_https' ) ); $direct_update_url = wp_get_direct_update_https_url(); if ( ! empty( $direct_update_url ) ) { $result['actions'] = sprintf( '<p class="button-container"><a class="button button-primary" href="%1$s" target="_blank" rel="noopener">%2$s<span class="screen-reader-text"> %3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>', esc_url( $direct_update_url ), __( 'Update your site to use HTTPS' ), /* translators: Accessibility text. */ __( '(opens in a new tab)' ) ); } else { $result['actions'] = sprintf( '<p class="button-container"><a class="button button-primary" href="%1$s">%2$s</a></p>', esc_url( $default_direct_update_url ), __( 'Update your site to use HTTPS' ) ); } } } else { // If host-specific "Update HTTPS" URL is provided, include a link. $update_url = wp_get_update_https_url(); if ( $update_url !== $default_update_url ) { $result['description'] .= sprintf( '<p><a href="%s" target="_blank" rel="noopener">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>', esc_url( $update_url ), __( 'Talk to your web host about supporting HTTPS for your website.' ), /* translators: Accessibility text. */ __( '(opens in a new tab)' ) ); } else { $result['description'] .= sprintf( '<p>%s</p>', __( 'Talk to your web host about supporting HTTPS for your website.' ) ); } } } return $result; } /** * Checks if the HTTP API can handle SSL/TLS requests. * * @since 5.2.0 * * @return array The test result. */ public function get_test_ssl_support() { $result = array( 'label' => '', 'status' => '', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'Securely communicating between servers are needed for transactions such as fetching files, conducting sales on store sites, and much more.' ) ), 'actions' => '', 'test' => 'ssl_support', ); $supports_https = wp_http_supports( array( 'ssl' ) ); if ( $supports_https ) { $result['status'] = 'good'; $result['label'] = __( 'Your site can communicate securely with other services' ); } else { $result['status'] = 'critical'; $result['label'] = __( 'Your site is unable to communicate securely with other services' ); $result['description'] .= sprintf( '<p>%s</p>', __( 'Talk to your web host about OpenSSL support for PHP.' ) ); } return $result; } /** * Tests if scheduled events run as intended. * * If scheduled events are not running, this may indicate something with WP_Cron is not working * as intended, or that there are orphaned events hanging around from older code. * * @since 5.2.0 * * @return array The test results. */ public function get_test_scheduled_events() { $result = array( 'label' => __( 'Scheduled events are running' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'Scheduled events are what periodically looks for updates to plugins, themes and WordPress itself. It is also what makes sure scheduled posts are published on time. It may also be used by various plugins to make sure that planned actions are executed.' ) ), 'actions' => '', 'test' => 'scheduled_events', ); $this->wp_schedule_test_init(); if ( is_wp_error( $this->has_missed_cron() ) ) { $result['status'] = 'critical'; $result['label'] = __( 'It was not possible to check your scheduled events' ); $result['description'] = sprintf( '<p>%s</p>', sprintf( /* translators: %s: The error message returned while from the cron scheduler. */ __( 'While trying to test your site&#8217;s scheduled events, the following error was returned: %s' ), $this->has_missed_cron()->get_error_message() ) ); } elseif ( $this->has_missed_cron() ) { $result['status'] = 'recommended'; $result['label'] = __( 'A scheduled event has failed' ); $result['description'] = sprintf( '<p>%s</p>', sprintf( /* translators: %s: The name of the failed cron event. */ __( 'The scheduled event, %s, failed to run. Your site still works, but this may indicate that scheduling posts or automated updates may not work as intended.' ), $this->last_missed_cron ) ); } elseif ( $this->has_late_cron() ) { $result['status'] = 'recommended'; $result['label'] = __( 'A scheduled event is late' ); $result['description'] = sprintf( '<p>%s</p>', sprintf( /* translators: %s: The name of the late cron event. */ __( 'The scheduled event, %s, is late to run. Your site still works, but this may indicate that scheduling posts or automated updates may not work as intended.' ), $this->last_late_cron ) ); } return $result; } /** * Tests if WordPress can run automated background updates. * * Background updates in WordPress are primarily used for minor releases and security updates. * It's important to either have these working, or be aware that they are intentionally disabled * for whatever reason. * * @since 5.2.0 * * @return array The test results. */ public function get_test_background_updates() { $result = array( 'label' => __( 'Background updates are working' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'Background updates ensure that WordPress can auto-update if a security update is released for the version you are currently using.' ) ), 'actions' => '', 'test' => 'background_updates', ); if ( ! class_exists( 'WP_Site_Health_Auto_Updates' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-site-health-auto-updates.php'; } // Run the auto-update tests in a separate class, // as there are many considerations to be made. $automatic_updates = new WP_Site_Health_Auto_Updates(); $tests = $automatic_updates->run_tests(); $output = '<ul>'; foreach ( $tests as $test ) { $severity_string = __( 'Passed' ); if ( 'fail' === $test->severity ) { $result['label'] = __( 'Background updates are not working as expected' ); $result['status'] = 'critical'; $severity_string = __( 'Error' ); } if ( 'warning' === $test->severity && 'good' === $result['status'] ) { $result['label'] = __( 'Background updates may not be working properly' ); $result['status'] = 'recommended'; $severity_string = __( 'Warning' ); } $output .= sprintf( '<li><span class="dashicons %s"><span class="screen-reader-text">%s</span></span> %s</li>', esc_attr( $test->severity ), $severity_string, $test->description ); } $output .= '</ul>'; if ( 'good' !== $result['status'] ) { $result['description'] .= $output; } return $result; } /** * Tests if plugin and theme auto-updates appear to be configured correctly. * * @since 5.5.0 * * @return array The test results. */ public function get_test_plugin_theme_auto_updates() { $result = array( 'label' => __( 'Plugin and theme auto-updates appear to be configured correctly' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'Plugin and theme auto-updates ensure that the latest versions are always installed.' ) ), 'actions' => '', 'test' => 'plugin_theme_auto_updates', ); $check_plugin_theme_updates = $this->detect_plugin_theme_auto_update_issues(); $result['status'] = $check_plugin_theme_updates->status; if ( 'good' !== $result['status'] ) { $result['label'] = __( 'Your site may have problems auto-updating plugins and themes' ); $result['description'] .= sprintf( '<p>%s</p>', $check_plugin_theme_updates->message ); } return $result; } /** * Tests if loopbacks work as expected. * * A loopback is when WordPress queries itself, for example to start a new WP_Cron instance, * or when editing a plugin or theme. This has shown itself to be a recurring issue, * as code can very easily break this interaction. * * @since 5.2.0 * * @return array The test results. */ public function get_test_loopback_requests() { $result = array( 'label' => __( 'Your site can perform loopback requests' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'Loopback requests are used to run scheduled events, and are also used by the built-in editors for themes and plugins to verify code stability.' ) ), 'actions' => '', 'test' => 'loopback_requests', ); $check_loopback = $this->can_perform_loopback(); $result['status'] = $check_loopback->status; if ( 'good' !== $result['status'] ) { $result['label'] = __( 'Your site could not complete a loopback request' ); $result['description'] .= sprintf( '<p>%s</p>', $check_loopback->message ); } return $result; } /** * Tests if HTTP requests are blocked. * * It's possible to block all outgoing communication (with the possibility of allowing certain * hosts) via the HTTP API. This may create problems for users as many features are running as * services these days. * * @since 5.2.0 * * @return array The test results. */ public function get_test_http_requests() { $result = array( 'label' => __( 'HTTP requests seem to be working as expected' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'It is possible for site maintainers to block all, or some, communication to other sites and services. If set up incorrectly, this may prevent plugins and themes from working as intended.' ) ), 'actions' => '', 'test' => 'http_requests', ); $blocked = false; $hosts = array(); if ( defined( 'WP_HTTP_BLOCK_EXTERNAL' ) && WP_HTTP_BLOCK_EXTERNAL ) { $blocked = true; } if ( defined( 'WP_ACCESSIBLE_HOSTS' ) ) { $hosts = explode( ',', WP_ACCESSIBLE_HOSTS ); } if ( $blocked && 0 === count( $hosts ) ) { $result['status'] = 'critical'; $result['label'] = __( 'HTTP requests are blocked' ); $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: %s: Name of the constant used. */ __( 'HTTP requests have been blocked by the %s constant, with no allowed hosts.' ), '<code>WP_HTTP_BLOCK_EXTERNAL</code>' ) ); } if ( $blocked && 0 < count( $hosts ) ) { $result['status'] = 'recommended'; $result['label'] = __( 'HTTP requests are partially blocked' ); $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: 1: Name of the constant used. 2: List of allowed hostnames. */ __( 'HTTP requests have been blocked by the %1$s constant, with some allowed hosts: %2$s.' ), '<code>WP_HTTP_BLOCK_EXTERNAL</code>', implode( ',', $hosts ) ) ); } return $result; } /** * Tests if the REST API is accessible. * * Various security measures may block the REST API from working, or it may have been disabled in general. * This is required for the new block editor to work, so we explicitly test for this. * * @since 5.2.0 * * @return array The test results. */ public function get_test_rest_availability() { $result = array( 'label' => __( 'The REST API is available' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'The REST API is one way that WordPress and other applications communicate with the server. For example, the block editor screen relies on the REST API to display and save your posts and pages.' ) ), 'actions' => '', 'test' => 'rest_availability', ); $cookies = wp_unslash( $_COOKIE ); $timeout = 10; // 10 seconds. $headers = array( 'Cache-Control' => 'no-cache', 'X-WP-Nonce' => wp_create_nonce( 'wp_rest' ), ); /** This filter is documented in wp-includes/class-wp-http-streams.php */ $sslverify = apply_filters( 'https_local_ssl_verify', false ); // Include Basic auth in loopback requests. if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) { $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) ); } $url = rest_url( 'wp/v2/types/post' ); // The context for this is editing with the new block editor. $url = add_query_arg( array( 'context' => 'edit', ), $url ); $r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) ); if ( is_wp_error( $r ) ) { $result['status'] = 'critical'; $result['label'] = __( 'The REST API encountered an error' ); $result['description'] .= sprintf( '<p>%s</p><p>%s<br>%s</p>', __( 'When testing the REST API, an error was encountered:' ), sprintf( // translators: %s: The REST API URL. __( 'REST API Endpoint: %s' ), $url ), sprintf( // translators: 1: The WordPress error code. 2: The WordPress error message. __( 'REST API Response: (%1$s) %2$s' ), $r->get_error_code(), $r->get_error_message() ) ); } elseif ( 200 !== wp_remote_retrieve_response_code( $r ) ) { $result['status'] = 'recommended'; $result['label'] = __( 'The REST API encountered an unexpected result' ); $result['description'] .= sprintf( '<p>%s</p><p>%s<br>%s</p>', __( 'When testing the REST API, an unexpected result was returned:' ), sprintf( // translators: %s: The REST API URL. __( 'REST API Endpoint: %s' ), $url ), sprintf( // translators: 1: The WordPress error code. 2: The HTTP status code error message. __( 'REST API Response: (%1$s) %2$s' ), wp_remote_retrieve_response_code( $r ), wp_remote_retrieve_response_message( $r ) ) ); } else { $json = json_decode( wp_remote_retrieve_body( $r ), true ); if ( false !== $json && ! isset( $json['capabilities'] ) ) { $result['status'] = 'recommended'; $result['label'] = __( 'The REST API did not behave correctly' ); $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: %s: The name of the query parameter being tested. */ __( 'The REST API did not process the %s query parameter correctly.' ), '<code>context</code>' ) ); } } return $result; } /** * Tests if 'file_uploads' directive in PHP.ini is turned off. * * @since 5.5.0 * * @return array The test results. */ public function get_test_file_uploads() { $result = array( 'label' => __( 'Files can be uploaded' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', sprintf( /* translators: 1: file_uploads, 2: php.ini */ __( 'The %1$s directive in %2$s determines if uploading files is allowed on your site.' ), '<code>file_uploads</code>', '<code>php.ini</code>' ) ), 'actions' => '', 'test' => 'file_uploads', ); if ( ! function_exists( 'ini_get' ) ) { $result['status'] = 'critical'; $result['description'] .= sprintf( /* translators: %s: ini_get() */ __( 'The %s function has been disabled, some media settings are unavailable because of this.' ), '<code>ini_get()</code>' ); return $result; } if ( empty( ini_get( 'file_uploads' ) ) ) { $result['status'] = 'critical'; $result['description'] .= sprintf( '<p>%s</p>', sprintf( /* translators: 1: file_uploads, 2: 0 */ __( '%1$s is set to %2$s. You won\'t be able to upload files on your site.' ), '<code>file_uploads</code>', '<code>0</code>' ) ); return $result; } $post_max_size = ini_get( 'post_max_size' ); $upload_max_filesize = ini_get( 'upload_max_filesize' ); if ( wp_convert_hr_to_bytes( $post_max_size ) < wp_convert_hr_to_bytes( $upload_max_filesize ) ) { $result['label'] = sprintf( /* translators: 1: post_max_size, 2: upload_max_filesize */ __( 'The "%1$s" value is smaller than "%2$s"' ), 'post_max_size', 'upload_max_filesize' ); $result['status'] = 'recommended'; if ( 0 === wp_convert_hr_to_bytes( $post_max_size ) ) { $result['description'] = sprintf( '<p>%s</p>', sprintf( /* translators: 1: post_max_size, 2: upload_max_filesize */ __( 'The setting for %1$s is currently configured as 0, this could cause some problems when trying to upload files through plugin or theme features that rely on various upload methods. It is recommended to configure this setting to a fixed value, ideally matching the value of %2$s, as some upload methods read the value 0 as either unlimited, or disabled.' ), '<code>post_max_size</code>', '<code>upload_max_filesize</code>' ) ); } else { $result['description'] = sprintf( '<p>%s</p>', sprintf( /* translators: 1: post_max_size, 2: upload_max_filesize */ __( 'The setting for %1$s is smaller than %2$s, this could cause some problems when trying to upload files.' ), '<code>post_max_size</code>', '<code>upload_max_filesize</code>' ) ); } return $result; } return $result; } /** * Tests if the Authorization header has the expected values. * * @since 5.6.0 * * @return array */ public function get_test_authorization_header() { $result = array( 'label' => __( 'The Authorization header is working as expected' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '<p>%s</p>', __( 'The Authorization header is used by third-party applications you have approved for this site. Without this header, those apps cannot connect to your site.' ) ), 'actions' => '', 'test' => 'authorization_header', ); if ( ! isset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) { $result['label'] = __( 'The authorization header is missing' ); } elseif ( 'user' !== $_SERVER['PHP_AUTH_USER'] || 'pwd' !== $_SERVER['PHP_AUTH_PW'] ) { $result['label'] = __( 'The authorization header is invalid' ); } else { return $result; } $result['status'] = 'recommended'; $result['description'] .= sprintf( '<p>%s</p>', __( 'If you are still seeing this warning after having tried the actions below, you may need to contact your hosting provider for further assistance.' ) ); if ( ! function_exists( 'got_mod_rewrite' ) ) { require_once ABSPATH . 'wp-admin/includes/misc.php'; } if ( got_mod_rewrite() ) { $result['actions'] .= sprintf( '<p><a href="%s">%s</a></p>', esc_url( admin_url( 'options-permalink.php' ) ), __( 'Flush permalinks' ) ); } else { $result['actions'] .= sprintf( '<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>', __( 'https://developer.wordpress.org/rest-api/frequently-asked-questions/#why-is-authentication-not-working' ), __( 'Learn how to configure the Authorization header.' ), /* translators: Accessibility text. */ __( '(opens in a new tab)' ) ); } return $result; } /** * Tests if a full page cache is available. * * @since 6.1.0 * * @return array The test result. */ public function get_test_page_cache() { $description = '<p>' . __( 'Page cache enhances the speed and performance of your site by saving and serving static pages instead of calling for a page every time a user visits.' ) . '</p>'; $description .= '<p>' . __( 'Page cache is detected by looking for an active page cache plugin as well as making three requests to the homepage and looking for one or more of the following HTTP client caching response headers:' ) . '</p>'; $description .= '<code>' . implode( '</code>, <code>', array_keys( $this->get_page_cache_headers() ) ) . '.</code>'; $result = array( 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => wp_kses_post( $description ), 'test' => 'page_cache', 'status' => 'good', 'label' => '', 'actions' => sprintf( '<p><a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s <span class="screen-reader-text">%3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>', __( 'https://wordpress.org/support/article/optimization/#Caching' ), __( 'Learn more about page cache' ), /* translators: Accessibility text. */ __( '(opens in a new tab)' ) ), ); $page_cache_detail = $this->get_page_cache_detail(); if ( is_wp_error( $page_cache_detail ) ) { $result['label'] = __( 'Unable to detect the presence of page cache' ); $result['status'] = 'recommended'; $error_info = sprintf( /* translators: 1: Error message, 2: Error code. */ __( 'Unable to detect page cache due to possible loopback request problem. Please verify that the loopback request test is passing. Error: %1$s (Code: %2$s)' ), $page_cache_detail->get_error_message(), $page_cache_detail->get_error_code() ); $result['description'] = wp_kses_post( "<p>$error_info</p>" ) . $result['description']; return $result; } $result['status'] = $page_cache_detail['status']; switch ( $page_cache_detail['status'] ) { case 'recommended': $result['label'] = __( 'Page cache is not detected but the server response time is OK' ); break; case 'good': $result['label'] = __( 'Page cache is detected and the server response time is good' ); break; default: if ( empty( $page_cache_detail['headers'] ) && ! $page_cache_detail['advanced_cache_present'] ) { $result['label'] = __( 'Page cache is not detected and the server response time is slow' ); } else { $result['label'] = __( 'Page cache is detected but the server response time is still slow' ); } } $page_cache_test_summary = array(); if ( empty( $page_cache_detail['response_time'] ) ) { $page_cache_test_summary[] = '<span class="dashicons dashicons-dismiss"></span> ' . __( 'Server response time could not be determined. Verify that loopback requests are working.' ); } else { $threshold = $this->get_good_response_time_threshold(); if ( $page_cache_detail['response_time'] < $threshold ) { $page_cache_test_summary[] = '<span class="dashicons dashicons-yes-alt"></span> ' . sprintf( /* translators: 1: The response time in milliseconds, 2: The recommended threshold in milliseconds. */ __( 'Median server response time was %1$s milliseconds. This is less than the recommended %2$s milliseconds threshold.' ), number_format_i18n( $page_cache_detail['response_time'] ), number_format_i18n( $threshold ) ); } else { $page_cache_test_summary[] = '<span class="dashicons dashicons-warning"></span> ' . sprintf( /* translators: 1: The response time in milliseconds, 2: The recommended threshold in milliseconds. */ __( 'Median server response time was %1$s milliseconds. It should be less than the recommended %2$s milliseconds threshold.' ), number_format_i18n( $page_cache_detail['response_time'] ), number_format_i18n( $threshold ) ); } if ( empty( $page_cache_detail['headers'] ) ) { $page_cache_test_summary[] = '<span class="dashicons dashicons-warning"></span> ' . __( 'No client caching response headers were detected.' ); } else { $headers_summary = '<span class="dashicons dashicons-yes-alt"></span>'; $headers_summary .= ' ' . sprintf( /* translators: %d: Number of caching headers. */ _n( 'There was %d client caching response header detected:', 'There were %d client caching response headers detected:', count( $page_cache_detail['headers'] ) ), count( $page_cache_detail['headers'] ) ); $headers_summary .= ' <code>' . implode( '</code>, <code>', $page_cache_detail['headers'] ) . '</code>.'; $page_cache_test_summary[] = $headers_summary; } } if ( $page_cache_detail['advanced_cache_present'] ) { $page_cache_test_summary[] = '<span class="dashicons dashicons-yes-alt"></span> ' . __( 'A page cache plugin was detected.' ); } elseif ( ! ( is_array( $page_cache_detail ) && ! empty( $page_cache_detail['headers'] ) ) ) { // Note: This message is not shown if client caching response headers were present since an external caching layer may be employed. $page_cache_test_summary[] = '<span class="dashicons dashicons-warning"></span> ' . __( 'A page cache plugin was not detected.' ); } $result['description'] .= '<ul><li>' . implode( '</li><li>', $page_cache_test_summary ) . '</li></ul>'; return $result; } /** * Tests if the site uses persistent object cache and recommends to use it if not. * * @since 6.1.0 * * @return array The test result. */ public function get_test_persistent_object_cache() { /** * Filters the action URL for the persistent object cache health check. * * @since 6.1.0 * * @param string $action_url Learn more link for persistent object cache health check. */ $action_url = apply_filters( 'site_status_persistent_object_cache_url', /* translators: Localized Support reference. */ __( 'https://wordpress.org/support/article/optimization/#persistent-object-cache' ) ); $result = array( 'test' => 'persistent_object_cache', 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'label' => __( 'A persistent object cache is being used' ), 'description' => sprintf( '<p>%s</p>', __( 'A persistent object cache makes your site&#8217;s database more efficient, resulting in faster load times because WordPress can retrieve your site&#8217;s content and settings much more quickly.' ) ), 'actions' => sprintf( '<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>', esc_url( $action_url ), __( 'Learn more about persistent object caching.' ), /* translators: Accessibility text. */ __( '(opens in a new tab)' ) ), ); if ( wp_using_ext_object_cache() ) { return $result; } if ( ! $this->should_suggest_persistent_object_cache() ) { $result['label'] = __( 'A persistent object cache is not required' ); return $result; } $available_services = $this->available_object_cache_services(); $notes = __( 'Your hosting provider can tell you if a persistent object cache can be enabled on your site.' ); if ( ! empty( $available_services ) ) { $notes .= ' ' . sprintf( /* translators: Available object caching services. */ __( 'Your host appears to support the following object caching services: %s.' ), implode( ', ', $available_services ) ); } /** * Filters the second paragraph of the health check's description * when suggesting the use of a persistent object cache. * * Hosts may want to replace the notes to recommend their preferred object caching solution. * * Plugin authors may want to append notes (not replace) on why object caching is recommended for their plugin. * * @since 6.1.0 * * @param string $notes The notes appended to the health check description. * @param string[] $available_services The list of available persistent object cache services. */ $notes = apply_filters( 'site_status_persistent_object_cache_notes', $notes, $available_services ); $result['status'] = 'recommended'; $result['label'] = __( 'You should use a persistent object cache' ); $result['description'] .= sprintf( '<p>%s</p>', wp_kses( $notes, array( 'a' => array( 'href' => true ), 'code' => true, 'em' => true, 'strong' => true, ) ) ); return $result; } /** * Returns a set of tests that belong to the site status page. * * Each site status test is defined here, they may be `direct` tests, that run on page load, or `async` tests * which will run later down the line via JavaScript calls to improve page performance and hopefully also user * experiences. * * @since 5.2.0 * @since 5.6.0 Added support for `has_rest` and `permissions`. * * @return array The list of tests to run. */ public static function get_tests() { $tests = array( 'direct' => array( 'wordpress_version' => array( 'label' => __( 'WordPress Version' ), 'test' => 'wordpress_version', ), 'plugin_version' => array( 'label' => __( 'Plugin Versions' ), 'test' => 'plugin_version', ), 'theme_version' => array( 'label' => __( 'Theme Versions' ), 'test' => 'theme_version', ), 'php_version' => array( 'label' => __( 'PHP Version' ), 'test' => 'php_version', ), 'php_extensions' => array( 'label' => __( 'PHP Extensions' ), 'test' => 'php_extensions', ), 'php_default_timezone' => array( 'label' => __( 'PHP Default Timezone' ), 'test' => 'php_default_timezone', ), 'php_sessions' => array( 'label' => __( 'PHP Sessions' ), 'test' => 'php_sessions', ), 'sql_server' => array( 'label' => __( 'Database Server version' ), 'test' => 'sql_server', ), 'utf8mb4_support' => array( 'label' => __( 'MySQL utf8mb4 support' ), 'test' => 'utf8mb4_support', ), 'ssl_support' => array( 'label' => __( 'Secure communication' ), 'test' => 'ssl_support', ), 'scheduled_events' => array( 'label' => __( 'Scheduled events' ), 'test' => 'scheduled_events', ), 'http_requests' => array( 'label' => __( 'HTTP Requests' ), 'test' => 'http_requests', ), 'rest_availability' => array( 'label' => __( 'REST API availability' ), 'test' => 'rest_availability', 'skip_cron' => true, ), 'debug_enabled' => array( 'label' => __( 'Debugging enabled' ), 'test' => 'is_in_debug_mode', ), 'file_uploads' => array( 'label' => __( 'File uploads' ), 'test' => 'file_uploads', ), 'plugin_theme_auto_updates' => array( 'label' => __( 'Plugin and theme auto-updates' ), 'test' => 'plugin_theme_auto_updates', ), ), 'async' => array( 'dotorg_communication' => array( 'label' => __( 'Communication with WordPress.org' ), 'test' => rest_url( 'wp-site-health/v1/tests/dotorg-communication' ), 'has_rest' => true, 'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_dotorg_communication' ), ), 'background_updates' => array( 'label' => __( 'Background updates' ), 'test' => rest_url( 'wp-site-health/v1/tests/background-updates' ), 'has_rest' => true, 'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_background_updates' ), ), 'loopback_requests' => array( 'label' => __( 'Loopback request' ), 'test' => rest_url( 'wp-site-health/v1/tests/loopback-requests' ), 'has_rest' => true, 'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_loopback_requests' ), ), 'https_status' => array( 'label' => __( 'HTTPS status' ), 'test' => rest_url( 'wp-site-health/v1/tests/https-status' ), 'has_rest' => true, 'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_https_status' ), ), ), ); // Conditionally include Authorization header test if the site isn't protected by Basic Auth. if ( ! wp_is_site_protected_by_basic_auth() ) { $tests['async']['authorization_header'] = array( 'label' => __( 'Authorization header' ), 'test' => rest_url( 'wp-site-health/v1/tests/authorization-header' ), 'has_rest' => true, 'headers' => array( 'Authorization' => 'Basic ' . base64_encode( 'user:pwd' ) ), 'skip_cron' => true, ); } // Only check for caches in production environments. if ( 'production' === wp_get_environment_type() ) { $tests['async']['page_cache'] = array( 'label' => __( 'Page cache' ), 'test' => rest_url( 'wp-site-health/v1/tests/page-cache' ), 'has_rest' => true, 'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_page_cache' ), ); $tests['direct']['persistent_object_cache'] = array( 'label' => __( 'Persistent object cache' ), 'test' => 'persistent_object_cache', ); } /** * Filters which site status tests are run on a site. * * The site health is determined by a set of tests based on best practices from * both the WordPress Hosting Team and web standards in general. * * Some sites may not have the same requirements, for example the automatic update * checks may be handled by a host, and are therefore disabled in core. * Or maybe you want to introduce a new test, is caching enabled/disabled/stale for example. * * Tests may be added either as direct, or asynchronous ones. Any test that may require some time * to complete should run asynchronously, to avoid extended loading periods within wp-admin. * * @since 5.2.0 * @since 5.6.0 Added the `async_direct_test` array key for asynchronous tests. * Added the `skip_cron` array key for all tests. * * @param array[] $tests { * An associative array of direct and asynchronous tests. * * @type array[] $direct { * An array of direct tests. * * @type array ...$identifier { * `$identifier` should be a unique identifier for the test. Plugins and themes are encouraged to * prefix test identifiers with their slug to avoid collisions between tests. * * @type string $label The friendly label to identify the test. * @type callable $test The callback function that runs the test and returns its result. * @type bool $skip_cron Whether to skip this test when running as cron. * } * } * @type array[] $async { * An array of asynchronous tests. * * @type array ...$identifier { * `$identifier` should be a unique identifier for the test. Plugins and themes are encouraged to * prefix test identifiers with their slug to avoid collisions between tests. * * @type string $label The friendly label to identify the test. * @type string $test An admin-ajax.php action to be called to perform the test, or * if `$has_rest` is true, a URL to a REST API endpoint to perform * the test. * @type bool $has_rest Whether the `$test` property points to a REST API endpoint. * @type bool $skip_cron Whether to skip this test when running as cron. * @type callable $async_direct_test A manner of directly calling the test marked as asynchronous, * as the scheduled event can not authenticate, and endpoints * may require authentication. * } * } * } */ $tests = apply_filters( 'site_status_tests', $tests ); // Ensure that the filtered tests contain the required array keys. $tests = array_merge( array( 'direct' => array(), 'async' => array(), ), $tests ); return $tests; } /** * Adds a class to the body HTML tag. * * Filters the body class string for admin pages and adds our own class for easier styling. * * @since 5.2.0 * * @param string $body_class The body class string. * @return string The modified body class string. */ public function admin_body_class( $body_class ) { $screen = get_current_screen(); if ( 'site-health' !== $screen->id ) { return $body_class; } $body_class .= ' site-health'; return $body_class; } /** * Initiates the WP_Cron schedule test cases. * * @since 5.2.0 */ private function wp_schedule_test_init() { $this->schedules = wp_get_schedules(); $this->get_cron_tasks(); } /** * Populates the list of cron events and store them to a class-wide variable. * * @since 5.2.0 */ private function get_cron_tasks() { $cron_tasks = _get_cron_array(); if ( empty( $cron_tasks ) ) { $this->crons = new WP_Error( 'no_tasks', __( 'No scheduled events exist on this site.' ) ); return; } $this->crons = array(); foreach ( $cron_tasks as $time => $cron ) { foreach ( $cron as $hook => $dings ) { foreach ( $dings as $sig => $data ) { $this->crons[ "$hook-$sig-$time" ] = (object) array( 'hook' => $hook, 'time' => $time, 'sig' => $sig, 'args' => $data['args'], 'schedule' => $data['schedule'], 'interval' => isset( $data['interval'] ) ? $data['interval'] : null, ); } } } } /** * Checks if any scheduled tasks have been missed. * * Returns a boolean value of `true` if a scheduled task has been missed and ends processing. * * If the list of crons is an instance of WP_Error, returns the instance instead of a boolean value. * * @since 5.2.0 * * @return bool|WP_Error True if a cron was missed, false if not. WP_Error if the cron is set to that. */ public function has_missed_cron() { if ( is_wp_error( $this->crons ) ) { return $this->crons; } foreach ( $this->crons as $id => $cron ) { if ( ( $cron->time - time() ) < $this->timeout_missed_cron ) { $this->last_missed_cron = $cron->hook; return true; } } return false; } /** * Checks if any scheduled tasks are late. * * Returns a boolean value of `true` if a scheduled task is late and ends processing. * * If the list of crons is an instance of WP_Error, returns the instance instead of a boolean value. * * @since 5.3.0 * * @return bool|WP_Error True if a cron is late, false if not. WP_Error if the cron is set to that. */ public function has_late_cron() { if ( is_wp_error( $this->crons ) ) { return $this->crons; } foreach ( $this->crons as $id => $cron ) { $cron_offset = $cron->time - time(); if ( $cron_offset >= $this->timeout_missed_cron && $cron_offset < $this->timeout_late_cron ) { $this->last_late_cron = $cron->hook; return true; } } return false; } /** * Checks for potential issues with plugin and theme auto-updates. * * Though there is no way to 100% determine if plugin and theme auto-updates are configured * correctly, a few educated guesses could be made to flag any conditions that would * potentially cause unexpected behaviors. * * @since 5.5.0 * * @return object The test results. */ public function detect_plugin_theme_auto_update_issues() { $mock_plugin = (object) array( 'id' => 'w.org/plugins/a-fake-plugin', 'slug' => 'a-fake-plugin', 'plugin' => 'a-fake-plugin/a-fake-plugin.php', 'new_version' => '9.9', 'url' => 'https://wordpress.org/plugins/a-fake-plugin/', 'package' => 'https://downloads.wordpress.org/plugin/a-fake-plugin.9.9.zip', 'icons' => array( '2x' => 'https://ps.w.org/a-fake-plugin/assets/icon-256x256.png', '1x' => 'https://ps.w.org/a-fake-plugin/assets/icon-128x128.png', ), 'banners' => array( '2x' => 'https://ps.w.org/a-fake-plugin/assets/banner-1544x500.png', '1x' => 'https://ps.w.org/a-fake-plugin/assets/banner-772x250.png', ), 'banners_rtl' => array(), 'tested' => '5.5.0', 'requires_php' => '5.6.20', 'compatibility' => new stdClass(), ); $mock_theme = (object) array( 'theme' => 'a-fake-theme', 'new_version' => '9.9', 'url' => 'https://wordpress.org/themes/a-fake-theme/', 'package' => 'https://downloads.wordpress.org/theme/a-fake-theme.9.9.zip', 'requires' => '5.0.0', 'requires_php' => '5.6.20', ); $test_plugins_enabled = wp_is_auto_update_forced_for_item( 'plugin', true, $mock_plugin ); $test_themes_enabled = wp_is_auto_update_forced_for_item( 'theme', true, $mock_theme ); $ui_enabled_for_plugins = wp_is_auto_update_enabled_for_type( 'plugin' ); $ui_enabled_for_themes = wp_is_auto_update_enabled_for_type( 'theme' ); $plugin_filter_present = has_filter( 'auto_update_plugin' ); $theme_filter_present = has_filter( 'auto_update_theme' ); if ( ( ! $test_plugins_enabled && $ui_enabled_for_plugins ) || ( ! $test_themes_enabled && $ui_enabled_for_themes ) ) { return (object) array( 'status' => 'critical', 'message' => __( 'Auto-updates for plugins and/or themes appear to be disabled, but settings are still set to be displayed. This could cause auto-updates to not work as expected.' ), ); } if ( ( ! $test_plugins_enabled && $plugin_filter_present ) && ( ! $test_themes_enabled && $theme_filter_present ) ) { return (object) array( 'status' => 'recommended', 'message' => __( 'Auto-updates for plugins and themes appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ), ); } elseif ( ! $test_plugins_enabled && $plugin_filter_present ) { return (object) array( 'status' => 'recommended', 'message' => __( 'Auto-updates for plugins appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ), ); } elseif ( ! $test_themes_enabled && $theme_filter_present ) { return (object) array( 'status' => 'recommended', 'message' => __( 'Auto-updates for themes appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ), ); } return (object) array( 'status' => 'good', 'message' => __( 'There appear to be no issues with plugin and theme auto-updates.' ), ); } /** * Runs a loopback test on the site. * * Loopbacks are what WordPress uses to communicate with itself to start up WP_Cron, scheduled posts, * make sure plugin or theme edits don't cause site failures and similar. * * @since 5.2.0 * * @return object The test results. */ public function can_perform_loopback() { $body = array( 'site-health' => 'loopback-test' ); $cookies = wp_unslash( $_COOKIE ); $timeout = 10; // 10 seconds. $headers = array( 'Cache-Control' => 'no-cache', ); /** This filter is documented in wp-includes/class-wp-http-streams.php */ $sslverify = apply_filters( 'https_local_ssl_verify', false ); // Include Basic auth in loopback requests. if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) { $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) ); } $url = site_url( 'wp-cron.php' ); /* * A post request is used for the wp-cron.php loopback test to cause the file * to finish early without triggering cron jobs. This has two benefits: * - cron jobs are not triggered a second time on the site health page, * - the loopback request finishes sooner providing a quicker result. * * Using a POST request causes the loopback to differ slightly to the standard * GET request WordPress uses for wp-cron.php loopback requests but is close * enough. See https://core.trac.wordpress.org/ticket/52547 */ $r = wp_remote_post( $url, compact( 'body', 'cookies', 'headers', 'timeout', 'sslverify' ) ); if ( is_wp_error( $r ) ) { return (object) array( 'status' => 'critical', 'message' => sprintf( '%s<br>%s', __( 'The loopback request to your site failed, this means features relying on them are not currently working as expected.' ), sprintf( /* translators: 1: The WordPress error message. 2: The WordPress error code. */ __( 'Error: %1$s (%2$s)' ), $r->get_error_message(), $r->get_error_code() ) ), ); } if ( 200 !== wp_remote_retrieve_response_code( $r ) ) { return (object) array( 'status' => 'recommended', 'message' => sprintf( /* translators: %d: The HTTP response code returned. */ __( 'The loopback request returned an unexpected http status code, %d, it was not possible to determine if this will prevent features from working as expected.' ), wp_remote_retrieve_response_code( $r ) ), ); } return (object) array( 'status' => 'good', 'message' => __( 'The loopback request to your site completed successfully.' ), ); } /** * Creates a weekly cron event, if one does not already exist. * * @since 5.4.0 */ public function maybe_create_scheduled_event() { if ( ! wp_next_scheduled( 'wp_site_health_scheduled_check' ) && ! wp_installing() ) { wp_schedule_event( time() + DAY_IN_SECONDS, 'weekly', 'wp_site_health_scheduled_check' ); } } /** * Runs the scheduled event to check and update the latest site health status for the website. * * @since 5.4.0 */ public function wp_cron_scheduled_check() { // Bootstrap wp-admin, as WP_Cron doesn't do this for us. require_once trailingslashit( ABSPATH ) . 'wp-admin/includes/admin.php'; $tests = WP_Site_Health::get_tests(); $results = array(); $site_status = array( 'good' => 0, 'recommended' => 0, 'critical' => 0, ); // Don't run https test on development environments. if ( $this->is_development_environment() ) { unset( $tests['async']['https_status'] ); } foreach ( $tests['direct'] as $test ) { if ( ! empty( $test['skip_cron'] ) ) { continue; } if ( is_string( $test['test'] ) ) { $test_function = sprintf( 'get_test_%s', $test['test'] ); if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) { $results[] = $this->perform_test( array( $this, $test_function ) ); continue; } } if ( is_callable( $test['test'] ) ) { $results[] = $this->perform_test( $test['test'] ); } } foreach ( $tests['async'] as $test ) { if ( ! empty( $test['skip_cron'] ) ) { continue; } // Local endpoints may require authentication, so asynchronous tests can pass a direct test runner as well. if ( ! empty( $test['async_direct_test'] ) && is_callable( $test['async_direct_test'] ) ) { // This test is callable, do so and continue to the next asynchronous check. $results[] = $this->perform_test( $test['async_direct_test'] ); continue; } if ( is_string( $test['test'] ) ) { // Check if this test has a REST API endpoint. if ( isset( $test['has_rest'] ) && $test['has_rest'] ) { $result_fetch = wp_remote_get( $test['test'], array( 'body' => array( '_wpnonce' => wp_create_nonce( 'wp_rest' ), ), ) ); } else { $result_fetch = wp_remote_post( admin_url( 'admin-ajax.php' ), array( 'body' => array( 'action' => $test['test'], '_wpnonce' => wp_create_nonce( 'health-check-site-status' ), ), ) ); } if ( ! is_wp_error( $result_fetch ) && 200 === wp_remote_retrieve_response_code( $result_fetch ) ) { $result = json_decode( wp_remote_retrieve_body( $result_fetch ), true ); } else { $result = false; } if ( is_array( $result ) ) { $results[] = $result; } else { $results[] = array( 'status' => 'recommended', 'label' => __( 'A test is unavailable' ), ); } } } foreach ( $results as $result ) { if ( 'critical' === $result['status'] ) { $site_status['critical']++; } elseif ( 'recommended' === $result['status'] ) { $site_status['recommended']++; } else { $site_status['good']++; } } set_transient( 'health-check-site-status-result', wp_json_encode( $site_status ) ); } /** * Checks if the current environment type is set to 'development' or 'local'. * * @since 5.6.0 * * @return bool True if it is a development environment, false if not. */ public function is_development_environment() { return in_array( wp_get_environment_type(), array( 'development', 'local' ), true ); } /** * Returns a list of headers and its verification callback to verify if page cache is enabled or not. * * Note: key is header name and value could be callable function to verify header value. * Empty value mean existence of header detect page cache is enabled. * * @since 6.1.0 * * @return array List of client caching headers and their (optional) verification callbacks. */ public function get_page_cache_headers() { $cache_hit_callback = static function ( $header_value ) { return false !== strpos( strtolower( $header_value ), 'hit' ); }; $cache_headers = array( 'cache-control' => static function ( $header_value ) { return (bool) preg_match( '/max-age=[1-9]/', $header_value ); }, 'expires' => static function ( $header_value ) { return strtotime( $header_value ) > time(); }, 'age' => static function ( $header_value ) { return is_numeric( $header_value ) && $header_value > 0; }, 'last-modified' => '', 'etag' => '', 'x-cache-enabled' => static function ( $header_value ) { return 'true' === strtolower( $header_value ); }, 'x-cache-disabled' => static function ( $header_value ) { return ( 'on' !== strtolower( $header_value ) ); }, 'x-srcache-store-status' => $cache_hit_callback, 'x-srcache-fetch-status' => $cache_hit_callback, ); /** * Filters the list of cache headers supported by core. * * @since 6.1.0 * * @param array $cache_headers Array of supported cache headers. */ return apply_filters( 'site_status_page_cache_supported_cache_headers', $cache_headers ); } /** * Checks if site has page cache enabled or not. * * @since 6.1.0 * * @return WP_Error|array { * Page cache detection details or else error information. * * @type bool $advanced_cache_present Whether a page cache plugin is present. * @type array[] $page_caching_response_headers Sets of client caching headers for the responses. * @type float[] $response_timing Response timings. * } */ private function check_for_page_caching() { /** This filter is documented in wp-includes/class-wp-http-streams.php */ $sslverify = apply_filters( 'https_local_ssl_verify', false ); $headers = array(); // Include basic auth in loopback requests. Note that this will only pass along basic auth when user is // initiating the test. If a site requires basic auth, the test will fail when it runs in WP Cron as part of // wp_site_health_scheduled_check. This logic is copied from WP_Site_Health::can_perform_loopback(). if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) { $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) ); } $caching_headers = $this->get_page_cache_headers(); $page_caching_response_headers = array(); $response_timing = array(); for ( $i = 1; $i <= 3; $i++ ) { $start_time = microtime( true ); $http_response = wp_remote_get( home_url( '/' ), compact( 'sslverify', 'headers' ) ); $end_time = microtime( true ); if ( is_wp_error( $http_response ) ) { return $http_response; } if ( wp_remote_retrieve_response_code( $http_response ) !== 200 ) { return new WP_Error( 'http_' . wp_remote_retrieve_response_code( $http_response ), wp_remote_retrieve_response_message( $http_response ) ); } $response_headers = array(); foreach ( $caching_headers as $header => $callback ) { $header_values = wp_remote_retrieve_header( $http_response, $header ); if ( empty( $header_values ) ) { continue; } $header_values = (array) $header_values; if ( empty( $callback ) || ( is_callable( $callback ) && count( array_filter( $header_values, $callback ) ) > 0 ) ) { $response_headers[ $header ] = $header_values; } } $page_caching_response_headers[] = $response_headers; $response_timing[] = ( $end_time - $start_time ) * 1000; } return array( 'advanced_cache_present' => ( file_exists( WP_CONTENT_DIR . '/advanced-cache.php' ) && ( defined( 'WP_CACHE' ) && WP_CACHE ) && /** This filter is documented in wp-settings.php */ apply_filters( 'enable_loading_advanced_cache_dropin', true ) ), 'page_caching_response_headers' => $page_caching_response_headers, 'response_timing' => $response_timing, ); } /** * Gets page cache details. * * @since 6.1.0 * * @return WP_Error|array { * Page cache detail or else a WP_Error if unable to determine. * * @type string $status Page cache status. Good, Recommended or Critical. * @type bool $advanced_cache_present Whether page cache plugin is available or not. * @type string[] $headers Client caching response headers detected. * @type float $response_time Response time of site. * } */ private function get_page_cache_detail() { $page_cache_detail = $this->check_for_page_caching(); if ( is_wp_error( $page_cache_detail ) ) { return $page_cache_detail; } // Use the median server response time. $response_timings = $page_cache_detail['response_timing']; rsort( $response_timings ); $page_speed = $response_timings[ floor( count( $response_timings ) / 2 ) ]; // Obtain unique set of all client caching response headers. $headers = array(); foreach ( $page_cache_detail['page_caching_response_headers'] as $page_caching_response_headers ) { $headers = array_merge( $headers, array_keys( $page_caching_response_headers ) ); } $headers = array_unique( $headers ); // Page cache is detected if there are response headers or a page cache plugin is present. $has_page_caching = ( count( $headers ) > 0 || $page_cache_detail['advanced_cache_present'] ); if ( $page_speed && $page_speed < $this->get_good_response_time_threshold() ) { $result = $has_page_caching ? 'good' : 'recommended'; } else { $result = 'critical'; } return array( 'status' => $result, 'advanced_cache_present' => $page_cache_detail['advanced_cache_present'], 'headers' => $headers, 'response_time' => $page_speed, ); } /** * Gets the threshold below which a response time is considered good. * * @since 6.1.0 * * @return int Threshold in milliseconds. */ private function get_good_response_time_threshold() { /** * Filters the threshold below which a response time is considered good. * * The default is based on https://web.dev/time-to-first-byte/. * * @param int $threshold Threshold in milliseconds. Default 600. * * @since 6.1.0 */ return (int) apply_filters( 'site_status_good_response_time_threshold', 600 ); } /** * Determines whether to suggest using a persistent object cache. * * @since 6.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @return bool Whether to suggest using a persistent object cache. */ public function should_suggest_persistent_object_cache() { global $wpdb; /** * Filters whether to suggest use of a persistent object cache and bypass default threshold checks. * * Using this filter allows to override the default logic, effectively short-circuiting the method. * * @since 6.1.0 * * @param bool|null $suggest Boolean to short-circuit, for whether to suggest using a persistent object cache. * Default null. */ $short_circuit = apply_filters( 'site_status_should_suggest_persistent_object_cache', null ); if ( is_bool( $short_circuit ) ) { return $short_circuit; } if ( is_multisite() ) { return true; } /** * Filters the thresholds used to determine whether to suggest the use of a persistent object cache. * * @since 6.1.0 * * @param int[] $thresholds The list of threshold numbers keyed by threshold name. */ $thresholds = apply_filters( 'site_status_persistent_object_cache_thresholds', array( 'alloptions_count' => 500, 'alloptions_bytes' => 100000, 'comments_count' => 1000, 'options_count' => 1000, 'posts_count' => 1000, 'terms_count' => 1000, 'users_count' => 1000, ) ); $alloptions = wp_load_alloptions(); if ( $thresholds['alloptions_count'] < count( $alloptions ) ) { return true; } if ( $thresholds['alloptions_bytes'] < strlen( serialize( $alloptions ) ) ) { return true; } $table_names = implode( "','", array( $wpdb->comments, $wpdb->options, $wpdb->posts, $wpdb->terms, $wpdb->users ) ); // With InnoDB the `TABLE_ROWS` are estimates, which are accurate enough and faster to retrieve than individual `COUNT()` queries. $results = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- This query cannot use interpolation. "SELECT TABLE_NAME AS 'table', TABLE_ROWS AS 'rows', SUM(data_length + index_length) as 'bytes' FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME IN ('$table_names') GROUP BY TABLE_NAME;", DB_NAME ), OBJECT_K ); $threshold_map = array( 'comments_count' => $wpdb->comments, 'options_count' => $wpdb->options, 'posts_count' => $wpdb->posts, 'terms_count' => $wpdb->terms, 'users_count' => $wpdb->users, ); foreach ( $threshold_map as $threshold => $table ) { if ( $thresholds[ $threshold ] <= $results[ $table ]->rows ) { return true; } } return false; } /** * Returns a list of available persistent object cache services. * * @since 6.1.0 * * @return string[] The list of available persistent object cache services. */ private function available_object_cache_services() { $extensions = array_map( 'extension_loaded', array( 'APCu' => 'apcu', 'Redis' => 'redis', 'Relay' => 'relay', 'Memcache' => 'memcache', 'Memcached' => 'memcached', ) ); $services = array_keys( array_filter( $extensions ) ); /** * Filters the persistent object cache services available to the user. * * This can be useful to hide or add services not included in the defaults. * * @since 6.1.0 * * @param string[] $services The list of available persistent object cache services. */ return apply_filters( 'site_status_available_object_cache_services', $services ); } } ``` | Version | Description | | --- | --- | | [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
programming_docs
wordpress class WP_HTTP_Fsockopen {} class WP\_HTTP\_Fsockopen {} ============================ This class has been deprecated. Use [WP\_HTTP::request()](wp_http/request) instead. Deprecated HTTP Transport method which used fsockopen. This class is not used, and is included for backward compatibility only. All code should make use of [WP\_Http](wp_http) directly through its API. * [WP\_HTTP::request()](wp_http/request) File: `wp-includes/class-wp-http-streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-streams.php/) ``` class WP_HTTP_Fsockopen extends WP_Http_Streams { // For backward compatibility for users who are using the class directly. } ``` | Uses | Description | | --- | --- | | [WP\_Http\_Streams](wp_http_streams) wp-includes/class-wp-http-streams.php | Core class used to integrate PHP Streams as an HTTP transport. | | Version | Description | | --- | --- | | [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Please use [WP\_HTTP::request()](wp_http/request) directly | | [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. | wordpress class WP_Customize_Nav_Menus_Panel {} class WP\_Customize\_Nav\_Menus\_Panel {} ========================================= Customize Nav Menus Panel Class Needed to add screen options. * [WP\_Customize\_Panel](wp_customize_panel) * [check\_capabilities](wp_customize_nav_menus_panel/check_capabilities) β€” Checks required user capabilities and whether the theme has the feature support required by the panel. * [content\_template](wp_customize_nav_menus_panel/content_template) β€” An Underscore (JS) template for this panel's content (but not its container). * [render\_screen\_options](wp_customize_nav_menus_panel/render_screen_options) β€” Render screen options for Menus. * [wp\_nav\_menu\_manage\_columns](wp_customize_nav_menus_panel/wp_nav_menu_manage_columns) β€” Returns the advanced options for the nav menus page. β€” deprecated File: `wp-includes/customize/class-wp-customize-nav-menus-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menus-panel.php/) ``` class WP_Customize_Nav_Menus_Panel extends WP_Customize_Panel { /** * Control type. * * @since 4.3.0 * @var string */ public $type = 'nav_menus'; /** * Render screen options for Menus. * * @since 4.3.0 */ public function render_screen_options() { // Adds the screen options. require_once ABSPATH . 'wp-admin/includes/nav-menu.php'; add_filter( 'manage_nav-menus_columns', 'wp_nav_menu_manage_columns' ); // Display screen options. $screen = WP_Screen::get( 'nav-menus.php' ); $screen->render_screen_options( array( 'wrap' => false ) ); } /** * Returns the advanced options for the nav menus page. * * Link title attribute added as it's a relatively advanced concept for new users. * * @since 4.3.0 * @deprecated 4.5.0 Deprecated in favor of wp_nav_menu_manage_columns(). */ public function wp_nav_menu_manage_columns() { _deprecated_function( __METHOD__, '4.5.0', 'wp_nav_menu_manage_columns' ); require_once ABSPATH . 'wp-admin/includes/nav-menu.php'; return wp_nav_menu_manage_columns(); } /** * An Underscore (JS) template for this panel's content (but not its container). * * Class variables for this panel class are available in the `data` JS object; * export custom variables by overriding WP_Customize_Panel::json(). * * @since 4.3.0 * * @see WP_Customize_Panel::print_template() */ protected function content_template() { ?> <li class="panel-meta customize-info accordion-section <# if ( ! data.description ) { #> cannot-expand<# } #>"> <button type="button" class="customize-panel-back" tabindex="-1"> <span class="screen-reader-text"><?php _e( 'Back' ); ?></span> </button> <div class="accordion-section-title"> <span class="preview-notice"> <?php /* translators: %s: The site/panel title in the Customizer. */ printf( __( 'You are customizing %s' ), '<strong class="panel-title">{{ data.title }}</strong>' ); ?> </span> <button type="button" class="customize-help-toggle dashicons dashicons-editor-help" aria-expanded="false"> <span class="screen-reader-text"><?php _e( 'Help' ); ?></span> </button> <button type="button" class="customize-screen-options-toggle" aria-expanded="false"> <span class="screen-reader-text"><?php _e( 'Menu Options' ); ?></span> </button> </div> <# if ( data.description ) { #> <div class="description customize-panel-description">{{{ data.description }}}</div> <# } #> <div id="screen-options-wrap"> <?php $this->render_screen_options(); ?> </div> </li> <?php // NOTE: The following is a workaround for an inability to treat (and thus label) a list of sections as a whole. ?> <li class="customize-control-title customize-section-title-nav_menus-heading"><?php _e( 'Menus' ); ?></li> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Panel](wp_customize_panel) wp-includes/class-wp-customize-panel.php | Customize Panel class. | | Version | Description | | --- | --- | | [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. | wordpress class IXR_IntrospectionServer {} class IXR\_IntrospectionServer {} ================================= [IXR\_IntrospectionServer](ixr_introspectionserver) * [\_\_construct](ixr_introspectionserver/__construct) β€” PHP5 constructor. * [addCallback](ixr_introspectionserver/addcallback) * [call](ixr_introspectionserver/call) * [IXR\_IntrospectionServer](ixr_introspectionserver/ixr_introspectionserver) β€” PHP4 constructor. * [methodHelp](ixr_introspectionserver/methodhelp) * [methodSignature](ixr_introspectionserver/methodsignature) File: `wp-includes/IXR/class-IXR-introspectionserver.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-introspectionserver.php/) ``` class IXR_IntrospectionServer extends IXR_Server { var $signatures; var $help; /** * PHP5 constructor. */ function __construct() { $this->setCallbacks(); $this->setCapabilities(); $this->capabilities['introspection'] = array( 'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html', 'specVersion' => 1 ); $this->addCallback( 'system.methodSignature', 'this:methodSignature', array('array', 'string'), 'Returns an array describing the return type and required parameters of a method' ); $this->addCallback( 'system.getCapabilities', 'this:getCapabilities', array('struct'), 'Returns a struct describing the XML-RPC specifications supported by this server' ); $this->addCallback( 'system.listMethods', 'this:listMethods', array('array'), 'Returns an array of available methods on this server' ); $this->addCallback( 'system.methodHelp', 'this:methodHelp', array('string', 'string'), 'Returns a documentation string for the specified method' ); } /** * PHP4 constructor. */ public function IXR_IntrospectionServer() { self::__construct(); } function addCallback($method, $callback, $args, $help) { $this->callbacks[$method] = $callback; $this->signatures[$method] = $args; $this->help[$method] = $help; } function call($methodname, $args) { // Make sure it's in an array if ($args && !is_array($args)) { $args = array($args); } // Over-rides default call method, adds signature check if (!$this->hasMethod($methodname)) { return new IXR_Error(-32601, 'server error. requested method "'.$this->message->methodName.'" not specified.'); } $method = $this->callbacks[$methodname]; $signature = $this->signatures[$methodname]; $returnType = array_shift($signature); // Check the number of arguments if (count($args) != count($signature)) { return new IXR_Error(-32602, 'server error. wrong number of method parameters'); } // Check the argument types $ok = true; $argsbackup = $args; for ($i = 0, $j = count($args); $i < $j; $i++) { $arg = array_shift($args); $type = array_shift($signature); switch ($type) { case 'int': case 'i4': if (is_array($arg) || !is_int($arg)) { $ok = false; } break; case 'base64': case 'string': if (!is_string($arg)) { $ok = false; } break; case 'boolean': if ($arg !== false && $arg !== true) { $ok = false; } break; case 'float': case 'double': if (!is_float($arg)) { $ok = false; } break; case 'date': case 'dateTime.iso8601': if (!is_a($arg, 'IXR_Date')) { $ok = false; } break; } if (!$ok) { return new IXR_Error(-32602, 'server error. invalid method parameters'); } } // It passed the test - run the "real" method call return parent::call($methodname, $argsbackup); } function methodSignature($method) { if (!$this->hasMethod($method)) { return new IXR_Error(-32601, 'server error. requested method "'.$method.'" not specified.'); } // We should be returning an array of types $types = $this->signatures[$method]; $return = array(); foreach ($types as $type) { switch ($type) { case 'string': $return[] = 'string'; break; case 'int': case 'i4': $return[] = 42; break; case 'double': $return[] = 3.1415; break; case 'dateTime.iso8601': $return[] = new IXR_Date(time()); break; case 'boolean': $return[] = true; break; case 'base64': $return[] = new IXR_Base64('base64'); break; case 'array': $return[] = array('array'); break; case 'struct': $return[] = array('struct' => 'struct'); break; } } return $return; } function methodHelp($method) { return $this->help[$method]; } } ``` | Uses | Description | | --- | --- | | [IXR\_Server](ixr_server) wp-includes/IXR/class-IXR-server.php | [IXR\_Server](ixr_server) | | Version | Description | | --- | --- | | [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. | wordpress class WP_REST_Site_Health_Controller {} class WP\_REST\_Site\_Health\_Controller {} =========================================== Core class for interacting with Site Health tests. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_site_health_controller/__construct) β€” Site Health controller constructor. * [get\_directory\_sizes](wp_rest_site_health_controller/get_directory_sizes) β€” Gets the current directory sizes for this install. * [get\_item\_schema](wp_rest_site_health_controller/get_item_schema) β€” Gets the schema for each site health test. * [load\_admin\_textdomain](wp_rest_site_health_controller/load_admin_textdomain) β€” Loads the admin textdomain for Site Health tests. * [register\_routes](wp_rest_site_health_controller/register_routes) β€” Registers API routes. * [test\_authorization\_header](wp_rest_site_health_controller/test_authorization_header) β€” Checks that the authorization header is valid. * [test\_background\_updates](wp_rest_site_health_controller/test_background_updates) β€” Checks if background updates work as expected. * [test\_dotorg\_communication](wp_rest_site_health_controller/test_dotorg_communication) β€” Checks that the site can reach the WordPress.org API. * [test\_https\_status](wp_rest_site_health_controller/test_https_status) β€” Checks that the site's frontend can be accessed over HTTPS. * [test\_loopback\_requests](wp_rest_site_health_controller/test_loopback_requests) β€” Checks that loopbacks can be performed. * [test\_page\_cache](wp_rest_site_health_controller/test_page_cache) β€” Checks that full page cache is active. * [validate\_request\_permission](wp_rest_site_health_controller/validate_request_permission) β€” Validates if the current user can request this REST endpoint. File: `wp-includes/rest-api/endpoints/class-wp-rest-site-health-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-site-health-controller.php/) ``` class WP_REST_Site_Health_Controller extends WP_REST_Controller { /** * An instance of the site health class. * * @since 5.6.0 * * @var WP_Site_Health */ private $site_health; /** * Site Health controller constructor. * * @since 5.6.0 * * @param WP_Site_Health $site_health An instance of the site health class. */ public function __construct( $site_health ) { $this->namespace = 'wp-site-health/v1'; $this->rest_base = 'tests'; $this->site_health = $site_health; } /** * Registers API routes. * * @since 5.6.0 * @since 6.1.0 Adds page-cache async test. * * @see register_rest_route() */ public function register_routes() { register_rest_route( $this->namespace, sprintf( '/%s/%s', $this->rest_base, 'background-updates' ), array( array( 'methods' => 'GET', 'callback' => array( $this, 'test_background_updates' ), 'permission_callback' => function () { return $this->validate_request_permission( 'background_updates' ); }, ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, sprintf( '/%s/%s', $this->rest_base, 'loopback-requests' ), array( array( 'methods' => 'GET', 'callback' => array( $this, 'test_loopback_requests' ), 'permission_callback' => function () { return $this->validate_request_permission( 'loopback_requests' ); }, ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, sprintf( '/%s/%s', $this->rest_base, 'https-status' ), array( array( 'methods' => 'GET', 'callback' => array( $this, 'test_https_status' ), 'permission_callback' => function () { return $this->validate_request_permission( 'https_status' ); }, ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, sprintf( '/%s/%s', $this->rest_base, 'dotorg-communication' ), array( array( 'methods' => 'GET', 'callback' => array( $this, 'test_dotorg_communication' ), 'permission_callback' => function () { return $this->validate_request_permission( 'dotorg_communication' ); }, ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, sprintf( '/%s/%s', $this->rest_base, 'authorization-header' ), array( array( 'methods' => 'GET', 'callback' => array( $this, 'test_authorization_header' ), 'permission_callback' => function () { return $this->validate_request_permission( 'authorization_header' ); }, ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, sprintf( '/%s', 'directory-sizes' ), array( 'methods' => 'GET', 'callback' => array( $this, 'get_directory_sizes' ), 'permission_callback' => function() { return $this->validate_request_permission( 'debug_enabled' ) && ! is_multisite(); }, ) ); register_rest_route( $this->namespace, sprintf( '/%s/%s', $this->rest_base, 'page-cache' ), array( array( 'methods' => 'GET', 'callback' => array( $this, 'test_page_cache' ), 'permission_callback' => function () { return $this->validate_request_permission( 'view_site_health_checks' ); }, ), ) ); } /** * Validates if the current user can request this REST endpoint. * * @since 5.6.0 * * @param string $check The endpoint check being ran. * @return bool */ protected function validate_request_permission( $check ) { $default_capability = 'view_site_health_checks'; /** * Filters the capability needed to run a given Site Health check. * * @since 5.6.0 * * @param string $default_capability The default capability required for this check. * @param string $check The Site Health check being performed. */ $capability = apply_filters( "site_health_test_rest_capability_{$check}", $default_capability, $check ); return current_user_can( $capability ); } /** * Checks if background updates work as expected. * * @since 5.6.0 * * @return array */ public function test_background_updates() { $this->load_admin_textdomain(); return $this->site_health->get_test_background_updates(); } /** * Checks that the site can reach the WordPress.org API. * * @since 5.6.0 * * @return array */ public function test_dotorg_communication() { $this->load_admin_textdomain(); return $this->site_health->get_test_dotorg_communication(); } /** * Checks that loopbacks can be performed. * * @since 5.6.0 * * @return array */ public function test_loopback_requests() { $this->load_admin_textdomain(); return $this->site_health->get_test_loopback_requests(); } /** * Checks that the site's frontend can be accessed over HTTPS. * * @since 5.7.0 * * @return array */ public function test_https_status() { $this->load_admin_textdomain(); return $this->site_health->get_test_https_status(); } /** * Checks that the authorization header is valid. * * @since 5.6.0 * * @return array */ public function test_authorization_header() { $this->load_admin_textdomain(); return $this->site_health->get_test_authorization_header(); } /** * Checks that full page cache is active. * * @since 6.1.0 * * @return array The test result. */ public function test_page_cache() { $this->load_admin_textdomain(); return $this->site_health->get_test_page_cache(); } /** * Gets the current directory sizes for this install. * * @since 5.6.0 * * @return array|WP_Error */ public function get_directory_sizes() { if ( ! class_exists( 'WP_Debug_Data' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-debug-data.php'; } $this->load_admin_textdomain(); $sizes_data = WP_Debug_Data::get_sizes(); $all_sizes = array( 'raw' => 0 ); foreach ( $sizes_data as $name => $value ) { $name = sanitize_text_field( $name ); $data = array(); if ( isset( $value['size'] ) ) { if ( is_string( $value['size'] ) ) { $data['size'] = sanitize_text_field( $value['size'] ); } else { $data['size'] = (int) $value['size']; } } if ( isset( $value['debug'] ) ) { if ( is_string( $value['debug'] ) ) { $data['debug'] = sanitize_text_field( $value['debug'] ); } else { $data['debug'] = (int) $value['debug']; } } if ( ! empty( $value['raw'] ) ) { $data['raw'] = (int) $value['raw']; } $all_sizes[ $name ] = $data; } if ( isset( $all_sizes['total_size']['debug'] ) && 'not available' === $all_sizes['total_size']['debug'] ) { return new WP_Error( 'not_available', __( 'Directory sizes could not be returned.' ), array( 'status' => 500 ) ); } return $all_sizes; } /** * Loads the admin textdomain for Site Health tests. * * The {@see WP_Site_Health} class is defined in WP-Admin, while the REST API operates in a front-end context. * This means that the translations for Site Health won't be loaded by default in {@see load_default_textdomain()}. * * @since 5.6.0 */ protected function load_admin_textdomain() { // Accounts for inner REST API requests in the admin. if ( ! is_admin() ) { $locale = determine_locale(); load_textdomain( 'default', WP_LANG_DIR . "/admin-$locale.mo" ); } } /** * Gets the schema for each site health test. * * @since 5.6.0 * * @return array The test schema. */ public function get_item_schema() { if ( $this->schema ) { return $this->schema; } $this->schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'wp-site-health-test', 'type' => 'object', 'properties' => array( 'test' => array( 'type' => 'string', 'description' => __( 'The name of the test being run.' ), 'readonly' => true, ), 'label' => array( 'type' => 'string', 'description' => __( 'A label describing the test.' ), 'readonly' => true, ), 'status' => array( 'type' => 'string', 'description' => __( 'The status of the test.' ), 'enum' => array( 'good', 'recommended', 'critical' ), 'readonly' => true, ), 'badge' => array( 'type' => 'object', 'description' => __( 'The category this test is grouped in.' ), 'properties' => array( 'label' => array( 'type' => 'string', 'readonly' => true, ), 'color' => array( 'type' => 'string', 'enum' => array( 'blue', 'orange', 'red', 'green', 'purple', 'gray' ), 'readonly' => true, ), ), 'readonly' => true, ), 'description' => array( 'type' => 'string', 'description' => __( 'A more descriptive explanation of what the test looks for, and why it is important for the user.' ), 'readonly' => true, ), 'actions' => array( 'type' => 'string', 'description' => __( 'HTML containing an action to direct the user to where they can resolve the issue.' ), 'readonly' => true, ), ), ); return $this->schema; } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Server {} class WP\_REST\_Server {} ========================= Core class used to implement the WordPress REST API server. * [\_\_construct](wp_rest_server/__construct) β€” Instantiates the REST server. * [add\_active\_theme\_link\_to\_index](wp_rest_server/add_active_theme_link_to_index) β€” Adds a link to the active theme for users who have proper permissions. * [add\_image\_to\_index](wp_rest_server/add_image_to_index) β€” Exposes an image through the WordPress REST API. * [add\_site\_icon\_to\_index](wp_rest_server/add_site_icon_to_index) β€” Exposes the site icon through the WordPress REST API. * [add\_site\_logo\_to\_index](wp_rest_server/add_site_logo_to_index) β€” Exposes the site logo through the WordPress REST API. * [check\_authentication](wp_rest_server/check_authentication) β€” Checks the authentication headers if supplied. * [dispatch](wp_rest_server/dispatch) β€” Matches the request to a callback and call it. * [embed\_links](wp_rest_server/embed_links) β€” Embeds the links from the data into the request. * [envelope\_response](wp_rest_server/envelope_response) β€” Wraps the response in an envelope. * [error\_to\_response](wp_rest_server/error_to_response) β€” Converts an error to a response object. * [get\_compact\_response\_links](wp_rest_server/get_compact_response_links) β€” Retrieves the CURIEs (compact URIs) used for relations. * [get\_data\_for\_route](wp_rest_server/get_data_for_route) β€” Retrieves publicly-visible data for the route. * [get\_data\_for\_routes](wp_rest_server/get_data_for_routes) β€” Retrieves the publicly-visible data for routes. * [get\_headers](wp_rest_server/get_headers) β€” Extracts headers from a PHP-style $\_SERVER array. * [get\_index](wp_rest_server/get_index) β€” Retrieves the site index. * [get\_json\_encode\_options](wp_rest_server/get_json_encode_options) β€” Gets the encoding options passed to {@see wp\_json\_encode}. * [get\_json\_last\_error](wp_rest_server/get_json_last_error) β€” Returns if an error occurred during most recent JSON encode/decode. * [get\_max\_batch\_size](wp_rest_server/get_max_batch_size) β€” Gets the maximum number of requests that can be included in a batch. * [get\_namespace\_index](wp_rest_server/get_namespace_index) β€” Retrieves the index for a namespace. * [get\_namespaces](wp_rest_server/get_namespaces) β€” Retrieves namespaces registered on the server. * [get\_raw\_data](wp_rest_server/get_raw_data) β€” Retrieves the raw request entity (body). * [get\_response\_links](wp_rest_server/get_response_links) β€” Retrieves links from a response. * [get\_route\_options](wp_rest_server/get_route_options) β€” Retrieves specified options for a route. * [get\_routes](wp_rest_server/get_routes) β€” Retrieves the route map. * [json\_error](wp_rest_server/json_error) β€” Retrieves an appropriate error representation in JSON. * [match\_request\_to\_handler](wp_rest_server/match_request_to_handler) β€” Matches a request object to its handler. * [register\_route](wp_rest_server/register_route) β€” Registers a route to the server. * [remove\_header](wp_rest_server/remove_header) β€” Removes an HTTP header from the current response. * [respond\_to\_request](wp_rest_server/respond_to_request) β€” Dispatches the request to the callback handler. * [response\_to\_data](wp_rest_server/response_to_data) β€” Converts a response to data to send. * [send\_header](wp_rest_server/send_header) β€” Sends an HTTP header. * [send\_headers](wp_rest_server/send_headers) β€” Sends multiple HTTP headers. * [serve\_batch\_request\_v1](wp_rest_server/serve_batch_request_v1) β€” Serves the batch/v1 request. * [serve\_request](wp_rest_server/serve_request) β€” Handles serving a REST API request. * [set\_status](wp_rest_server/set_status) β€” Sends an HTTP status code. File: `wp-includes/rest-api/class-wp-rest-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-server.php/) ``` class WP_REST_Server { /** * Alias for GET transport method. * * @since 4.4.0 * @var string */ const READABLE = 'GET'; /** * Alias for POST transport method. * * @since 4.4.0 * @var string */ const CREATABLE = 'POST'; /** * Alias for POST, PUT, PATCH transport methods together. * * @since 4.4.0 * @var string */ const EDITABLE = 'POST, PUT, PATCH'; /** * Alias for DELETE transport method. * * @since 4.4.0 * @var string */ const DELETABLE = 'DELETE'; /** * Alias for GET, POST, PUT, PATCH & DELETE transport methods together. * * @since 4.4.0 * @var string */ const ALLMETHODS = 'GET, POST, PUT, PATCH, DELETE'; /** * Namespaces registered to the server. * * @since 4.4.0 * @var array */ protected $namespaces = array(); /** * Endpoints registered to the server. * * @since 4.4.0 * @var array */ protected $endpoints = array(); /** * Options defined for the routes. * * @since 4.4.0 * @var array */ protected $route_options = array(); /** * Caches embedded requests. * * @since 5.4.0 * @var array */ protected $embed_cache = array(); /** * Instantiates the REST server. * * @since 4.4.0 */ public function __construct() { $this->endpoints = array( // Meta endpoints. '/' => array( 'callback' => array( $this, 'get_index' ), 'methods' => 'GET', 'args' => array( 'context' => array( 'default' => 'view', ), ), ), '/batch/v1' => array( 'callback' => array( $this, 'serve_batch_request_v1' ), 'methods' => 'POST', 'args' => array( 'validation' => array( 'type' => 'string', 'enum' => array( 'require-all-validate', 'normal' ), 'default' => 'normal', ), 'requests' => array( 'required' => true, 'type' => 'array', 'maxItems' => $this->get_max_batch_size(), 'items' => array( 'type' => 'object', 'properties' => array( 'method' => array( 'type' => 'string', 'enum' => array( 'POST', 'PUT', 'PATCH', 'DELETE' ), 'default' => 'POST', ), 'path' => array( 'type' => 'string', 'required' => true, ), 'body' => array( 'type' => 'object', 'properties' => array(), 'additionalProperties' => true, ), 'headers' => array( 'type' => 'object', 'properties' => array(), 'additionalProperties' => array( 'type' => array( 'string', 'array' ), 'items' => array( 'type' => 'string', ), ), ), ), ), ), ), ), ); } /** * Checks the authentication headers if supplied. * * @since 4.4.0 * * @return WP_Error|null WP_Error indicates unsuccessful login, null indicates successful * or no authentication provided */ public function check_authentication() { /** * Filters REST API authentication errors. * * This is used to pass a WP_Error from an authentication method back to * the API. * * Authentication methods should check first if they're being used, as * multiple authentication methods can be enabled on a site (cookies, * HTTP basic auth, OAuth). If the authentication method hooked in is * not actually being attempted, null should be returned to indicate * another authentication method should check instead. Similarly, * callbacks should ensure the value is `null` before checking for * errors. * * A WP_Error instance can be returned if an error occurs, and this should * match the format used by API methods internally (that is, the `status` * data should be used). A callback can return `true` to indicate that * the authentication method was used, and it succeeded. * * @since 4.4.0 * * @param WP_Error|null|true $errors WP_Error if authentication error, null if authentication * method wasn't used, true if authentication succeeded. */ return apply_filters( 'rest_authentication_errors', null ); } /** * Converts an error to a response object. * * This iterates over all error codes and messages to change it into a flat * array. This enables simpler client behaviour, as it is represented as a * list in JSON rather than an object/map. * * @since 4.4.0 * @since 5.7.0 Converted to a wrapper of {@see rest_convert_error_to_response()}. * * @param WP_Error $error WP_Error instance. * @return WP_REST_Response List of associative arrays with code and message keys. */ protected function error_to_response( $error ) { return rest_convert_error_to_response( $error ); } /** * Retrieves an appropriate error representation in JSON. * * Note: This should only be used in WP_REST_Server::serve_request(), as it * cannot handle WP_Error internally. All callbacks and other internal methods * should instead return a WP_Error with the data set to an array that includes * a 'status' key, with the value being the HTTP status to send. * * @since 4.4.0 * * @param string $code WP_Error-style code. * @param string $message Human-readable message. * @param int $status Optional. HTTP status code to send. Default null. * @return string JSON representation of the error */ protected function json_error( $code, $message, $status = null ) { if ( $status ) { $this->set_status( $status ); } $error = compact( 'code', 'message' ); return wp_json_encode( $error ); } /** * Gets the encoding options passed to {@see wp_json_encode}. * * @since 6.1.0 * * @param \WP_REST_Request $request The current request object. * * @return int The JSON encode options. */ protected function get_json_encode_options( WP_REST_Request $request ) { $options = 0; if ( $request->has_param( '_pretty' ) ) { $options |= JSON_PRETTY_PRINT; } /** * Filters the JSON encoding options used to send the REST API response. * * @since 6.1.0 * * @param int $options JSON encoding options {@see json_encode()}. * @param WP_REST_Request $request Current request object. */ return apply_filters( 'rest_json_encode_options', $options, $request ); } /** * Handles serving a REST API request. * * Matches the current server URI to a route and runs the first matching * callback then outputs a JSON representation of the returned value. * * @since 4.4.0 * * @see WP_REST_Server::dispatch() * * @global WP_User $current_user The currently authenticated user. * * @param string $path Optional. The request route. If not set, `$_SERVER['PATH_INFO']` will be used. * Default null. * @return null|false Null if not served and a HEAD request, false otherwise. */ public function serve_request( $path = null ) { /* @var WP_User|null $current_user */ global $current_user; if ( $current_user instanceof WP_User && ! $current_user->exists() ) { /* * If there is no current user authenticated via other means, clear * the cached lack of user, so that an authenticate check can set it * properly. * * This is done because for authentications such as Application * Passwords, we don't want it to be accepted unless the current HTTP * request is a REST API request, which can't always be identified early * enough in evaluation. */ $current_user = null; } /** * Filters whether JSONP is enabled for the REST API. * * @since 4.4.0 * * @param bool $jsonp_enabled Whether JSONP is enabled. Default true. */ $jsonp_enabled = apply_filters( 'rest_jsonp_enabled', true ); $jsonp_callback = false; if ( isset( $_GET['_jsonp'] ) ) { $jsonp_callback = $_GET['_jsonp']; } $content_type = ( $jsonp_callback && $jsonp_enabled ) ? 'application/javascript' : 'application/json'; $this->send_header( 'Content-Type', $content_type . '; charset=' . get_option( 'blog_charset' ) ); $this->send_header( 'X-Robots-Tag', 'noindex' ); $api_root = get_rest_url(); if ( ! empty( $api_root ) ) { $this->send_header( 'Link', '<' . sanitize_url( $api_root ) . '>; rel="https://api.w.org/"' ); } /* * Mitigate possible JSONP Flash attacks. * * https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/ */ $this->send_header( 'X-Content-Type-Options', 'nosniff' ); $expose_headers = array( 'X-WP-Total', 'X-WP-TotalPages', 'Link' ); /** * Filters the list of response headers that are exposed to REST API CORS requests. * * @since 5.5.0 * * @param string[] $expose_headers The list of response headers to expose. */ $expose_headers = apply_filters( 'rest_exposed_cors_headers', $expose_headers ); $this->send_header( 'Access-Control-Expose-Headers', implode( ', ', $expose_headers ) ); $allow_headers = array( 'Authorization', 'X-WP-Nonce', 'Content-Disposition', 'Content-MD5', 'Content-Type', ); /** * Filters the list of request headers that are allowed for REST API CORS requests. * * The allowed headers are passed to the browser to specify which * headers can be passed to the REST API. By default, we allow the * Content-* headers needed to upload files to the media endpoints. * As well as the Authorization and Nonce headers for allowing authentication. * * @since 5.5.0 * * @param string[] $allow_headers The list of request headers to allow. */ $allow_headers = apply_filters( 'rest_allowed_cors_headers', $allow_headers ); $this->send_header( 'Access-Control-Allow-Headers', implode( ', ', $allow_headers ) ); /** * Filters whether to send nocache headers on a REST API request. * * @since 4.4.0 * * @param bool $rest_send_nocache_headers Whether to send no-cache headers. */ $send_no_cache_headers = apply_filters( 'rest_send_nocache_headers', is_user_logged_in() ); if ( $send_no_cache_headers ) { foreach ( wp_get_nocache_headers() as $header => $header_value ) { if ( empty( $header_value ) ) { $this->remove_header( $header ); } else { $this->send_header( $header, $header_value ); } } } /** * Filters whether the REST API is enabled. * * @since 4.4.0 * @deprecated 4.7.0 Use the {@see 'rest_authentication_errors'} filter to * restrict access to the REST API. * * @param bool $rest_enabled Whether the REST API is enabled. Default true. */ apply_filters_deprecated( 'rest_enabled', array( true ), '4.7.0', 'rest_authentication_errors', sprintf( /* translators: %s: rest_authentication_errors */ __( 'The REST API can no longer be completely disabled, the %s filter can be used to restrict access to the API, instead.' ), 'rest_authentication_errors' ) ); if ( $jsonp_callback ) { if ( ! $jsonp_enabled ) { echo $this->json_error( 'rest_callback_disabled', __( 'JSONP support is disabled on this site.' ), 400 ); return false; } if ( ! wp_check_jsonp_callback( $jsonp_callback ) ) { echo $this->json_error( 'rest_callback_invalid', __( 'Invalid JSONP callback function.' ), 400 ); return false; } } if ( empty( $path ) ) { if ( isset( $_SERVER['PATH_INFO'] ) ) { $path = $_SERVER['PATH_INFO']; } else { $path = '/'; } } $request = new WP_REST_Request( $_SERVER['REQUEST_METHOD'], $path ); $request->set_query_params( wp_unslash( $_GET ) ); $request->set_body_params( wp_unslash( $_POST ) ); $request->set_file_params( $_FILES ); $request->set_headers( $this->get_headers( wp_unslash( $_SERVER ) ) ); $request->set_body( self::get_raw_data() ); /* * HTTP method override for clients that can't use PUT/PATCH/DELETE. First, we check * $_GET['_method']. If that is not set, we check for the HTTP_X_HTTP_METHOD_OVERRIDE * header. */ if ( isset( $_GET['_method'] ) ) { $request->set_method( $_GET['_method'] ); } elseif ( isset( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ) ) { $request->set_method( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ); } $result = $this->check_authentication(); if ( ! is_wp_error( $result ) ) { $result = $this->dispatch( $request ); } // Normalize to either WP_Error or WP_REST_Response... $result = rest_ensure_response( $result ); // ...then convert WP_Error across. if ( is_wp_error( $result ) ) { $result = $this->error_to_response( $result ); } /** * Filters the REST API response. * * Allows modification of the response before returning. * * @since 4.4.0 * @since 4.5.0 Applied to embedded responses. * * @param WP_HTTP_Response $result Result to send to the client. Usually a `WP_REST_Response`. * @param WP_REST_Server $server Server instance. * @param WP_REST_Request $request Request used to generate the response. */ $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $request ); // Wrap the response in an envelope if asked for. if ( isset( $_GET['_envelope'] ) ) { $embed = isset( $_GET['_embed'] ) ? rest_parse_embed_param( $_GET['_embed'] ) : false; $result = $this->envelope_response( $result, $embed ); } // Send extra data from response objects. $headers = $result->get_headers(); $this->send_headers( $headers ); $code = $result->get_status(); $this->set_status( $code ); /** * Filters whether the REST API request has already been served. * * Allow sending the request manually - by returning true, the API result * will not be sent to the client. * * @since 4.4.0 * * @param bool $served Whether the request has already been served. * Default false. * @param WP_HTTP_Response $result Result to send to the client. Usually a `WP_REST_Response`. * @param WP_REST_Request $request Request used to generate the response. * @param WP_REST_Server $server Server instance. */ $served = apply_filters( 'rest_pre_serve_request', false, $result, $request, $this ); if ( ! $served ) { if ( 'HEAD' === $request->get_method() ) { return null; } // Embed links inside the request. $embed = isset( $_GET['_embed'] ) ? rest_parse_embed_param( $_GET['_embed'] ) : false; $result = $this->response_to_data( $result, $embed ); /** * Filters the REST API response. * * Allows modification of the response data after inserting * embedded data (if any) and before echoing the response data. * * @since 4.8.1 * * @param array $result Response data to send to the client. * @param WP_REST_Server $server Server instance. * @param WP_REST_Request $request Request used to generate the response. */ $result = apply_filters( 'rest_pre_echo_response', $result, $this, $request ); // The 204 response shouldn't have a body. if ( 204 === $code || null === $result ) { return null; } $result = wp_json_encode( $result, $this->get_json_encode_options( $request ) ); $json_error_message = $this->get_json_last_error(); if ( $json_error_message ) { $this->set_status( 500 ); $json_error_obj = new WP_Error( 'rest_encode_error', $json_error_message, array( 'status' => 500 ) ); $result = $this->error_to_response( $json_error_obj ); $result = wp_json_encode( $result->data, $this->get_json_encode_options( $request ) ); } if ( $jsonp_callback ) { // Prepend '/**/' to mitigate possible JSONP Flash attacks. // https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/ echo '/**/' . $jsonp_callback . '(' . $result . ')'; } else { echo $result; } } return null; } /** * Converts a response to data to send. * * @since 4.4.0 * @since 5.4.0 The $embed parameter can now contain a list of link relations to include. * * @param WP_REST_Response $response Response object. * @param bool|string[] $embed Whether to embed all links, a filtered list of link relations, or no links. * @return array { * Data with sub-requests embedded. * * @type array $_links Links. * @type array $_embedded Embedded objects. * } */ public function response_to_data( $response, $embed ) { $data = $response->get_data(); $links = self::get_compact_response_links( $response ); if ( ! empty( $links ) ) { // Convert links to part of the data. $data['_links'] = $links; } if ( $embed ) { $this->embed_cache = array(); // Determine if this is a numeric array. if ( wp_is_numeric_array( $data ) ) { foreach ( $data as $key => $item ) { $data[ $key ] = $this->embed_links( $item, $embed ); } } else { $data = $this->embed_links( $data, $embed ); } $this->embed_cache = array(); } return $data; } /** * Retrieves links from a response. * * Extracts the links from a response into a structured hash, suitable for * direct output. * * @since 4.4.0 * * @param WP_REST_Response $response Response to extract links from. * @return array Map of link relation to list of link hashes. */ public static function get_response_links( $response ) { $links = $response->get_links(); if ( empty( $links ) ) { return array(); } // Convert links to part of the data. $data = array(); foreach ( $links as $rel => $items ) { $data[ $rel ] = array(); foreach ( $items as $item ) { $attributes = $item['attributes']; $attributes['href'] = $item['href']; $data[ $rel ][] = $attributes; } } return $data; } /** * Retrieves the CURIEs (compact URIs) used for relations. * * Extracts the links from a response into a structured hash, suitable for * direct output. * * @since 4.5.0 * * @param WP_REST_Response $response Response to extract links from. * @return array Map of link relation to list of link hashes. */ public static function get_compact_response_links( $response ) { $links = self::get_response_links( $response ); if ( empty( $links ) ) { return array(); } $curies = $response->get_curies(); $used_curies = array(); foreach ( $links as $rel => $items ) { // Convert $rel URIs to their compact versions if they exist. foreach ( $curies as $curie ) { $href_prefix = substr( $curie['href'], 0, strpos( $curie['href'], '{rel}' ) ); if ( strpos( $rel, $href_prefix ) !== 0 ) { continue; } // Relation now changes from '$uri' to '$curie:$relation'. $rel_regex = str_replace( '\{rel\}', '(.+)', preg_quote( $curie['href'], '!' ) ); preg_match( '!' . $rel_regex . '!', $rel, $matches ); if ( $matches ) { $new_rel = $curie['name'] . ':' . $matches[1]; $used_curies[ $curie['name'] ] = $curie; $links[ $new_rel ] = $items; unset( $links[ $rel ] ); break; } } } // Push the curies onto the start of the links array. if ( $used_curies ) { $links['curies'] = array_values( $used_curies ); } return $links; } /** * Embeds the links from the data into the request. * * @since 4.4.0 * @since 5.4.0 The $embed parameter can now contain a list of link relations to include. * * @param array $data Data from the request. * @param bool|string[] $embed Whether to embed all links or a filtered list of link relations. * @return array { * Data with sub-requests embedded. * * @type array $_links Links. * @type array $_embedded Embedded objects. * } */ protected function embed_links( $data, $embed = true ) { if ( empty( $data['_links'] ) ) { return $data; } $embedded = array(); foreach ( $data['_links'] as $rel => $links ) { // If a list of relations was specified, and the link relation // is not in the list of allowed relations, don't process the link. if ( is_array( $embed ) && ! in_array( $rel, $embed, true ) ) { continue; } $embeds = array(); foreach ( $links as $item ) { // Determine if the link is embeddable. if ( empty( $item['embeddable'] ) ) { // Ensure we keep the same order. $embeds[] = array(); continue; } if ( ! array_key_exists( $item['href'], $this->embed_cache ) ) { // Run through our internal routing and serve. $request = WP_REST_Request::from_url( $item['href'] ); if ( ! $request ) { $embeds[] = array(); continue; } // Embedded resources get passed context=embed. if ( empty( $request['context'] ) ) { $request['context'] = 'embed'; } $response = $this->dispatch( $request ); /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */ $response = apply_filters( 'rest_post_dispatch', rest_ensure_response( $response ), $this, $request ); $this->embed_cache[ $item['href'] ] = $this->response_to_data( $response, false ); } $embeds[] = $this->embed_cache[ $item['href'] ]; } // Determine if any real links were found. $has_links = count( array_filter( $embeds ) ); if ( $has_links ) { $embedded[ $rel ] = $embeds; } } if ( ! empty( $embedded ) ) { $data['_embedded'] = $embedded; } return $data; } /** * Wraps the response in an envelope. * * The enveloping technique is used to work around browser/client * compatibility issues. Essentially, it converts the full HTTP response to * data instead. * * @since 4.4.0 * @since 6.0.0 The $embed parameter can now contain a list of link relations to include * * @param WP_REST_Response $response Response object. * @param bool|string[] $embed Whether to embed all links, a filtered list of link relations, or no links. * @return WP_REST_Response New response with wrapped data */ public function envelope_response( $response, $embed ) { $envelope = array( 'body' => $this->response_to_data( $response, $embed ), 'status' => $response->get_status(), 'headers' => $response->get_headers(), ); /** * Filters the enveloped form of a REST API response. * * @since 4.4.0 * * @param array $envelope { * Envelope data. * * @type array $body Response data. * @type int $status The 3-digit HTTP status code. * @type array $headers Map of header name to header value. * } * @param WP_REST_Response $response Original response data. */ $envelope = apply_filters( 'rest_envelope_response', $envelope, $response ); // Ensure it's still a response and return. return rest_ensure_response( $envelope ); } /** * Registers a route to the server. * * @since 4.4.0 * * @param string $namespace Namespace. * @param string $route The REST route. * @param array $route_args Route arguments. * @param bool $override Optional. Whether the route should be overridden if it already exists. * Default false. */ public function register_route( $namespace, $route, $route_args, $override = false ) { if ( ! isset( $this->namespaces[ $namespace ] ) ) { $this->namespaces[ $namespace ] = array(); $this->register_route( $namespace, '/' . $namespace, array( array( 'methods' => self::READABLE, 'callback' => array( $this, 'get_namespace_index' ), 'args' => array( 'namespace' => array( 'default' => $namespace, ), 'context' => array( 'default' => 'view', ), ), ), ) ); } // Associative to avoid double-registration. $this->namespaces[ $namespace ][ $route ] = true; $route_args['namespace'] = $namespace; if ( $override || empty( $this->endpoints[ $route ] ) ) { $this->endpoints[ $route ] = $route_args; } else { $this->endpoints[ $route ] = array_merge( $this->endpoints[ $route ], $route_args ); } } /** * Retrieves the route map. * * The route map is an associative array with path regexes as the keys. The * value is an indexed array with the callback function/method as the first * item, and a bitmask of HTTP methods as the second item (see the class * constants). * * Each route can be mapped to more than one callback by using an array of * the indexed arrays. This allows mapping e.g. GET requests to one callback * and POST requests to another. * * Note that the path regexes (array keys) must have @ escaped, as this is * used as the delimiter with preg_match() * * @since 4.4.0 * @since 5.4.0 Add $namespace parameter. * * @param string $namespace Optionally, only return routes in the given namespace. * @return array `'/path/regex' => array( $callback, $bitmask )` or * `'/path/regex' => array( array( $callback, $bitmask ), ...)`. */ public function get_routes( $namespace = '' ) { $endpoints = $this->endpoints; if ( $namespace ) { $endpoints = wp_list_filter( $endpoints, array( 'namespace' => $namespace ) ); } /** * Filters the array of available REST API endpoints. * * @since 4.4.0 * * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped * to an array of callbacks for the endpoint. These take the format * `'/path/regex' => array( $callback, $bitmask )` or * `'/path/regex' => array( array( $callback, $bitmask ). */ $endpoints = apply_filters( 'rest_endpoints', $endpoints ); // Normalize the endpoints. $defaults = array( 'methods' => '', 'accept_json' => false, 'accept_raw' => false, 'show_in_index' => true, 'args' => array(), ); foreach ( $endpoints as $route => &$handlers ) { if ( isset( $handlers['callback'] ) ) { // Single endpoint, add one deeper. $handlers = array( $handlers ); } if ( ! isset( $this->route_options[ $route ] ) ) { $this->route_options[ $route ] = array(); } foreach ( $handlers as $key => &$handler ) { if ( ! is_numeric( $key ) ) { // Route option, move it to the options. $this->route_options[ $route ][ $key ] = $handler; unset( $handlers[ $key ] ); continue; } $handler = wp_parse_args( $handler, $defaults ); // Allow comma-separated HTTP methods. if ( is_string( $handler['methods'] ) ) { $methods = explode( ',', $handler['methods'] ); } elseif ( is_array( $handler['methods'] ) ) { $methods = $handler['methods']; } else { $methods = array(); } $handler['methods'] = array(); foreach ( $methods as $method ) { $method = strtoupper( trim( $method ) ); $handler['methods'][ $method ] = true; } } } return $endpoints; } /** * Retrieves namespaces registered on the server. * * @since 4.4.0 * * @return string[] List of registered namespaces. */ public function get_namespaces() { return array_keys( $this->namespaces ); } /** * Retrieves specified options for a route. * * @since 4.4.0 * * @param string $route Route pattern to fetch options for. * @return array|null Data as an associative array if found, or null if not found. */ public function get_route_options( $route ) { if ( ! isset( $this->route_options[ $route ] ) ) { return null; } return $this->route_options[ $route ]; } /** * Matches the request to a callback and call it. * * @since 4.4.0 * * @param WP_REST_Request $request Request to attempt dispatching. * @return WP_REST_Response Response returned by the callback. */ public function dispatch( $request ) { /** * Filters the pre-calculated result of a REST API dispatch request. * * Allow hijacking the request before dispatching by returning a non-empty. The returned value * will be used to serve the request instead. * * @since 4.4.0 * * @param mixed $result Response to replace the requested version with. Can be anything * a normal endpoint can return, or null to not hijack the request. * @param WP_REST_Server $server Server instance. * @param WP_REST_Request $request Request used to generate the response. */ $result = apply_filters( 'rest_pre_dispatch', null, $this, $request ); if ( ! empty( $result ) ) { return $result; } $error = null; $matched = $this->match_request_to_handler( $request ); if ( is_wp_error( $matched ) ) { return $this->error_to_response( $matched ); } list( $route, $handler ) = $matched; if ( ! is_callable( $handler['callback'] ) ) { $error = new WP_Error( 'rest_invalid_handler', __( 'The handler for the route is invalid.' ), array( 'status' => 500 ) ); } if ( ! is_wp_error( $error ) ) { $check_required = $request->has_valid_params(); if ( is_wp_error( $check_required ) ) { $error = $check_required; } else { $check_sanitized = $request->sanitize_params(); if ( is_wp_error( $check_sanitized ) ) { $error = $check_sanitized; } } } return $this->respond_to_request( $request, $route, $handler, $error ); } /** * Matches a request object to its handler. * * @access private * @since 5.6.0 * * @param WP_REST_Request $request The request object. * @return array|WP_Error The route and request handler on success or a WP_Error instance if no handler was found. */ protected function match_request_to_handler( $request ) { $method = $request->get_method(); $path = $request->get_route(); $with_namespace = array(); foreach ( $this->get_namespaces() as $namespace ) { if ( 0 === strpos( trailingslashit( ltrim( $path, '/' ) ), $namespace ) ) { $with_namespace[] = $this->get_routes( $namespace ); } } if ( $with_namespace ) { $routes = array_merge( ...$with_namespace ); } else { $routes = $this->get_routes(); } foreach ( $routes as $route => $handlers ) { $match = preg_match( '@^' . $route . '$@i', $path, $matches ); if ( ! $match ) { continue; } $args = array(); foreach ( $matches as $param => $value ) { if ( ! is_int( $param ) ) { $args[ $param ] = $value; } } foreach ( $handlers as $handler ) { $callback = $handler['callback']; $response = null; // Fallback to GET method if no HEAD method is registered. $checked_method = $method; if ( 'HEAD' === $method && empty( $handler['methods']['HEAD'] ) ) { $checked_method = 'GET'; } if ( empty( $handler['methods'][ $checked_method ] ) ) { continue; } if ( ! is_callable( $callback ) ) { return array( $route, $handler ); } $request->set_url_params( $args ); $request->set_attributes( $handler ); $defaults = array(); foreach ( $handler['args'] as $arg => $options ) { if ( isset( $options['default'] ) ) { $defaults[ $arg ] = $options['default']; } } $request->set_default_params( $defaults ); return array( $route, $handler ); } } return new WP_Error( 'rest_no_route', __( 'No route was found matching the URL and request method.' ), array( 'status' => 404 ) ); } /** * Dispatches the request to the callback handler. * * @access private * @since 5.6.0 * * @param WP_REST_Request $request The request object. * @param string $route The matched route regex. * @param array $handler The matched route handler. * @param WP_Error|null $response The current error object if any. * @return WP_REST_Response */ protected function respond_to_request( $request, $route, $handler, $response ) { /** * Filters the response before executing any REST API callbacks. * * Allows plugins to perform additional validation after a * request is initialized and matched to a registered route, * but before it is executed. * * Note that this filter will not be called for requests that * fail to authenticate or match to a registered route. * * @since 4.7.0 * * @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client. * Usually a WP_REST_Response or WP_Error. * @param array $handler Route handler used for the request. * @param WP_REST_Request $request Request used to generate the response. */ $response = apply_filters( 'rest_request_before_callbacks', $response, $handler, $request ); // Check permission specified on the route. if ( ! is_wp_error( $response ) && ! empty( $handler['permission_callback'] ) ) { $permission = call_user_func( $handler['permission_callback'], $request ); if ( is_wp_error( $permission ) ) { $response = $permission; } elseif ( false === $permission || null === $permission ) { $response = new WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to do that.' ), array( 'status' => rest_authorization_required_code() ) ); } } if ( ! is_wp_error( $response ) ) { /** * Filters the REST API dispatch request result. * * Allow plugins to override dispatching the request. * * @since 4.4.0 * @since 4.5.0 Added `$route` and `$handler` parameters. * * @param mixed $dispatch_result Dispatch result, will be used if not empty. * @param WP_REST_Request $request Request used to generate the response. * @param string $route Route matched for the request. * @param array $handler Route handler used for the request. */ $dispatch_result = apply_filters( 'rest_dispatch_request', null, $request, $route, $handler ); // Allow plugins to halt the request via this filter. if ( null !== $dispatch_result ) { $response = $dispatch_result; } else { $response = call_user_func( $handler['callback'], $request ); } } /** * Filters the response immediately after executing any REST API * callbacks. * * Allows plugins to perform any needed cleanup, for example, * to undo changes made during the {@see 'rest_request_before_callbacks'} * filter. * * Note that this filter will not be called for requests that * fail to authenticate or match to a registered route. * * Note that an endpoint's `permission_callback` can still be * called after this filter - see `rest_send_allow_header()`. * * @since 4.7.0 * * @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client. * Usually a WP_REST_Response or WP_Error. * @param array $handler Route handler used for the request. * @param WP_REST_Request $request Request used to generate the response. */ $response = apply_filters( 'rest_request_after_callbacks', $response, $handler, $request ); if ( is_wp_error( $response ) ) { $response = $this->error_to_response( $response ); } else { $response = rest_ensure_response( $response ); } $response->set_matched_route( $route ); $response->set_matched_handler( $handler ); return $response; } /** * Returns if an error occurred during most recent JSON encode/decode. * * Strings to be translated will be in format like * "Encoding error: Maximum stack depth exceeded". * * @since 4.4.0 * * @return false|string Boolean false or string error message. */ protected function get_json_last_error() { $last_error_code = json_last_error(); if ( JSON_ERROR_NONE === $last_error_code || empty( $last_error_code ) ) { return false; } return json_last_error_msg(); } /** * Retrieves the site index. * * This endpoint describes the capabilities of the site. * * @since 4.4.0 * * @param array $request { * Request. * * @type string $context Context. * } * @return WP_REST_Response The API root index data. */ public function get_index( $request ) { // General site data. $available = array( 'name' => get_option( 'blogname' ), 'description' => get_option( 'blogdescription' ), 'url' => get_option( 'siteurl' ), 'home' => home_url(), 'gmt_offset' => get_option( 'gmt_offset' ), 'timezone_string' => get_option( 'timezone_string' ), 'namespaces' => array_keys( $this->namespaces ), 'authentication' => array(), 'routes' => $this->get_data_for_routes( $this->get_routes(), $request['context'] ), ); $response = new WP_REST_Response( $available ); $response->add_link( 'help', 'https://developer.wordpress.org/rest-api/' ); $this->add_active_theme_link_to_index( $response ); $this->add_site_logo_to_index( $response ); $this->add_site_icon_to_index( $response ); /** * Filters the REST API root index data. * * This contains the data describing the API. This includes information * about supported authentication schemes, supported namespaces, routes * available on the API, and a small amount of data about the site. * * @since 4.4.0 * @since 6.0.0 Added `$request` parameter. * * @param WP_REST_Response $response Response data. * @param WP_REST_Request $request Request data. */ return apply_filters( 'rest_index', $response, $request ); } /** * Adds a link to the active theme for users who have proper permissions. * * @since 5.7.0 * * @param WP_REST_Response $response REST API response. */ protected function add_active_theme_link_to_index( WP_REST_Response $response ) { $should_add = current_user_can( 'switch_themes' ) || current_user_can( 'manage_network_themes' ); if ( ! $should_add && current_user_can( 'edit_posts' ) ) { $should_add = true; } if ( ! $should_add ) { foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) { if ( current_user_can( $post_type->cap->edit_posts ) ) { $should_add = true; break; } } } if ( $should_add ) { $theme = wp_get_theme(); $response->add_link( 'https://api.w.org/active-theme', rest_url( 'wp/v2/themes/' . $theme->get_stylesheet() ) ); } } /** * Exposes the site logo through the WordPress REST API. * * This is used for fetching this information when user has no rights * to update settings. * * @since 5.8.0 * * @param WP_REST_Response $response REST API response. */ protected function add_site_logo_to_index( WP_REST_Response $response ) { $site_logo_id = get_theme_mod( 'custom_logo', 0 ); $this->add_image_to_index( $response, $site_logo_id, 'site_logo' ); } /** * Exposes the site icon through the WordPress REST API. * * This is used for fetching this information when user has no rights * to update settings. * * @since 5.9.0 * * @param WP_REST_Response $response REST API response. */ protected function add_site_icon_to_index( WP_REST_Response $response ) { $site_icon_id = get_option( 'site_icon', 0 ); $this->add_image_to_index( $response, $site_icon_id, 'site_icon' ); $response->data['site_icon_url'] = get_site_icon_url(); } /** * Exposes an image through the WordPress REST API. * This is used for fetching this information when user has no rights * to update settings. * * @since 5.9.0 * * @param WP_REST_Response $response REST API response. * @param int $image_id Image attachment ID. * @param string $type Type of Image. */ protected function add_image_to_index( WP_REST_Response $response, $image_id, $type ) { $response->data[ $type ] = (int) $image_id; if ( $image_id ) { $response->add_link( 'https://api.w.org/featuredmedia', rest_url( rest_get_route_for_post( $image_id ) ), array( 'embeddable' => true, 'type' => $type, ) ); } } /** * Retrieves the index for a namespace. * * @since 4.4.0 * * @param WP_REST_Request $request REST request instance. * @return WP_REST_Response|WP_Error WP_REST_Response instance if the index was found, * WP_Error if the namespace isn't set. */ public function get_namespace_index( $request ) { $namespace = $request['namespace']; if ( ! isset( $this->namespaces[ $namespace ] ) ) { return new WP_Error( 'rest_invalid_namespace', __( 'The specified namespace could not be found.' ), array( 'status' => 404 ) ); } $routes = $this->namespaces[ $namespace ]; $endpoints = array_intersect_key( $this->get_routes(), $routes ); $data = array( 'namespace' => $namespace, 'routes' => $this->get_data_for_routes( $endpoints, $request['context'] ), ); $response = rest_ensure_response( $data ); // Link to the root index. $response->add_link( 'up', rest_url( '/' ) ); /** * Filters the REST API namespace index data. * * This typically is just the route data for the namespace, but you can * add any data you'd like here. * * @since 4.4.0 * * @param WP_REST_Response $response Response data. * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter. */ return apply_filters( 'rest_namespace_index', $response, $request ); } /** * Retrieves the publicly-visible data for routes. * * @since 4.4.0 * * @param array $routes Routes to get data for. * @param string $context Optional. Context for data. Accepts 'view' or 'help'. Default 'view'. * @return array[] Route data to expose in indexes, keyed by route. */ public function get_data_for_routes( $routes, $context = 'view' ) { $available = array(); // Find the available routes. foreach ( $routes as $route => $callbacks ) { $data = $this->get_data_for_route( $route, $callbacks, $context ); if ( empty( $data ) ) { continue; } /** * Filters the publicly-visible data for a single REST API route. * * @since 4.4.0 * * @param array $data Publicly-visible data for the route. */ $available[ $route ] = apply_filters( 'rest_endpoints_description', $data ); } /** * Filters the publicly-visible data for REST API routes. * * This data is exposed on indexes and can be used by clients or * developers to investigate the site and find out how to use it. It * acts as a form of self-documentation. * * @since 4.4.0 * * @param array[] $available Route data to expose in indexes, keyed by route. * @param array $routes Internal route data as an associative array. */ return apply_filters( 'rest_route_data', $available, $routes ); } /** * Retrieves publicly-visible data for the route. * * @since 4.4.0 * * @param string $route Route to get data for. * @param array $callbacks Callbacks to convert to data. * @param string $context Optional. Context for the data. Accepts 'view' or 'help'. Default 'view'. * @return array|null Data for the route, or null if no publicly-visible data. */ public function get_data_for_route( $route, $callbacks, $context = 'view' ) { $data = array( 'namespace' => '', 'methods' => array(), 'endpoints' => array(), ); $allow_batch = false; if ( isset( $this->route_options[ $route ] ) ) { $options = $this->route_options[ $route ]; if ( isset( $options['namespace'] ) ) { $data['namespace'] = $options['namespace']; } $allow_batch = isset( $options['allow_batch'] ) ? $options['allow_batch'] : false; if ( isset( $options['schema'] ) && 'help' === $context ) { $data['schema'] = call_user_func( $options['schema'] ); } } $allowed_schema_keywords = array_flip( rest_get_allowed_schema_keywords() ); $route = preg_replace( '#\(\?P<(\w+?)>.*?\)#', '{$1}', $route ); foreach ( $callbacks as $callback ) { // Skip to the next route if any callback is hidden. if ( empty( $callback['show_in_index'] ) ) { continue; } $data['methods'] = array_merge( $data['methods'], array_keys( $callback['methods'] ) ); $endpoint_data = array( 'methods' => array_keys( $callback['methods'] ), ); $callback_batch = isset( $callback['allow_batch'] ) ? $callback['allow_batch'] : $allow_batch; if ( $callback_batch ) { $endpoint_data['allow_batch'] = $callback_batch; } if ( isset( $callback['args'] ) ) { $endpoint_data['args'] = array(); foreach ( $callback['args'] as $key => $opts ) { if ( is_string( $opts ) ) { $opts = array( $opts => 0 ); } elseif ( ! is_array( $opts ) ) { $opts = array(); } $arg_data = array_intersect_key( $opts, $allowed_schema_keywords ); $arg_data['required'] = ! empty( $opts['required'] ); $endpoint_data['args'][ $key ] = $arg_data; } } $data['endpoints'][] = $endpoint_data; // For non-variable routes, generate links. if ( strpos( $route, '{' ) === false ) { $data['_links'] = array( 'self' => array( array( 'href' => rest_url( $route ), ), ), ); } } if ( empty( $data['methods'] ) ) { // No methods supported, hide the route. return null; } return $data; } /** * Gets the maximum number of requests that can be included in a batch. * * @since 5.6.0 * * @return int The maximum requests. */ protected function get_max_batch_size() { /** * Filters the maximum number of REST API requests that can be included in a batch. * * @since 5.6.0 * * @param int $max_size The maximum size. */ return apply_filters( 'rest_get_max_batch_size', 25 ); } /** * Serves the batch/v1 request. * * @since 5.6.0 * * @param WP_REST_Request $batch_request The batch request object. * @return WP_REST_Response The generated response object. */ public function serve_batch_request_v1( WP_REST_Request $batch_request ) { $requests = array(); foreach ( $batch_request['requests'] as $args ) { $parsed_url = wp_parse_url( $args['path'] ); if ( false === $parsed_url ) { $requests[] = new WP_Error( 'parse_path_failed', __( 'Could not parse the path.' ), array( 'status' => 400 ) ); continue; } $single_request = new WP_REST_Request( isset( $args['method'] ) ? $args['method'] : 'POST', $parsed_url['path'] ); if ( ! empty( $parsed_url['query'] ) ) { $query_args = null; // Satisfy linter. wp_parse_str( $parsed_url['query'], $query_args ); $single_request->set_query_params( $query_args ); } if ( ! empty( $args['body'] ) ) { $single_request->set_body_params( $args['body'] ); } if ( ! empty( $args['headers'] ) ) { $single_request->set_headers( $args['headers'] ); } $requests[] = $single_request; } $matches = array(); $validation = array(); $has_error = false; foreach ( $requests as $single_request ) { $match = $this->match_request_to_handler( $single_request ); $matches[] = $match; $error = null; if ( is_wp_error( $match ) ) { $error = $match; } if ( ! $error ) { list( $route, $handler ) = $match; if ( isset( $handler['allow_batch'] ) ) { $allow_batch = $handler['allow_batch']; } else { $route_options = $this->get_route_options( $route ); $allow_batch = isset( $route_options['allow_batch'] ) ? $route_options['allow_batch'] : false; } if ( ! is_array( $allow_batch ) || empty( $allow_batch['v1'] ) ) { $error = new WP_Error( 'rest_batch_not_allowed', __( 'The requested route does not support batch requests.' ), array( 'status' => 400 ) ); } } if ( ! $error ) { $check_required = $single_request->has_valid_params(); if ( is_wp_error( $check_required ) ) { $error = $check_required; } } if ( ! $error ) { $check_sanitized = $single_request->sanitize_params(); if ( is_wp_error( $check_sanitized ) ) { $error = $check_sanitized; } } if ( $error ) { $has_error = true; $validation[] = $error; } else { $validation[] = true; } } $responses = array(); if ( $has_error && 'require-all-validate' === $batch_request['validation'] ) { foreach ( $validation as $valid ) { if ( is_wp_error( $valid ) ) { $responses[] = $this->envelope_response( $this->error_to_response( $valid ), false )->get_data(); } else { $responses[] = null; } } return new WP_REST_Response( array( 'failed' => 'validation', 'responses' => $responses, ), WP_Http::MULTI_STATUS ); } foreach ( $requests as $i => $single_request ) { $clean_request = clone $single_request; $clean_request->set_url_params( array() ); $clean_request->set_attributes( array() ); $clean_request->set_default_params( array() ); /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */ $result = apply_filters( 'rest_pre_dispatch', null, $this, $clean_request ); if ( empty( $result ) ) { $match = $matches[ $i ]; $error = null; if ( is_wp_error( $validation[ $i ] ) ) { $error = $validation[ $i ]; } if ( is_wp_error( $match ) ) { $result = $this->error_to_response( $match ); } else { list( $route, $handler ) = $match; if ( ! $error && ! is_callable( $handler['callback'] ) ) { $error = new WP_Error( 'rest_invalid_handler', __( 'The handler for the route is invalid' ), array( 'status' => 500 ) ); } $result = $this->respond_to_request( $single_request, $route, $handler, $error ); } } /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */ $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $single_request ); $responses[] = $this->envelope_response( $result, false )->get_data(); } return new WP_REST_Response( array( 'responses' => $responses ), WP_Http::MULTI_STATUS ); } /** * Sends an HTTP status code. * * @since 4.4.0 * * @param int $code HTTP status. */ protected function set_status( $code ) { status_header( $code ); } /** * Sends an HTTP header. * * @since 4.4.0 * * @param string $key Header key. * @param string $value Header value. */ public function send_header( $key, $value ) { /* * Sanitize as per RFC2616 (Section 4.2): * * Any LWS that occurs between field-content MAY be replaced with a * single SP before interpreting the field value or forwarding the * message downstream. */ $value = preg_replace( '/\s+/', ' ', $value ); header( sprintf( '%s: %s', $key, $value ) ); } /** * Sends multiple HTTP headers. * * @since 4.4.0 * * @param array $headers Map of header name to header value. */ public function send_headers( $headers ) { foreach ( $headers as $key => $value ) { $this->send_header( $key, $value ); } } /** * Removes an HTTP header from the current response. * * @since 4.8.0 * * @param string $key Header key. */ public function remove_header( $key ) { header_remove( $key ); } /** * Retrieves the raw request entity (body). * * @since 4.4.0 * * @global string $HTTP_RAW_POST_DATA Raw post data. * * @return string Raw request data. */ public static function get_raw_data() { // phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved global $HTTP_RAW_POST_DATA; // $HTTP_RAW_POST_DATA was deprecated in PHP 5.6 and removed in PHP 7.0. if ( ! isset( $HTTP_RAW_POST_DATA ) ) { $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' ); } return $HTTP_RAW_POST_DATA; // phpcs:enable } /** * Extracts headers from a PHP-style $_SERVER array. * * @since 4.4.0 * * @param array $server Associative array similar to `$_SERVER`. * @return array Headers extracted from the input. */ public function get_headers( $server ) { $headers = array(); // CONTENT_* headers are not prefixed with HTTP_. $additional = array( 'CONTENT_LENGTH' => true, 'CONTENT_MD5' => true, 'CONTENT_TYPE' => true, ); foreach ( $server as $key => $value ) { if ( strpos( $key, 'HTTP_' ) === 0 ) { $headers[ substr( $key, 5 ) ] = $value; } elseif ( 'REDIRECT_HTTP_AUTHORIZATION' === $key && empty( $server['HTTP_AUTHORIZATION'] ) ) { /* * In some server configurations, the authorization header is passed in this alternate location. * Since it would not be passed in in both places we do not check for both headers and resolve. */ $headers['AUTHORIZATION'] = $value; } elseif ( isset( $additional[ $key ] ) ) { $headers[ $key ] = $value; } } return $headers; } } ``` | Version | Description | | --- | --- | | [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
programming_docs
wordpress class Requests_Session {} class Requests\_Session {} ========================== Session handler for persistent requests and default parameters Allows various options to be set as default values, and merges both the options and URL properties together. A base URL can be set for all requests, with all subrequests resolved from this. Base options can be set (including a shared cookie jar), then overridden for individual requests. * [\_\_construct](requests_session/__construct) β€” Create a new session * [\_\_get](requests_session/__get) β€” Get a property's value * [\_\_isset](requests_session/__isset) β€” Remove a property's value * [\_\_set](requests_session/__set) β€” Set a property's value * [\_\_unset](requests_session/__unset) β€” Remove a property's value * [delete](requests_session/delete) β€” Send a DELETE request * [get](requests_session/get) β€” Send a GET request * [head](requests_session/head) β€” Send a HEAD request * [merge\_request](requests_session/merge_request) β€” Merge a request's data with the default data * [patch](requests_session/patch) β€” Send a PATCH request * [post](requests_session/post) β€” Send a POST request * [put](requests_session/put) β€” Send a PUT request * [request](requests_session/request) β€” Main interface for HTTP requests * [request\_multiple](requests_session/request_multiple) β€” Send multiple HTTP requests simultaneously File: `wp-includes/Requests/Session.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/session.php/) ``` class Requests_Session { /** * Base URL for requests * * URLs will be made absolute using this as the base * * @var string|null */ public $url = null; /** * Base headers for requests * * @var array */ public $headers = array(); /** * Base data for requests * * If both the base data and the per-request data are arrays, the data will * be merged before sending the request. * * @var array */ public $data = array(); /** * Base options for requests * * The base options are merged with the per-request data for each request. * The only default option is a shared cookie jar between requests. * * Values here can also be set directly via properties on the Session * object, e.g. `$session->useragent = 'X';` * * @var array */ public $options = array(); /** * Create a new session * * @param string|null $url Base URL for requests * @param array $headers Default headers for requests * @param array $data Default data for requests * @param array $options Default options for requests */ public function __construct($url = null, $headers = array(), $data = array(), $options = array()) { $this->url = $url; $this->headers = $headers; $this->data = $data; $this->options = $options; if (empty($this->options['cookies'])) { $this->options['cookies'] = new Requests_Cookie_Jar(); } } /** * Get a property's value * * @param string $key Property key * @return mixed|null Property value, null if none found */ public function __get($key) { if (isset($this->options[$key])) { return $this->options[$key]; } return null; } /** * Set a property's value * * @param string $key Property key * @param mixed $value Property value */ public function __set($key, $value) { $this->options[$key] = $value; } /** * Remove a property's value * * @param string $key Property key */ public function __isset($key) { return isset($this->options[$key]); } /** * Remove a property's value * * @param string $key Property key */ public function __unset($key) { if (isset($this->options[$key])) { unset($this->options[$key]); } } /**#@+ * @see request() * @param string $url * @param array $headers * @param array $options * @return Requests_Response */ /** * Send a GET request */ public function get($url, $headers = array(), $options = array()) { return $this->request($url, $headers, null, Requests::GET, $options); } /** * Send a HEAD request */ public function head($url, $headers = array(), $options = array()) { return $this->request($url, $headers, null, Requests::HEAD, $options); } /** * Send a DELETE request */ public function delete($url, $headers = array(), $options = array()) { return $this->request($url, $headers, null, Requests::DELETE, $options); } /**#@-*/ /**#@+ * @see request() * @param string $url * @param array $headers * @param array $data * @param array $options * @return Requests_Response */ /** * Send a POST request */ public function post($url, $headers = array(), $data = array(), $options = array()) { return $this->request($url, $headers, $data, Requests::POST, $options); } /** * Send a PUT request */ public function put($url, $headers = array(), $data = array(), $options = array()) { return $this->request($url, $headers, $data, Requests::PUT, $options); } /** * Send a PATCH request * * Note: Unlike {@see post} and {@see put}, `$headers` is required, as the * specification recommends that should send an ETag * * @link https://tools.ietf.org/html/rfc5789 */ public function patch($url, $headers, $data = array(), $options = array()) { return $this->request($url, $headers, $data, Requests::PATCH, $options); } /**#@-*/ /** * Main interface for HTTP requests * * This method initiates a request and sends it via a transport before * parsing. * * @see Requests::request() * * @throws Requests_Exception On invalid URLs (`nonhttp`) * * @param string $url URL to request * @param array $headers Extra headers to send with the request * @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests * @param string $type HTTP request type (use Requests constants) * @param array $options Options for the request (see {@see Requests::request}) * @return Requests_Response */ public function request($url, $headers = array(), $data = array(), $type = Requests::GET, $options = array()) { $request = $this->merge_request(compact('url', 'headers', 'data', 'options')); return Requests::request($request['url'], $request['headers'], $request['data'], $type, $request['options']); } /** * Send multiple HTTP requests simultaneously * * @see Requests::request_multiple() * * @param array $requests Requests data (see {@see Requests::request_multiple}) * @param array $options Global and default options (see {@see Requests::request}) * @return array Responses (either Requests_Response or a Requests_Exception object) */ public function request_multiple($requests, $options = array()) { foreach ($requests as $key => $request) { $requests[$key] = $this->merge_request($request, false); } $options = array_merge($this->options, $options); // Disallow forcing the type, as that's a per request setting unset($options['type']); return Requests::request_multiple($requests, $options); } /** * Merge a request's data with the default data * * @param array $request Request data (same form as {@see request_multiple}) * @param boolean $merge_options Should we merge options as well? * @return array Request data */ protected function merge_request($request, $merge_options = true) { if ($this->url !== null) { $request['url'] = Requests_IRI::absolutize($this->url, $request['url']); $request['url'] = $request['url']->uri; } if (empty($request['headers'])) { $request['headers'] = array(); } $request['headers'] = array_merge($this->headers, $request['headers']); if (empty($request['data'])) { if (is_array($this->data)) { $request['data'] = $this->data; } } elseif (is_array($request['data']) && is_array($this->data)) { $request['data'] = array_merge($this->data, $request['data']); } if ($merge_options !== false) { $request['options'] = array_merge($this->options, $request['options']); // Disallow forcing the type, as that's a per request setting unset($request['options']['type']); } return $request; } } ``` wordpress class WP_REST_Application_Passwords_Controller {} class WP\_REST\_Application\_Passwords\_Controller {} ===================================================== Core class to access a user’s application passwords via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_application_passwords_controller/__construct) β€” Application Passwords controller constructor. * [create\_item](wp_rest_application_passwords_controller/create_item) β€” Creates an application password. * [create\_item\_permissions\_check](wp_rest_application_passwords_controller/create_item_permissions_check) β€” Checks if a given request has access to create application passwords. * [delete\_item](wp_rest_application_passwords_controller/delete_item) β€” Deletes an application password for a user. * [delete\_item\_permissions\_check](wp_rest_application_passwords_controller/delete_item_permissions_check) β€” Checks if a given request has access to delete a specific application password for a user. * [delete\_items](wp_rest_application_passwords_controller/delete_items) β€” Deletes all application passwords for a user. * [delete\_items\_permissions\_check](wp_rest_application_passwords_controller/delete_items_permissions_check) β€” Checks if a given request has access to delete all application passwords for a user. * [do\_permissions\_check](wp_rest_application_passwords_controller/do_permissions_check) β€” Performs a permissions check for the request. β€” deprecated * [get\_application\_password](wp_rest_application_passwords_controller/get_application_password) β€” Gets the requested application password for a user. * [get\_collection\_params](wp_rest_application_passwords_controller/get_collection_params) β€” Retrieves the query params for the collections. * [get\_current\_item](wp_rest_application_passwords_controller/get_current_item) β€” Retrieves the application password being currently used for authentication of a user. * [get\_current\_item\_permissions\_check](wp_rest_application_passwords_controller/get_current_item_permissions_check) β€” Checks if a given request has access to get the currently used application password for a user. * [get\_item](wp_rest_application_passwords_controller/get_item) β€” Retrieves one application password from the collection. * [get\_item\_permissions\_check](wp_rest_application_passwords_controller/get_item_permissions_check) β€” Checks if a given request has access to get a specific application password. * [get\_item\_schema](wp_rest_application_passwords_controller/get_item_schema) β€” Retrieves the application password's schema, conforming to JSON Schema. * [get\_items](wp_rest_application_passwords_controller/get_items) β€” Retrieves a collection of application passwords. * [get\_items\_permissions\_check](wp_rest_application_passwords_controller/get_items_permissions_check) β€” Checks if a given request has access to get application passwords. * [get\_user](wp_rest_application_passwords_controller/get_user) β€” Gets the requested user. * [prepare\_item\_for\_database](wp_rest_application_passwords_controller/prepare_item_for_database) β€” Prepares an application password for a create or update operation. * [prepare\_item\_for\_response](wp_rest_application_passwords_controller/prepare_item_for_response) β€” Prepares the application password for the REST response. * [prepare\_links](wp_rest_application_passwords_controller/prepare_links) β€” Prepares links for the request. * [register\_routes](wp_rest_application_passwords_controller/register_routes) β€” Registers the REST API routes for the application passwords controller. * [update\_item](wp_rest_application_passwords_controller/update_item) β€” Updates an application password. * [update\_item\_permissions\_check](wp_rest_application_passwords_controller/update_item_permissions_check) β€” Checks if a given request has access to update application passwords. File: `wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php/) ``` class WP_REST_Application_Passwords_Controller extends WP_REST_Controller { /** * Application Passwords controller constructor. * * @since 5.6.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'users/(?P<user_id>(?:[\d]+|me))/application-passwords'; } /** * Registers the REST API routes for the application passwords controller. * * @since 5.6.0 */ 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(), ), array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => array( $this, 'delete_items' ), 'permission_callback' => array( $this, 'delete_items_permissions_check' ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/introspect', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_current_item' ), 'permission_callback' => array( $this, 'get_current_item_permissions_check' ), 'args' => array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<uuid>[\w\-]+)', array( 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' ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks if a given request has access to get application passwords. * * @since 5.6.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } if ( ! current_user_can( 'list_app_passwords', $user->ID ) ) { return new WP_Error( 'rest_cannot_list_application_passwords', __( 'Sorry, you are not allowed to list application passwords for this user.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Retrieves a collection of application passwords. * * @since 5.6.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } $passwords = WP_Application_Passwords::get_user_application_passwords( $user->ID ); $response = array(); foreach ( $passwords as $password ) { $response[] = $this->prepare_response_for_collection( $this->prepare_item_for_response( $password, $request ) ); } return new WP_REST_Response( $response ); } /** * Checks if a given request has access to get a specific application password. * * @since 5.6.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise. */ public function get_item_permissions_check( $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } if ( ! current_user_can( 'read_app_password', $user->ID, $request['uuid'] ) ) { return new WP_Error( 'rest_cannot_read_application_password', __( 'Sorry, you are not allowed to read this application password.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Retrieves one application password from the collection. * * @since 5.6.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_item( $request ) { $password = $this->get_application_password( $request ); if ( is_wp_error( $password ) ) { return $password; } return $this->prepare_item_for_response( $password, $request ); } /** * Checks if a given request has access to create application passwords. * * @since 5.6.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise. */ public function create_item_permissions_check( $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } if ( ! current_user_can( 'create_app_password', $user->ID ) ) { return new WP_Error( 'rest_cannot_create_application_passwords', __( 'Sorry, you are not allowed to create application passwords for this user.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Creates an application password. * * @since 5.6.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function create_item( $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } $prepared = $this->prepare_item_for_database( $request ); if ( is_wp_error( $prepared ) ) { return $prepared; } $created = WP_Application_Passwords::create_new_application_password( $user->ID, wp_slash( (array) $prepared ) ); if ( is_wp_error( $created ) ) { return $created; } $password = $created[0]; $item = WP_Application_Passwords::get_user_application_password( $user->ID, $created[1]['uuid'] ); $item['new_password'] = WP_Application_Passwords::chunk_password( $password ); $fields_update = $this->update_additional_fields_for_object( $item, $request ); if ( is_wp_error( $fields_update ) ) { return $fields_update; } /** * Fires after a single application password is completely created or updated via the REST API. * * @since 5.6.0 * * @param array $item Inserted or updated password item. * @param WP_REST_Request $request Request object. * @param bool $creating True when creating an application password, false when updating. */ do_action( 'rest_after_insert_application_password', $item, $request, true ); $request->set_param( 'context', 'edit' ); $response = $this->prepare_item_for_response( $item, $request ); $response->set_status( 201 ); $response->header( 'Location', $response->get_links()['self'][0]['href'] ); return $response; } /** * Checks if a given request has access to update application passwords. * * @since 5.6.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to create items, WP_Error object otherwise. */ public function update_item_permissions_check( $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } if ( ! current_user_can( 'edit_app_password', $user->ID, $request['uuid'] ) ) { return new WP_Error( 'rest_cannot_edit_application_password', __( 'Sorry, you are not allowed to edit this application password.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Updates an application password. * * @since 5.6.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function update_item( $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } $item = $this->get_application_password( $request ); if ( is_wp_error( $item ) ) { return $item; } $prepared = $this->prepare_item_for_database( $request ); if ( is_wp_error( $prepared ) ) { return $prepared; } $saved = WP_Application_Passwords::update_application_password( $user->ID, $item['uuid'], wp_slash( (array) $prepared ) ); if ( is_wp_error( $saved ) ) { return $saved; } $fields_update = $this->update_additional_fields_for_object( $item, $request ); if ( is_wp_error( $fields_update ) ) { return $fields_update; } $item = WP_Application_Passwords::get_user_application_password( $user->ID, $item['uuid'] ); /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php */ do_action( 'rest_after_insert_application_password', $item, $request, false ); $request->set_param( 'context', 'edit' ); return $this->prepare_item_for_response( $item, $request ); } /** * Checks if a given request has access to delete all application passwords for a user. * * @since 5.6.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise. */ public function delete_items_permissions_check( $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } if ( ! current_user_can( 'delete_app_passwords', $user->ID ) ) { return new WP_Error( 'rest_cannot_delete_application_passwords', __( 'Sorry, you are not allowed to delete application passwords for this user.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Deletes all application passwords for a user. * * @since 5.6.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function delete_items( $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } $deleted = WP_Application_Passwords::delete_all_application_passwords( $user->ID ); if ( is_wp_error( $deleted ) ) { return $deleted; } return new WP_REST_Response( array( 'deleted' => true, 'count' => $deleted, ) ); } /** * Checks if a given request has access to delete a specific application password for a user. * * @since 5.6.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to delete the item, WP_Error object otherwise. */ public function delete_item_permissions_check( $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } if ( ! current_user_can( 'delete_app_password', $user->ID, $request['uuid'] ) ) { return new WP_Error( 'rest_cannot_delete_application_password', __( 'Sorry, you are not allowed to delete this application password.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Deletes an application password for a user. * * @since 5.6.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function delete_item( $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } $password = $this->get_application_password( $request ); if ( is_wp_error( $password ) ) { return $password; } $request->set_param( 'context', 'edit' ); $previous = $this->prepare_item_for_response( $password, $request ); $deleted = WP_Application_Passwords::delete_application_password( $user->ID, $password['uuid'] ); if ( is_wp_error( $deleted ) ) { return $deleted; } return new WP_REST_Response( array( 'deleted' => true, 'previous' => $previous->get_data(), ) ); } /** * Checks if a given request has access to get the currently used application password for a user. * * @since 5.7.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access for the item, WP_Error object otherwise. */ public function get_current_item_permissions_check( $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } if ( get_current_user_id() !== $user->ID ) { return new WP_Error( 'rest_cannot_introspect_app_password_for_non_authenticated_user', __( 'The authenticated application password can only be introspected for the current user.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Retrieves the application password being currently used for authentication of a user. * * @since 5.7.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_current_item( $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } $uuid = rest_get_authenticated_app_password(); if ( ! $uuid ) { return new WP_Error( 'rest_no_authenticated_app_password', __( 'Cannot introspect application password.' ), array( 'status' => 404 ) ); } $password = WP_Application_Passwords::get_user_application_password( $user->ID, $uuid ); if ( ! $password ) { return new WP_Error( 'rest_application_password_not_found', __( 'Application password not found.' ), array( 'status' => 500 ) ); } return $this->prepare_item_for_response( $password, $request ); } /** * Performs a permissions check for the request. * * @since 5.6.0 * @deprecated 5.7.0 Use `edit_user` directly or one of the specific meta capabilities introduced in 5.7.0. * * @param WP_REST_Request $request * @return true|WP_Error */ protected function do_permissions_check( $request ) { _deprecated_function( __METHOD__, '5.7.0' ); $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } if ( ! current_user_can( 'edit_user', $user->ID ) ) { return new WP_Error( 'rest_cannot_manage_application_passwords', __( 'Sorry, you are not allowed to manage application passwords for this user.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Prepares an application password for a create or update operation. * * @since 5.6.0 * * @param WP_REST_Request $request Request object. * @return object|WP_Error The prepared item, or WP_Error object on failure. */ protected function prepare_item_for_database( $request ) { $prepared = (object) array( 'name' => $request['name'], ); if ( $request['app_id'] && ! $request['uuid'] ) { $prepared->app_id = $request['app_id']; } /** * Filters an application password before it is inserted via the REST API. * * @since 5.6.0 * * @param stdClass $prepared An object representing a single application password prepared for inserting or updating the database. * @param WP_REST_Request $request Request object. */ return apply_filters( 'rest_pre_insert_application_password', $prepared, $request ); } /** * Prepares the application password for the REST response. * * @since 5.6.0 * * @param array $item WordPress representation of the item. * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function prepare_item_for_response( $item, $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } $fields = $this->get_fields_for_response( $request ); $prepared = array( 'uuid' => $item['uuid'], 'app_id' => empty( $item['app_id'] ) ? '' : $item['app_id'], 'name' => $item['name'], 'created' => gmdate( 'Y-m-d\TH:i:s', $item['created'] ), 'last_used' => $item['last_used'] ? gmdate( 'Y-m-d\TH:i:s', $item['last_used'] ) : null, 'last_ip' => $item['last_ip'] ? $item['last_ip'] : null, ); if ( isset( $item['new_password'] ) ) { $prepared['password'] = $item['new_password']; } $prepared = $this->add_additional_fields_to_object( $prepared, $request ); $prepared = $this->filter_response_by_context( $prepared, $request['context'] ); $response = new WP_REST_Response( $prepared ); if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { $response->add_links( $this->prepare_links( $user, $item ) ); } /** * Filters the REST API response for an application password. * * @since 5.6.0 * * @param WP_REST_Response $response The response object. * @param array $item The application password array. * @param WP_REST_Request $request The request object. */ return apply_filters( 'rest_prepare_application_password', $response, $item, $request ); } /** * Prepares links for the request. * * @since 5.6.0 * * @param WP_User $user The requested user. * @param array $item The application password. * @return array The list of links. */ protected function prepare_links( WP_User $user, $item ) { return array( 'self' => array( 'href' => rest_url( sprintf( '%s/users/%d/application-passwords/%s', $this->namespace, $user->ID, $item['uuid'] ) ), ), ); } /** * Gets the requested user. * * @since 5.6.0 * * @param WP_REST_Request $request The request object. * @return WP_User|WP_Error The WordPress user associated with the request, or a WP_Error if none found. */ protected function get_user( $request ) { if ( ! wp_is_application_passwords_available() ) { return new WP_Error( 'application_passwords_disabled', __( 'Application passwords are not available.' ), array( 'status' => 501 ) ); } $error = new WP_Error( 'rest_user_invalid_id', __( 'Invalid user ID.' ), array( 'status' => 404 ) ); $id = $request['user_id']; if ( 'me' === $id ) { if ( ! is_user_logged_in() ) { return new WP_Error( 'rest_not_logged_in', __( 'You are not currently logged in.' ), array( 'status' => 401 ) ); } $user = wp_get_current_user(); } else { $id = (int) $id; if ( $id <= 0 ) { return $error; } $user = get_userdata( $id ); } if ( empty( $user ) || ! $user->exists() ) { return $error; } if ( is_multisite() && ! user_can( $user->ID, 'manage_sites' ) && ! is_user_member_of_blog( $user->ID ) ) { return $error; } if ( ! wp_is_application_passwords_available_for_user( $user ) ) { return new WP_Error( 'application_passwords_disabled_for_user', __( 'Application passwords are not available for your account. Please contact the site administrator for assistance.' ), array( 'status' => 501 ) ); } return $user; } /** * Gets the requested application password for a user. * * @since 5.6.0 * * @param WP_REST_Request $request The request object. * @return array|WP_Error The application password details if found, a WP_Error otherwise. */ protected function get_application_password( $request ) { $user = $this->get_user( $request ); if ( is_wp_error( $user ) ) { return $user; } $password = WP_Application_Passwords::get_user_application_password( $user->ID, $request['uuid'] ); if ( ! $password ) { return new WP_Error( 'rest_application_password_not_found', __( 'Application password not found.' ), array( 'status' => 404 ) ); } return $password; } /** * Retrieves the query params for the collections. * * @since 5.6.0 * * @return array Query parameters for the collection. */ public function get_collection_params() { return array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ); } /** * Retrieves the application password's schema, conforming to JSON Schema. * * @since 5.6.0 * * @return array Item schema data. */ 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' => 'application-password', 'type' => 'object', 'properties' => array( 'uuid' => array( 'description' => __( 'The unique identifier for the application password.' ), 'type' => 'string', 'format' => 'uuid', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'app_id' => array( 'description' => __( 'A UUID provided by the application to uniquely identify it. It is recommended to use an UUID v5 with the URL or DNS namespace.' ), 'type' => 'string', 'format' => 'uuid', 'context' => array( 'view', 'edit', 'embed' ), ), 'name' => array( 'description' => __( 'The name of the application password.' ), 'type' => 'string', 'required' => true, 'context' => array( 'view', 'edit', 'embed' ), 'minLength' => 1, 'pattern' => '.*\S.*', ), 'password' => array( 'description' => __( 'The generated password. Only available after adding an application.' ), 'type' => 'string', 'context' => array( 'edit' ), 'readonly' => true, ), 'created' => array( 'description' => __( 'The GMT date the application password was created.' ), 'type' => 'string', 'format' => 'date-time', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), 'last_used' => array( 'description' => __( 'The GMT date the application password was last used.' ), 'type' => array( 'string', 'null' ), 'format' => 'date-time', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), 'last_ip' => array( 'description' => __( 'The IP address the application password was last used by.' ), 'type' => array( 'string', 'null' ), 'format' => 'ip', 'context' => array( 'view', 'edit' ), 'readonly' => true, ), ), ); return $this->add_additional_fields_schema( $this->schema ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
programming_docs
wordpress class Requests_Exception_HTTP_404 {} class Requests\_Exception\_HTTP\_404 {} ======================================= Exception for 404 Not Found responses File: `wp-includes/Requests/Exception/HTTP/404.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/404.php/) ``` class Requests_Exception_HTTP_404 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 404; /** * Reason phrase * * @var string */ protected $reason = 'Not Found'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_Nav_Menu_Widget {} class WP\_Nav\_Menu\_Widget {} ============================== Core class used to implement the Navigation Menu widget. * [WP\_Widget](wp_widget) * [\_\_construct](wp_nav_menu_widget/__construct) β€” Sets up a new Navigation Menu widget instance. * [form](wp_nav_menu_widget/form) β€” Outputs the settings form for the Navigation Menu widget. * [update](wp_nav_menu_widget/update) β€” Handles updating settings for the current Navigation Menu widget instance. * [widget](wp_nav_menu_widget/widget) β€” Outputs the content for the current Navigation Menu widget instance. File: `wp-includes/widgets/class-wp-nav-menu-widget.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-nav-menu-widget.php/) ``` class WP_Nav_Menu_Widget extends WP_Widget { /** * Sets up a new Navigation Menu widget instance. * * @since 3.0.0 */ public function __construct() { $widget_ops = array( 'description' => __( 'Add a navigation menu to your sidebar.' ), 'customize_selective_refresh' => true, 'show_instance_in_rest' => true, ); parent::__construct( 'nav_menu', __( 'Navigation Menu' ), $widget_ops ); } /** * Outputs the content for the current Navigation Menu widget instance. * * @since 3.0.0 * * @param array $args Display arguments including 'before_title', 'after_title', * 'before_widget', and 'after_widget'. * @param array $instance Settings for the current Navigation Menu widget instance. */ public function widget( $args, $instance ) { // Get menu. $nav_menu = ! empty( $instance['nav_menu'] ) ? wp_get_nav_menu_object( $instance['nav_menu'] ) : false; if ( ! $nav_menu ) { return; } $default_title = __( 'Menu' ); $title = ! empty( $instance['title'] ) ? $instance['title'] : ''; /** 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'; /** * Filters the HTML format of widgets with navigation links. * * @since 5.5.0 * * @param string $format The type of markup to use in widgets with navigation links. * Accepts 'html5', 'xhtml'. */ $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; $nav_menu_args = array( 'fallback_cb' => '', 'menu' => $nav_menu, 'container' => 'nav', 'container_aria_label' => $aria_label, 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', ); } else { $nav_menu_args = array( 'fallback_cb' => '', 'menu' => $nav_menu, ); } /** * Filters the arguments for the Navigation Menu widget. * * @since 4.2.0 * @since 4.4.0 Added the `$instance` parameter. * * @param array $nav_menu_args { * An array of arguments passed to wp_nav_menu() to retrieve a navigation menu. * * @type callable|bool $fallback_cb Callback to fire if the menu doesn't exist. Default empty. * @type mixed $menu Menu ID, slug, or name. * } * @param WP_Term $nav_menu Nav menu object for the current menu. * @param array $args Display arguments for the current widget. * @param array $instance Array of settings for the current widget. */ wp_nav_menu( apply_filters( 'widget_nav_menu_args', $nav_menu_args, $nav_menu, $args, $instance ) ); echo $args['after_widget']; } /** * Handles updating settings for the current Navigation Menu widget instance. * * @since 3.0.0 * * @param array $new_instance New settings for this instance as input by the user via * WP_Widget::form(). * @param array $old_instance Old settings for this instance. * @return array Updated settings to save. */ public function update( $new_instance, $old_instance ) { $instance = array(); if ( ! empty( $new_instance['title'] ) ) { $instance['title'] = sanitize_text_field( $new_instance['title'] ); } if ( ! empty( $new_instance['nav_menu'] ) ) { $instance['nav_menu'] = (int) $new_instance['nav_menu']; } return $instance; } /** * Outputs the settings form for the Navigation Menu widget. * * @since 3.0.0 * * @param array $instance Current settings. * @global WP_Customize_Manager $wp_customize */ public function form( $instance ) { global $wp_customize; $title = isset( $instance['title'] ) ? $instance['title'] : ''; $nav_menu = isset( $instance['nav_menu'] ) ? $instance['nav_menu'] : ''; // Get menus. $menus = wp_get_nav_menus(); $empty_menus_style = ''; $not_empty_menus_style = ''; if ( empty( $menus ) ) { $empty_menus_style = ' style="display:none" '; } else { $not_empty_menus_style = ' style="display:none" '; } $nav_menu_style = ''; if ( ! $nav_menu ) { $nav_menu_style = 'display: none;'; } // If no menus exists, direct the user to go and create some. ?> <p class="nav-menu-widget-no-menus-message" <?php echo $not_empty_menus_style; ?>> <?php if ( $wp_customize instanceof WP_Customize_Manager ) { $url = 'javascript: wp.customize.panel( "nav_menus" ).focus();'; } else { $url = admin_url( 'nav-menus.php' ); } printf( /* translators: %s: URL to create a new menu. */ __( 'No menus have been created yet. <a href="%s">Create some</a>.' ), // The URL can be a `javascript:` link, so esc_attr() is used here instead of esc_url(). esc_attr( $url ) ); ?> </p> <div class="nav-menu-widget-form-controls" <?php echo $empty_menus_style; ?>> <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> <p> <label for="<?php echo $this->get_field_id( 'nav_menu' ); ?>"><?php _e( 'Select Menu:' ); ?></label> <select id="<?php echo $this->get_field_id( 'nav_menu' ); ?>" name="<?php echo $this->get_field_name( 'nav_menu' ); ?>"> <option value="0"><?php _e( '&mdash; Select &mdash;' ); ?></option> <?php foreach ( $menus as $menu ) : ?> <option value="<?php echo esc_attr( $menu->term_id ); ?>" <?php selected( $nav_menu, $menu->term_id ); ?>> <?php echo esc_html( $menu->name ); ?> </option> <?php endforeach; ?> </select> </p> <?php if ( $wp_customize instanceof WP_Customize_Manager ) : ?> <p class="edit-selected-nav-menu" style="<?php echo $nav_menu_style; ?>"> <button type="button" class="button"><?php _e( 'Edit Menu' ); ?></button> </p> <?php endif; ?> </div> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Widget](wp_widget) wp-includes/class-wp-widget.php | Core base class extended to register widgets. | | Version | Description | | --- | --- | | [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. | wordpress class WP_User {} class WP\_User {} ================= Core class used to implement the [WP\_User](wp_user) object. To instantiate a specific user, you may use the class constructor : ``` <?php $user = new WP_User( $id [, $name [, $blog_id ] ] ); ?> ``` You can also use the `wp_get_current_user` global function to get a `WP_User` object matching the current logged user. ``` <?php $current_user = wp_get_current_user(); if ( $current_user->has_cap('edit_users') ) { // do something } ?> ``` Check if user exists: ``` <?php $current_user = wp_get_current_user(); if ( $current_user->exists() ) { // do something } ?> ``` Check if user has a property: ``` <?php $current_user = wp_get_current_user(); if ( $current_user->has_prop( 'twitter' ) ) { // do something } ?> ``` The `WP_User` constructor allows the following parameters : * **id** (int) – the user’s id. Leave empty to use login name instead. * **name** (string) – the user’s login name. Ignored if id is set. * **blog\_id** (int) – the blog id on a multisite environment. Defaults to the current blog id. The semantics seem rather fuzzy. If `id` is a `WP_User` or other object, or an array of properties, it seems to clone it without touching the cache. Otherwise if id is a number it seems to try to read it possibly from the cache, or from the database using `->get_data_by()`, which can also update the cache. If `id` is empty it reads by login name. > *Note*: If called with the `id` or `name` parameter, the constructor queries the `(wp_)users` table. If successful, the additional row data become properties of the object: `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`, `spam` *(multisite only)*, `deleted` *(multisite only)*. > > * [\_\_call](wp_user/__call) β€” Makes private/protected methods readable for backward compatibility. * [\_\_construct](wp_user/__construct) β€” Constructor. * [\_\_get](wp_user/__get) β€” Magic method for accessing custom fields. * [\_\_isset](wp_user/__isset) β€” Magic method for checking the existence of a certain custom field. * [\_\_set](wp_user/__set) β€” Magic method for setting custom user fields. * [\_\_unset](wp_user/__unset) β€” Magic method for unsetting a certain custom field. * [\_init\_caps](wp_user/_init_caps) β€” Sets up capability object properties. β€” deprecated * [add\_cap](wp_user/add_cap) β€” Adds capability and grant or deny access to capability. * [add\_role](wp_user/add_role) β€” Adds role to user. * [exists](wp_user/exists) β€” Determines whether the user exists in the database. * [for\_blog](wp_user/for_blog) β€” Sets the site to operate on. Defaults to the current site. β€” deprecated * [for\_site](wp_user/for_site) β€” Sets the site to operate on. Defaults to the current site. * [get](wp_user/get) β€” Retrieves the value of a property or meta key. * [get\_caps\_data](wp_user/get_caps_data) β€” Gets the available user capabilities data. * [get\_data\_by](wp_user/get_data_by) β€” Returns only the main user fields. * [get\_role\_caps](wp_user/get_role_caps) β€” Retrieves all of the capabilities of the user's roles, and merges them with individual user capabilities. * [get\_site\_id](wp_user/get_site_id) β€” Gets the ID of the site for which the user's capabilities are currently initialized. * [has\_cap](wp_user/has_cap) β€” Returns whether the user has the specified capability. * [has\_prop](wp_user/has_prop) β€” Determines whether a property or meta key is set. * [init](wp_user/init) β€” Sets up object properties, including capabilities. * [level\_reduction](wp_user/level_reduction) β€” Chooses the maximum level the user has. * [remove\_all\_caps](wp_user/remove_all_caps) β€” Removes all of the capabilities of the user. * [remove\_cap](wp_user/remove_cap) β€” Removes capability from user. * [remove\_role](wp_user/remove_role) β€” Removes role from user. * [set\_role](wp_user/set_role) β€” Sets the role of the user. * [to\_array](wp_user/to_array) β€” Returns an array representation. * [translate\_level\_to\_cap](wp_user/translate_level_to_cap) β€” Converts numeric level to level capability name. * [update\_user\_level\_from\_caps](wp_user/update_user_level_from_caps) β€” Updates the maximum user level for the user. File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/) ``` class WP_User { /** * User data container. * * @since 2.0.0 * @var stdClass */ public $data; /** * The user's ID. * * @since 2.1.0 * @var int */ public $ID = 0; /** * Capabilities that the individual user has been granted outside of those inherited from their role. * * @since 2.0.0 * @var bool[] Array of key/value pairs where keys represent a capability name * and boolean values represent whether the user has that capability. */ public $caps = array(); /** * User metadata option name. * * @since 2.0.0 * @var string */ public $cap_key; /** * The roles the user is part of. * * @since 2.0.0 * @var string[] */ public $roles = array(); /** * All capabilities the user has, including individual and role based. * * @since 2.0.0 * @var bool[] Array of key/value pairs where keys represent a capability name * and boolean values represent whether the user has that capability. */ public $allcaps = array(); /** * The filter context applied to user data fields. * * @since 2.9.0 * @var string */ public $filter = null; /** * The site ID the capabilities of this user are initialized for. * * @since 4.9.0 * @var int */ private $site_id = 0; /** * @since 3.3.0 * @var array */ private static $back_compat_keys; /** * Constructor. * * Retrieves the userdata and passes it to WP_User::init(). * * @since 2.0.0 * * @param int|string|stdClass|WP_User $id User's ID, a WP_User object, or a user object from the DB. * @param string $name Optional. User's username * @param int $site_id Optional Site ID, defaults to current site. */ public function __construct( $id = 0, $name = '', $site_id = '' ) { if ( ! isset( self::$back_compat_keys ) ) { $prefix = $GLOBALS['wpdb']->prefix; self::$back_compat_keys = array( 'user_firstname' => 'first_name', 'user_lastname' => 'last_name', 'user_description' => 'description', 'user_level' => $prefix . 'user_level', $prefix . 'usersettings' => $prefix . 'user-settings', $prefix . 'usersettingstime' => $prefix . 'user-settings-time', ); } if ( $id instanceof WP_User ) { $this->init( $id->data, $site_id ); return; } elseif ( is_object( $id ) ) { $this->init( $id, $site_id ); return; } if ( ! empty( $id ) && ! is_numeric( $id ) ) { $name = $id; $id = 0; } if ( $id ) { $data = self::get_data_by( 'id', $id ); } else { $data = self::get_data_by( 'login', $name ); } if ( $data ) { $this->init( $data, $site_id ); } else { $this->data = new stdClass; } } /** * Sets up object properties, including capabilities. * * @since 3.3.0 * * @param object $data User DB row object. * @param int $site_id Optional. The site ID to initialize for. */ public function init( $data, $site_id = '' ) { if ( ! isset( $data->ID ) ) { $data->ID = 0; } $this->data = $data; $this->ID = (int) $data->ID; $this->for_site( $site_id ); } /** * Returns only the main user fields. * * @since 3.3.0 * @since 4.4.0 Added 'ID' as an alias of 'id' for the `$field` parameter. * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $field The field to query against: 'id', 'ID', 'slug', 'email' or 'login'. * @param string|int $value The field value. * @return object|false Raw user object. */ public static function get_data_by( $field, $value ) { global $wpdb; // 'ID' is an alias of 'id'. if ( 'ID' === $field ) { $field = 'id'; } if ( 'id' === $field ) { // Make sure the value is numeric to avoid casting objects, for example, // to int 1. if ( ! is_numeric( $value ) ) { return false; } $value = (int) $value; if ( $value < 1 ) { return false; } } else { $value = trim( $value ); } if ( ! $value ) { return false; } switch ( $field ) { case 'id': $user_id = $value; $db_field = 'ID'; break; case 'slug': $user_id = wp_cache_get( $value, 'userslugs' ); $db_field = 'user_nicename'; break; case 'email': $user_id = wp_cache_get( $value, 'useremail' ); $db_field = 'user_email'; break; case 'login': $value = sanitize_user( $value ); $user_id = wp_cache_get( $value, 'userlogins' ); $db_field = 'user_login'; break; default: return false; } if ( false !== $user_id ) { $user = wp_cache_get( $user_id, 'users' ); if ( $user ) { return $user; } } $user = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->users WHERE $db_field = %s LIMIT 1", $value ) ); if ( ! $user ) { return false; } update_user_caches( $user ); return $user; } /** * Magic method for checking the existence of a certain custom field. * * @since 3.3.0 * * @param string $key User meta key to check if set. * @return bool Whether the given user meta key is set. */ public function __isset( $key ) { if ( 'id' === $key ) { _deprecated_argument( 'WP_User->id', '2.1.0', sprintf( /* translators: %s: WP_User->ID */ __( 'Use %s instead.' ), '<code>WP_User->ID</code>' ) ); $key = 'ID'; } if ( isset( $this->data->$key ) ) { return true; } if ( isset( self::$back_compat_keys[ $key ] ) ) { $key = self::$back_compat_keys[ $key ]; } return metadata_exists( 'user', $this->ID, $key ); } /** * Magic method for accessing custom fields. * * @since 3.3.0 * * @param string $key User meta key to retrieve. * @return mixed Value of the given user meta key (if set). If `$key` is 'id', the user ID. */ public function __get( $key ) { if ( 'id' === $key ) { _deprecated_argument( 'WP_User->id', '2.1.0', sprintf( /* translators: %s: WP_User->ID */ __( 'Use %s instead.' ), '<code>WP_User->ID</code>' ) ); return $this->ID; } if ( isset( $this->data->$key ) ) { $value = $this->data->$key; } else { if ( isset( self::$back_compat_keys[ $key ] ) ) { $key = self::$back_compat_keys[ $key ]; } $value = get_user_meta( $this->ID, $key, true ); } if ( $this->filter ) { $value = sanitize_user_field( $key, $value, $this->ID, $this->filter ); } return $value; } /** * Magic method for setting custom user fields. * * This method does not update custom fields in the database. It only stores * the value on the WP_User instance. * * @since 3.3.0 * * @param string $key User meta key. * @param mixed $value User meta value. */ public function __set( $key, $value ) { if ( 'id' === $key ) { _deprecated_argument( 'WP_User->id', '2.1.0', sprintf( /* translators: %s: WP_User->ID */ __( 'Use %s instead.' ), '<code>WP_User->ID</code>' ) ); $this->ID = $value; return; } $this->data->$key = $value; } /** * Magic method for unsetting a certain custom field. * * @since 4.4.0 * * @param string $key User meta key to unset. */ public function __unset( $key ) { if ( 'id' === $key ) { _deprecated_argument( 'WP_User->id', '2.1.0', sprintf( /* translators: %s: WP_User->ID */ __( 'Use %s instead.' ), '<code>WP_User->ID</code>' ) ); } if ( isset( $this->data->$key ) ) { unset( $this->data->$key ); } if ( isset( self::$back_compat_keys[ $key ] ) ) { unset( self::$back_compat_keys[ $key ] ); } } /** * Determines whether the user exists in the database. * * @since 3.4.0 * * @return bool True if user exists in the database, false if not. */ public function exists() { return ! empty( $this->ID ); } /** * Retrieves the value of a property or meta key. * * Retrieves from the users and usermeta table. * * @since 3.3.0 * * @param string $key Property * @return mixed */ public function get( $key ) { return $this->__get( $key ); } /** * Determines whether a property or meta key is set. * * Consults the users and usermeta tables. * * @since 3.3.0 * * @param string $key Property. * @return bool */ public function has_prop( $key ) { return $this->__isset( $key ); } /** * Returns an array representation. * * @since 3.5.0 * * @return array Array representation. */ public function to_array() { return get_object_vars( $this->data ); } /** * Makes private/protected methods readable for backward compatibility. * * @since 4.3.0 * * @param string $name Method to call. * @param array $arguments Arguments to pass when calling. * @return mixed|false Return value of the callback, false otherwise. */ public function __call( $name, $arguments ) { if ( '_init_caps' === $name ) { return $this->_init_caps( ...$arguments ); } return false; } /** * Sets up capability object properties. * * Will set the value for the 'cap_key' property to current database table * prefix, followed by 'capabilities'. Will then check to see if the * property matching the 'cap_key' exists and is an array. If so, it will be * used. * * @since 2.1.0 * @deprecated 4.9.0 Use WP_User::for_site() * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $cap_key Optional capability key */ protected function _init_caps( $cap_key = '' ) { global $wpdb; _deprecated_function( __METHOD__, '4.9.0', 'WP_User::for_site()' ); if ( empty( $cap_key ) ) { $this->cap_key = $wpdb->get_blog_prefix( $this->site_id ) . 'capabilities'; } else { $this->cap_key = $cap_key; } $this->caps = $this->get_caps_data(); $this->get_role_caps(); } /** * Retrieves all of the capabilities of the user's roles, and merges them with * individual user capabilities. * * All of the capabilities of the user's roles are merged with the user's individual * capabilities. This means that the user can be denied specific capabilities that * their role might have, but the user is specifically denied. * * @since 2.0.0 * * @return bool[] Array of key/value pairs where keys represent a capability name * and boolean values represent whether the user has that capability. */ public function get_role_caps() { $switch_site = false; if ( is_multisite() && get_current_blog_id() != $this->site_id ) { $switch_site = true; switch_to_blog( $this->site_id ); } $wp_roles = wp_roles(); // Filter out caps that are not role names and assign to $this->roles. if ( is_array( $this->caps ) ) { $this->roles = array_filter( array_keys( $this->caps ), array( $wp_roles, 'is_role' ) ); } // Build $allcaps from role caps, overlay user's $caps. $this->allcaps = array(); foreach ( (array) $this->roles as $role ) { $the_role = $wp_roles->get_role( $role ); $this->allcaps = array_merge( (array) $this->allcaps, (array) $the_role->capabilities ); } $this->allcaps = array_merge( (array) $this->allcaps, (array) $this->caps ); if ( $switch_site ) { restore_current_blog(); } return $this->allcaps; } /** * Adds role to user. * * Updates the user's meta data option with capabilities and roles. * * @since 2.0.0 * * @param string $role Role name. */ public function add_role( $role ) { if ( empty( $role ) ) { return; } if ( in_array( $role, $this->roles, true ) ) { return; } $this->caps[ $role ] = true; update_user_meta( $this->ID, $this->cap_key, $this->caps ); $this->get_role_caps(); $this->update_user_level_from_caps(); /** * Fires immediately after the user has been given a new role. * * @since 4.3.0 * * @param int $user_id The user ID. * @param string $role The new role. */ do_action( 'add_user_role', $this->ID, $role ); } /** * Removes role from user. * * @since 2.0.0 * * @param string $role Role name. */ public function remove_role( $role ) { if ( ! in_array( $role, $this->roles, true ) ) { return; } unset( $this->caps[ $role ] ); update_user_meta( $this->ID, $this->cap_key, $this->caps ); $this->get_role_caps(); $this->update_user_level_from_caps(); /** * Fires immediately after a role as been removed from a user. * * @since 4.3.0 * * @param int $user_id The user ID. * @param string $role The removed role. */ do_action( 'remove_user_role', $this->ID, $role ); } /** * Sets the role of the user. * * This will remove the previous roles of the user and assign the user the * new one. You can set the role to an empty string and it will remove all * of the roles from the user. * * @since 2.0.0 * * @param string $role Role name. */ public function set_role( $role ) { if ( 1 === count( $this->roles ) && current( $this->roles ) == $role ) { return; } foreach ( (array) $this->roles as $oldrole ) { unset( $this->caps[ $oldrole ] ); } $old_roles = $this->roles; if ( ! empty( $role ) ) { $this->caps[ $role ] = true; $this->roles = array( $role => true ); } else { $this->roles = array(); } update_user_meta( $this->ID, $this->cap_key, $this->caps ); $this->get_role_caps(); $this->update_user_level_from_caps(); foreach ( $old_roles as $old_role ) { if ( ! $old_role || $old_role === $role ) { continue; } /** This action is documented in wp-includes/class-wp-user.php */ do_action( 'remove_user_role', $this->ID, $old_role ); } if ( $role && ! in_array( $role, $old_roles, true ) ) { /** This action is documented in wp-includes/class-wp-user.php */ do_action( 'add_user_role', $this->ID, $role ); } /** * Fires after the user's role has changed. * * @since 2.9.0 * @since 3.6.0 Added $old_roles to include an array of the user's previous roles. * * @param int $user_id The user ID. * @param string $role The new role. * @param string[] $old_roles An array of the user's previous roles. */ do_action( 'set_user_role', $this->ID, $role, $old_roles ); } /** * Chooses the maximum level the user has. * * Will compare the level from the $item parameter against the $max * parameter. If the item is incorrect, then just the $max parameter value * will be returned. * * Used to get the max level based on the capabilities the user has. This * is also based on roles, so if the user is assigned the Administrator role * then the capability 'level_10' will exist and the user will get that * value. * * @since 2.0.0 * * @param int $max Max level of user. * @param string $item Level capability name. * @return int Max Level. */ public function level_reduction( $max, $item ) { if ( preg_match( '/^level_(10|[0-9])$/i', $item, $matches ) ) { $level = (int) $matches[1]; return max( $max, $level ); } else { return $max; } } /** * Updates the maximum user level for the user. * * Updates the 'user_level' user metadata (includes prefix that is the * database table prefix) with the maximum user level. Gets the value from * the all of the capabilities that the user has. * * @since 2.0.0 * * @global wpdb $wpdb WordPress database abstraction object. */ public function update_user_level_from_caps() { global $wpdb; $this->user_level = array_reduce( array_keys( $this->allcaps ), array( $this, 'level_reduction' ), 0 ); update_user_meta( $this->ID, $wpdb->get_blog_prefix() . 'user_level', $this->user_level ); } /** * Adds capability and grant or deny access to capability. * * @since 2.0.0 * * @param string $cap Capability name. * @param bool $grant Whether to grant capability to user. */ public function add_cap( $cap, $grant = true ) { $this->caps[ $cap ] = $grant; update_user_meta( $this->ID, $this->cap_key, $this->caps ); $this->get_role_caps(); $this->update_user_level_from_caps(); } /** * Removes capability from user. * * @since 2.0.0 * * @param string $cap Capability name. */ public function remove_cap( $cap ) { if ( ! isset( $this->caps[ $cap ] ) ) { return; } unset( $this->caps[ $cap ] ); update_user_meta( $this->ID, $this->cap_key, $this->caps ); $this->get_role_caps(); $this->update_user_level_from_caps(); } /** * Removes all of the capabilities of the user. * * @since 2.1.0 * * @global wpdb $wpdb WordPress database abstraction object. */ public function remove_all_caps() { global $wpdb; $this->caps = array(); delete_user_meta( $this->ID, $this->cap_key ); delete_user_meta( $this->ID, $wpdb->get_blog_prefix() . 'user_level' ); $this->get_role_caps(); } /** * Returns whether the user has the specified capability. * * This function also accepts an ID of an object to check against if the capability is a meta capability. Meta * capabilities such as `edit_post` and `edit_user` are capabilities used by the `map_meta_cap()` function to * map to primitive capabilities that a user or role has, such as `edit_posts` and `edit_others_posts`. * * Example usage: * * $user->has_cap( 'edit_posts' ); * $user->has_cap( 'edit_post', $post->ID ); * $user->has_cap( 'edit_post_meta', $post->ID, $meta_key ); * * While checking against a role in place of a capability is supported in part, this practice is discouraged as it * may produce unreliable results. * * @since 2.0.0 * @since 5.3.0 Formalized the existing and already documented `...$args` parameter * by adding it to the function signature. * * @see map_meta_cap() * * @param string $cap Capability name. * @param mixed ...$args Optional further parameters, typically starting with an object ID. * @return bool Whether the user has the given capability, or, if an object ID is passed, whether the user has * the given capability for that object. */ public function has_cap( $cap, ...$args ) { if ( is_numeric( $cap ) ) { _deprecated_argument( __FUNCTION__, '2.0.0', __( 'Usage of user levels is deprecated. Use capabilities instead.' ) ); $cap = $this->translate_level_to_cap( $cap ); } $caps = map_meta_cap( $cap, $this->ID, ...$args ); // Multisite super admin has all caps by definition, Unless specifically denied. if ( is_multisite() && is_super_admin( $this->ID ) ) { if ( in_array( 'do_not_allow', $caps, true ) ) { return false; } return true; } // Maintain BC for the argument passed to the "user_has_cap" filter. $args = array_merge( array( $cap, $this->ID ), $args ); /** * Dynamically filter a user's capabilities. * * @since 2.0.0 * @since 3.7.0 Added the `$user` parameter. * * @param bool[] $allcaps Array of key/value pairs where keys represent a capability name * and boolean values represent whether the user has that capability. * @param string[] $caps Required primitive capabilities for the requested capability. * @param array $args { * Arguments that accompany the requested capability check. * * @type string $0 Requested capability. * @type int $1 Concerned user ID. * @type mixed ...$2 Optional second and further parameters, typically object ID. * } * @param WP_User $user The user object. */ $capabilities = apply_filters( 'user_has_cap', $this->allcaps, $caps, $args, $this ); // Everyone is allowed to exist. $capabilities['exist'] = true; // Nobody is allowed to do things they are not allowed to do. unset( $capabilities['do_not_allow'] ); // Must have ALL requested caps. foreach ( (array) $caps as $cap ) { if ( empty( $capabilities[ $cap ] ) ) { return false; } } return true; } /** * Converts numeric level to level capability name. * * Prepends 'level_' to level number. * * @since 2.0.0 * * @param int $level Level number, 1 to 10. * @return string */ public function translate_level_to_cap( $level ) { return 'level_' . $level; } /** * Sets the site to operate on. Defaults to the current site. * * @since 3.0.0 * @deprecated 4.9.0 Use WP_User::for_site() * * @param int $blog_id Optional. Site ID, defaults to current site. */ public function for_blog( $blog_id = '' ) { _deprecated_function( __METHOD__, '4.9.0', 'WP_User::for_site()' ); $this->for_site( $blog_id ); } /** * Sets the site to operate on. Defaults to the current site. * * @since 4.9.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $site_id Site ID to initialize user capabilities for. Default is the current site. */ public function for_site( $site_id = '' ) { global $wpdb; if ( ! empty( $site_id ) ) { $this->site_id = absint( $site_id ); } else { $this->site_id = get_current_blog_id(); } $this->cap_key = $wpdb->get_blog_prefix( $this->site_id ) . 'capabilities'; $this->caps = $this->get_caps_data(); $this->get_role_caps(); } /** * Gets the ID of the site for which the user's capabilities are currently initialized. * * @since 4.9.0 * * @return int Site ID. */ public function get_site_id() { return $this->site_id; } /** * Gets the available user capabilities data. * * @since 4.9.0 * * @return bool[] List of capabilities keyed by the capability name, * e.g. array( 'edit_posts' => true, 'delete_posts' => false ). */ private function get_caps_data() { $caps = get_user_meta( $this->ID, $this->cap_key, true ); if ( ! is_array( $caps ) ) { return array(); } return $caps; } } ``` | Version | Description | | --- | --- | | [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
programming_docs
wordpress class WP_Style_Engine_CSS_Rules_Store {} class WP\_Style\_Engine\_CSS\_Rules\_Store {} ============================================= Class [WP\_Style\_Engine\_CSS\_Rules\_Store](wp_style_engine_css_rules_store). Holds, sanitizes, processes and prints CSS declarations for the style engine. * [add\_rule](wp_style_engine_css_rules_store/add_rule) β€” Gets a WP\_Style\_Engine\_CSS\_Rule object by its selector. * [get\_all\_rules](wp_style_engine_css_rules_store/get_all_rules) β€” Gets an array of all rules. * [get\_name](wp_style_engine_css_rules_store/get_name) β€” Gets the store name. * [get\_store](wp_style_engine_css_rules_store/get_store) β€” Gets an instance of the store. * [get\_stores](wp_style_engine_css_rules_store/get_stores) β€” Gets an array of all available stores. * [remove\_all\_stores](wp_style_engine_css_rules_store/remove_all_stores) β€” Clears all stores from static::$stores. * [remove\_rule](wp_style_engine_css_rules_store/remove_rule) β€” Removes a selector from the store. * [set\_name](wp_style_engine_css_rules_store/set_name) β€” Sets the store name. File: `wp-includes/style-engine/class-wp-style-engine-css-rules-store.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-css-rules-store.php/) ``` class WP_Style_Engine_CSS_Rules_Store { /** * An array of named WP_Style_Engine_CSS_Rules_Store objects. * * @static * * @since 6.1.0 * @var WP_Style_Engine_CSS_Rules_Store[] */ protected static $stores = array(); /** * The store name. * * @since 6.1.0 * @var string */ protected $name = ''; /** * An array of CSS Rules objects assigned to the store. * * @since 6.1.0 * @var WP_Style_Engine_CSS_Rule[] */ protected $rules = array(); /** * Gets an instance of the store. * * @since 6.1.0 * * @param string $store_name The name of the store. * * @return WP_Style_Engine_CSS_Rules_Store|void */ public static function get_store( $store_name = 'default' ) { if ( ! is_string( $store_name ) || empty( $store_name ) ) { return; } if ( ! isset( static::$stores[ $store_name ] ) ) { static::$stores[ $store_name ] = new static(); // Set the store name. static::$stores[ $store_name ]->set_name( $store_name ); } return static::$stores[ $store_name ]; } /** * Gets an array of all available stores. * * @since 6.1.0 * * @return WP_Style_Engine_CSS_Rules_Store[] */ public static function get_stores() { return static::$stores; } /** * Clears all stores from static::$stores. * * @since 6.1.0 * * @return void */ public static function remove_all_stores() { static::$stores = array(); } /** * Sets the store name. * * @since 6.1.0 * * @param string $name The store name. * * @return void */ public function set_name( $name ) { $this->name = $name; } /** * Gets the store name. * * @since 6.1.0 * * @return string */ public function get_name() { return $this->name; } /** * Gets an array of all rules. * * @since 6.1.0 * * @return WP_Style_Engine_CSS_Rule[] */ public function get_all_rules() { return $this->rules; } /** * Gets a WP_Style_Engine_CSS_Rule object by its selector. * If the rule does not exist, it will be created. * * @since 6.1.0 * * @param string $selector The CSS selector. * * @return WP_Style_Engine_CSS_Rule|void Returns a WP_Style_Engine_CSS_Rule object, or null if the selector is empty. */ public function add_rule( $selector ) { $selector = trim( $selector ); // Bail early if there is no selector. if ( empty( $selector ) ) { return; } // Create the rule if it doesn't exist. if ( empty( $this->rules[ $selector ] ) ) { $this->rules[ $selector ] = new WP_Style_Engine_CSS_Rule( $selector ); } return $this->rules[ $selector ]; } /** * Removes a selector from the store. * * @since 6.1.0 * * @param string $selector The CSS selector. * * @return void */ public function remove_rule( $selector ) { unset( $this->rules[ $selector ] ); } } ``` | Version | Description | | --- | --- | | [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. | wordpress class WP_Posts_List_Table {} class WP\_Posts\_List\_Table {} =============================== Core class used to implement displaying posts in a list table. * [WP\_List\_Table](wp_list_table) * [\_\_construct](wp_posts_list_table/__construct) β€” Constructor. * [\_column\_title](wp_posts_list_table/_column_title) * [\_display\_rows](wp_posts_list_table/_display_rows) * [\_display\_rows\_hierarchical](wp_posts_list_table/_display_rows_hierarchical) * [\_page\_rows](wp_posts_list_table/_page_rows) β€” Given a top level page ID, display the nested hierarchy of sub-pages together with paging support * [ajax\_user\_can](wp_posts_list_table/ajax_user_can) * [categories\_dropdown](wp_posts_list_table/categories_dropdown) β€” Displays a categories drop-down for filtering on the Posts list table. * [column\_author](wp_posts_list_table/column_author) β€” Handles the post author column output. * [column\_cb](wp_posts_list_table/column_cb) β€” Handles the checkbox column output. * [column\_comments](wp_posts_list_table/column_comments) β€” Handles the comments column output. * [column\_date](wp_posts_list_table/column_date) β€” Handles the post date column output. * [column\_default](wp_posts_list_table/column_default) β€” Handles the default column output. * [column\_title](wp_posts_list_table/column_title) β€” Handles the title column output. * [current\_action](wp_posts_list_table/current_action) * [display\_rows](wp_posts_list_table/display_rows) * [extra\_tablenav](wp_posts_list_table/extra_tablenav) * [formats\_dropdown](wp_posts_list_table/formats_dropdown) β€” Displays a formats drop-down for filtering items. * [get\_bulk\_actions](wp_posts_list_table/get_bulk_actions) * [get\_columns](wp_posts_list_table/get_columns) * [get\_default\_primary\_column\_name](wp_posts_list_table/get_default_primary_column_name) β€” Gets the name of the default primary column. * [get\_edit\_link](wp_posts_list_table/get_edit_link) β€” Helper to create links to edit.php with params. * [get\_sortable\_columns](wp_posts_list_table/get_sortable_columns) * [get\_table\_classes](wp_posts_list_table/get_table_classes) * [get\_views](wp_posts_list_table/get_views) * [handle\_row\_actions](wp_posts_list_table/handle_row_actions) β€” Generates and displays row action links. * [has\_items](wp_posts_list_table/has_items) * [inline\_edit](wp_posts_list_table/inline_edit) β€” Outputs the hidden row displayed when inline editing * [is\_base\_request](wp_posts_list_table/is_base_request) β€” Determine if the current view is the "All" view. * [no\_items](wp_posts_list_table/no_items) * [prepare\_items](wp_posts_list_table/prepare_items) * [set\_hierarchical\_display](wp_posts_list_table/set_hierarchical_display) β€” Sets whether the table layout should be hierarchical or not. * [single\_row](wp_posts_list_table/single_row) File: `wp-admin/includes/class-wp-posts-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-posts-list-table.php/) ``` class WP_Posts_List_Table extends WP_List_Table { /** * Whether the items should be displayed hierarchically or linearly. * * @since 3.1.0 * @var bool */ protected $hierarchical_display; /** * Holds the number of pending comments for each post. * * @since 3.1.0 * @var array */ protected $comment_pending_count; /** * Holds the number of posts for this user. * * @since 3.1.0 * @var int */ private $user_posts_count; /** * Holds the number of posts which are sticky. * * @since 3.1.0 * @var int */ private $sticky_posts_count = 0; private $is_trash; /** * Current level for output. * * @since 4.3.0 * @var int */ protected $current_level = 0; /** * Constructor. * * @since 3.1.0 * * @see WP_List_Table::__construct() for more information on default arguments. * * @global WP_Post_Type $post_type_object * @global wpdb $wpdb WordPress database abstraction object. * * @param array $args An associative array of arguments. */ public function __construct( $args = array() ) { global $post_type_object, $wpdb; parent::__construct( array( 'plural' => 'posts', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); $post_type = $this->screen->post_type; $post_type_object = get_post_type_object( $post_type ); $exclude_states = get_post_stati( array( 'show_in_admin_all_list' => false, ) ); $this->user_posts_count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( 1 ) FROM $wpdb->posts WHERE post_type = %s AND post_status NOT IN ( '" . implode( "','", $exclude_states ) . "' ) AND post_author = %d", $post_type, get_current_user_id() ) ); if ( $this->user_posts_count && ! current_user_can( $post_type_object->cap->edit_others_posts ) && empty( $_REQUEST['post_status'] ) && empty( $_REQUEST['all_posts'] ) && empty( $_REQUEST['author'] ) && empty( $_REQUEST['show_sticky'] ) ) { $_GET['author'] = get_current_user_id(); } $sticky_posts = get_option( 'sticky_posts' ); if ( 'post' === $post_type && $sticky_posts ) { $sticky_posts = implode( ', ', array_map( 'absint', (array) $sticky_posts ) ); $this->sticky_posts_count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( 1 ) FROM $wpdb->posts WHERE post_type = %s AND post_status NOT IN ('trash', 'auto-draft') AND ID IN ($sticky_posts)", $post_type ) ); } } /** * Sets whether the table layout should be hierarchical or not. * * @since 4.2.0 * * @param bool $display Whether the table layout should be hierarchical. */ public function set_hierarchical_display( $display ) { $this->hierarchical_display = $display; } /** * @return bool */ public function ajax_user_can() { return current_user_can( get_post_type_object( $this->screen->post_type )->cap->edit_posts ); } /** * @global string $mode List table view mode. * @global array $avail_post_stati * @global WP_Query $wp_query WordPress Query object. * @global int $per_page */ public function prepare_items() { global $mode, $avail_post_stati, $wp_query, $per_page; if ( ! empty( $_REQUEST['mode'] ) ) { $mode = 'excerpt' === $_REQUEST['mode'] ? 'excerpt' : 'list'; set_user_setting( 'posts_list_mode', $mode ); } else { $mode = get_user_setting( 'posts_list_mode', 'list' ); } // Is going to call wp(). $avail_post_stati = wp_edit_posts_query(); $this->set_hierarchical_display( is_post_type_hierarchical( $this->screen->post_type ) && 'menu_order title' === $wp_query->query['orderby'] ); $post_type = $this->screen->post_type; $per_page = $this->get_items_per_page( 'edit_' . $post_type . '_per_page' ); /** This filter is documented in wp-admin/includes/post.php */ $per_page = apply_filters( 'edit_posts_per_page', $per_page, $post_type ); if ( $this->hierarchical_display ) { $total_items = $wp_query->post_count; } elseif ( $wp_query->found_posts || $this->get_pagenum() === 1 ) { $total_items = $wp_query->found_posts; } else { $post_counts = (array) wp_count_posts( $post_type, 'readable' ); if ( isset( $_REQUEST['post_status'] ) && in_array( $_REQUEST['post_status'], $avail_post_stati, true ) ) { $total_items = $post_counts[ $_REQUEST['post_status'] ]; } elseif ( isset( $_REQUEST['show_sticky'] ) && $_REQUEST['show_sticky'] ) { $total_items = $this->sticky_posts_count; } elseif ( isset( $_GET['author'] ) && get_current_user_id() === (int) $_GET['author'] ) { $total_items = $this->user_posts_count; } else { $total_items = array_sum( $post_counts ); // Subtract post types that are not included in the admin all list. foreach ( get_post_stati( array( 'show_in_admin_all_list' => false ) ) as $state ) { $total_items -= $post_counts[ $state ]; } } } $this->is_trash = isset( $_REQUEST['post_status'] ) && 'trash' === $_REQUEST['post_status']; $this->set_pagination_args( array( 'total_items' => $total_items, 'per_page' => $per_page, ) ); } /** * @return bool */ public function has_items() { return have_posts(); } /** */ public function no_items() { if ( isset( $_REQUEST['post_status'] ) && 'trash' === $_REQUEST['post_status'] ) { echo get_post_type_object( $this->screen->post_type )->labels->not_found_in_trash; } else { echo get_post_type_object( $this->screen->post_type )->labels->not_found; } } /** * Determine if the current view is the "All" view. * * @since 4.2.0 * * @return bool Whether the current view is the "All" view. */ protected function is_base_request() { $vars = $_GET; unset( $vars['paged'] ); if ( empty( $vars ) ) { return true; } elseif ( 1 === count( $vars ) && ! empty( $vars['post_type'] ) ) { return $this->screen->post_type === $vars['post_type']; } return 1 === count( $vars ) && ! empty( $vars['mode'] ); } /** * Helper to create links to edit.php with params. * * @since 4.4.0 * * @param string[] $args Associative array of URL parameters for the link. * @param string $link_text Link text. * @param string $css_class Optional. Class attribute. Default empty string. * @return string The formatted link string. */ protected function get_edit_link( $args, $link_text, $css_class = '' ) { $url = add_query_arg( $args, 'edit.php' ); $class_html = ''; $aria_current = ''; if ( ! empty( $css_class ) ) { $class_html = sprintf( ' class="%s"', esc_attr( $css_class ) ); if ( 'current' === $css_class ) { $aria_current = ' aria-current="page"'; } } return sprintf( '<a href="%s"%s%s>%s</a>', esc_url( $url ), $class_html, $aria_current, $link_text ); } /** * @global array $locked_post_status This seems to be deprecated. * @global array $avail_post_stati * @return array */ protected function get_views() { global $locked_post_status, $avail_post_stati; $post_type = $this->screen->post_type; if ( ! empty( $locked_post_status ) ) { return array(); } $status_links = array(); $num_posts = wp_count_posts( $post_type, 'readable' ); $total_posts = array_sum( (array) $num_posts ); $class = ''; $current_user_id = get_current_user_id(); $all_args = array( 'post_type' => $post_type ); $mine = ''; // Subtract post types that are not included in the admin all list. foreach ( get_post_stati( array( 'show_in_admin_all_list' => false ) ) as $state ) { $total_posts -= $num_posts->$state; } if ( $this->user_posts_count && $this->user_posts_count !== $total_posts ) { if ( isset( $_GET['author'] ) && ( $current_user_id === (int) $_GET['author'] ) ) { $class = 'current'; } $mine_args = array( 'post_type' => $post_type, 'author' => $current_user_id, ); $mine_inner_html = sprintf( /* translators: %s: Number of posts. */ _nx( 'Mine <span class="count">(%s)</span>', 'Mine <span class="count">(%s)</span>', $this->user_posts_count, 'posts' ), number_format_i18n( $this->user_posts_count ) ); $mine = array( 'url' => esc_url( add_query_arg( $mine_args, 'edit.php' ) ), 'label' => $mine_inner_html, 'current' => isset( $_GET['author'] ) && ( $current_user_id === (int) $_GET['author'] ), ); $all_args['all_posts'] = 1; $class = ''; } $all_inner_html = sprintf( /* translators: %s: Number of posts. */ _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $total_posts, 'posts' ), number_format_i18n( $total_posts ) ); $status_links['all'] = array( 'url' => esc_url( add_query_arg( $all_args, 'edit.php' ) ), 'label' => $all_inner_html, 'current' => empty( $class ) && ( $this->is_base_request() || isset( $_REQUEST['all_posts'] ) ), ); if ( $mine ) { $status_links['mine'] = $mine; } foreach ( get_post_stati( array( 'show_in_admin_status_list' => true ), 'objects' ) as $status ) { $class = ''; $status_name = $status->name; if ( ! in_array( $status_name, $avail_post_stati, true ) || empty( $num_posts->$status_name ) ) { continue; } if ( isset( $_REQUEST['post_status'] ) && $status_name === $_REQUEST['post_status'] ) { $class = 'current'; } $status_args = array( 'post_status' => $status_name, 'post_type' => $post_type, ); $status_label = sprintf( translate_nooped_plural( $status->label_count, $num_posts->$status_name ), number_format_i18n( $num_posts->$status_name ) ); $status_links[ $status_name ] = array( 'url' => esc_url( add_query_arg( $status_args, 'edit.php' ) ), 'label' => $status_label, 'current' => isset( $_REQUEST['post_status'] ) && $status_name === $_REQUEST['post_status'], ); } if ( ! empty( $this->sticky_posts_count ) ) { $class = ! empty( $_REQUEST['show_sticky'] ) ? 'current' : ''; $sticky_args = array( 'post_type' => $post_type, 'show_sticky' => 1, ); $sticky_inner_html = sprintf( /* translators: %s: Number of posts. */ _nx( 'Sticky <span class="count">(%s)</span>', 'Sticky <span class="count">(%s)</span>', $this->sticky_posts_count, 'posts' ), number_format_i18n( $this->sticky_posts_count ) ); $sticky_link = array( 'sticky' => array( 'url' => esc_url( add_query_arg( $sticky_args, 'edit.php' ) ), 'label' => $sticky_inner_html, 'current' => ! empty( $_REQUEST['show_sticky'] ), ), ); // Sticky comes after Publish, or if not listed, after All. $split = 1 + array_search( ( isset( $status_links['publish'] ) ? 'publish' : 'all' ), array_keys( $status_links ), true ); $status_links = array_merge( array_slice( $status_links, 0, $split ), $sticky_link, array_slice( $status_links, $split ) ); } return $this->get_views_links( $status_links ); } /** * @return array */ protected function get_bulk_actions() { $actions = array(); $post_type_obj = get_post_type_object( $this->screen->post_type ); if ( current_user_can( $post_type_obj->cap->edit_posts ) ) { if ( $this->is_trash ) { $actions['untrash'] = __( 'Restore' ); } else { $actions['edit'] = __( 'Edit' ); } } if ( current_user_can( $post_type_obj->cap->delete_posts ) ) { if ( $this->is_trash || ! EMPTY_TRASH_DAYS ) { $actions['delete'] = __( 'Delete permanently' ); } else { $actions['trash'] = __( 'Move to Trash' ); } } return $actions; } /** * Displays a categories drop-down for filtering on the Posts list table. * * @since 4.6.0 * * @global int $cat Currently selected category. * * @param string $post_type Post type slug. */ protected function categories_dropdown( $post_type ) { global $cat; /** * Filters whether to remove the 'Categories' drop-down from the post list table. * * @since 4.6.0 * * @param bool $disable Whether to disable the categories drop-down. Default false. * @param string $post_type Post type slug. */ if ( false !== apply_filters( 'disable_categories_dropdown', false, $post_type ) ) { return; } if ( is_object_in_taxonomy( $post_type, 'category' ) ) { $dropdown_options = array( 'show_option_all' => get_taxonomy( 'category' )->labels->all_items, 'hide_empty' => 0, 'hierarchical' => 1, 'show_count' => 0, 'orderby' => 'name', 'selected' => $cat, ); echo '<label class="screen-reader-text" for="cat">' . get_taxonomy( 'category' )->labels->filter_by_item . '</label>'; wp_dropdown_categories( $dropdown_options ); } } /** * Displays a formats drop-down for filtering items. * * @since 5.2.0 * @access protected * * @param string $post_type Post type slug. */ protected function formats_dropdown( $post_type ) { /** * Filters whether to remove the 'Formats' drop-down from the post list table. * * @since 5.2.0 * @since 5.5.0 The `$post_type` parameter was added. * * @param bool $disable Whether to disable the drop-down. Default false. * @param string $post_type Post type slug. */ if ( apply_filters( 'disable_formats_dropdown', false, $post_type ) ) { return; } // Return if the post type doesn't have post formats or if we're in the Trash. if ( ! is_object_in_taxonomy( $post_type, 'post_format' ) || $this->is_trash ) { return; } // Make sure the dropdown shows only formats with a post count greater than 0. $used_post_formats = get_terms( array( 'taxonomy' => 'post_format', 'hide_empty' => true, ) ); // Return if there are no posts using formats. if ( ! $used_post_formats ) { return; } $displayed_post_format = isset( $_GET['post_format'] ) ? $_GET['post_format'] : ''; ?> <label for="filter-by-format" class="screen-reader-text"><?php _e( 'Filter by post format' ); ?></label> <select name="post_format" id="filter-by-format"> <option<?php selected( $displayed_post_format, '' ); ?> value=""><?php _e( 'All formats' ); ?></option> <?php foreach ( $used_post_formats as $used_post_format ) { // Post format slug. $slug = str_replace( 'post-format-', '', $used_post_format->slug ); // Pretty, translated version of the post format slug. $pretty_name = get_post_format_string( $slug ); // Skip the standard post format. if ( 'standard' === $slug ) { continue; } ?> <option<?php selected( $displayed_post_format, $slug ); ?> value="<?php echo esc_attr( $slug ); ?>"><?php echo esc_html( $pretty_name ); ?></option> <?php } ?> </select> <?php } /** * @param string $which */ protected function extra_tablenav( $which ) { ?> <div class="alignleft actions"> <?php if ( 'top' === $which ) { ob_start(); $this->months_dropdown( $this->screen->post_type ); $this->categories_dropdown( $this->screen->post_type ); $this->formats_dropdown( $this->screen->post_type ); /** * Fires before the Filter button on the Posts and Pages list tables. * * The Filter button allows sorting by date and/or category on the * Posts list table, and sorting by date on the Pages list table. * * @since 2.1.0 * @since 4.4.0 The `$post_type` parameter was added. * @since 4.6.0 The `$which` parameter was added. * * @param string $post_type The post type slug. * @param string $which The location of the extra table nav markup: * 'top' or 'bottom' for WP_Posts_List_Table, * 'bar' for WP_Media_List_Table. */ do_action( 'restrict_manage_posts', $this->screen->post_type, $which ); $output = ob_get_clean(); if ( ! empty( $output ) ) { echo $output; submit_button( __( 'Filter' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) ); } } if ( $this->is_trash && $this->has_items() && current_user_can( get_post_type_object( $this->screen->post_type )->cap->edit_others_posts ) ) { submit_button( __( 'Empty Trash' ), 'apply', 'delete_all', false ); } ?> </div> <?php /** * Fires immediately following the closing "actions" div in the tablenav for the posts * list table. * * @since 4.4.0 * * @param string $which The location of the extra table nav markup: 'top' or 'bottom'. */ do_action( 'manage_posts_extra_tablenav', $which ); } /** * @return string */ public function current_action() { if ( isset( $_REQUEST['delete_all'] ) || isset( $_REQUEST['delete_all2'] ) ) { return 'delete_all'; } return parent::current_action(); } /** * @global string $mode List table view mode. * * @return array */ protected function get_table_classes() { global $mode; $mode_class = esc_attr( 'table-view-' . $mode ); return array( 'widefat', 'fixed', 'striped', $mode_class, is_post_type_hierarchical( $this->screen->post_type ) ? 'pages' : 'posts', ); } /** * @return array */ public function get_columns() { $post_type = $this->screen->post_type; $posts_columns = array(); $posts_columns['cb'] = '<input type="checkbox" />'; /* translators: Posts screen column name. */ $posts_columns['title'] = _x( 'Title', 'column name' ); if ( post_type_supports( $post_type, 'author' ) ) { $posts_columns['author'] = __( 'Author' ); } $taxonomies = get_object_taxonomies( $post_type, 'objects' ); $taxonomies = wp_filter_object_list( $taxonomies, array( 'show_admin_column' => true ), 'and', 'name' ); /** * Filters the taxonomy columns in the Posts list table. * * The dynamic portion of the hook name, `$post_type`, refers to the post * type slug. * * Possible hook names include: * * - `manage_taxonomies_for_post_columns` * - `manage_taxonomies_for_page_columns` * * @since 3.5.0 * * @param string[] $taxonomies Array of taxonomy names to show columns for. * @param string $post_type The post type. */ $taxonomies = apply_filters( "manage_taxonomies_for_{$post_type}_columns", $taxonomies, $post_type ); $taxonomies = array_filter( $taxonomies, 'taxonomy_exists' ); foreach ( $taxonomies as $taxonomy ) { if ( 'category' === $taxonomy ) { $column_key = 'categories'; } elseif ( 'post_tag' === $taxonomy ) { $column_key = 'tags'; } else { $column_key = 'taxonomy-' . $taxonomy; } $posts_columns[ $column_key ] = get_taxonomy( $taxonomy )->labels->name; } $post_status = ! empty( $_REQUEST['post_status'] ) ? $_REQUEST['post_status'] : 'all'; if ( post_type_supports( $post_type, 'comments' ) && ! in_array( $post_status, array( 'pending', 'draft', 'future' ), true ) ) { $posts_columns['comments'] = sprintf( '<span class="vers comment-grey-bubble" title="%1$s" aria-hidden="true"></span><span class="screen-reader-text">%2$s</span>', esc_attr__( 'Comments' ), __( 'Comments' ) ); } $posts_columns['date'] = __( 'Date' ); if ( 'page' === $post_type ) { /** * Filters the columns displayed in the Pages list table. * * @since 2.5.0 * * @param string[] $post_columns An associative array of column headings. */ $posts_columns = apply_filters( 'manage_pages_columns', $posts_columns ); } else { /** * Filters the columns displayed in the Posts list table. * * @since 1.5.0 * * @param string[] $post_columns An associative array of column headings. * @param string $post_type The post type slug. */ $posts_columns = apply_filters( 'manage_posts_columns', $posts_columns, $post_type ); } /** * Filters the columns displayed in the Posts list table for a specific post type. * * The dynamic portion of the hook name, `$post_type`, refers to the post type slug. * * Possible hook names include: * * - `manage_post_posts_columns` * - `manage_page_posts_columns` * * @since 3.0.0 * * @param string[] $post_columns An associative array of column headings. */ return apply_filters( "manage_{$post_type}_posts_columns", $posts_columns ); } /** * @return array */ protected function get_sortable_columns() { return array( 'title' => 'title', 'parent' => 'parent', 'comments' => 'comment_count', 'date' => array( 'date', true ), ); } /** * @global WP_Query $wp_query WordPress Query object. * @global int $per_page * @param array $posts * @param int $level */ public function display_rows( $posts = array(), $level = 0 ) { global $wp_query, $per_page; if ( empty( $posts ) ) { $posts = $wp_query->posts; } add_filter( 'the_title', 'esc_html' ); if ( $this->hierarchical_display ) { $this->_display_rows_hierarchical( $posts, $this->get_pagenum(), $per_page ); } else { $this->_display_rows( $posts, $level ); } } /** * @param array $posts * @param int $level */ private function _display_rows( $posts, $level = 0 ) { $post_type = $this->screen->post_type; // Create array of post IDs. $post_ids = array(); foreach ( $posts as $a_post ) { $post_ids[] = $a_post->ID; } if ( post_type_supports( $post_type, 'comments' ) ) { $this->comment_pending_count = get_pending_comments_num( $post_ids ); } update_post_author_caches( $posts ); foreach ( $posts as $post ) { $this->single_row( $post, $level ); } } /** * @global wpdb $wpdb WordPress database abstraction object. * @global WP_Post $post Global post object. * @param array $pages * @param int $pagenum * @param int $per_page */ private function _display_rows_hierarchical( $pages, $pagenum = 1, $per_page = 20 ) { global $wpdb; $level = 0; if ( ! $pages ) { $pages = get_pages( array( 'sort_column' => 'menu_order' ) ); if ( ! $pages ) { return; } } /* * Arrange pages into two parts: top level pages and children_pages. * children_pages is two dimensional array. Example: * children_pages[10][] contains all sub-pages whose parent is 10. * It only takes O( N ) to arrange this and it takes O( 1 ) for subsequent lookup operations * If searching, ignore hierarchy and treat everything as top level */ if ( empty( $_REQUEST['s'] ) ) { $top_level_pages = array(); $children_pages = array(); foreach ( $pages as $page ) { // Catch and repair bad pages. if ( $page->post_parent === $page->ID ) { $page->post_parent = 0; $wpdb->update( $wpdb->posts, array( 'post_parent' => 0 ), array( 'ID' => $page->ID ) ); clean_post_cache( $page ); } if ( $page->post_parent > 0 ) { $children_pages[ $page->post_parent ][] = $page; } else { $top_level_pages[] = $page; } } $pages = &$top_level_pages; } $count = 0; $start = ( $pagenum - 1 ) * $per_page; $end = $start + $per_page; $to_display = array(); foreach ( $pages as $page ) { if ( $count >= $end ) { break; } if ( $count >= $start ) { $to_display[ $page->ID ] = $level; } $count++; if ( isset( $children_pages ) ) { $this->_page_rows( $children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page, $to_display ); } } // If it is the last pagenum and there are orphaned pages, display them with paging as well. if ( isset( $children_pages ) && $count < $end ) { foreach ( $children_pages as $orphans ) { foreach ( $orphans as $op ) { if ( $count >= $end ) { break; } if ( $count >= $start ) { $to_display[ $op->ID ] = 0; } $count++; } } } $ids = array_keys( $to_display ); _prime_post_caches( $ids ); $_posts = array_map( 'get_post', $ids ); update_post_author_caches( $_posts ); if ( ! isset( $GLOBALS['post'] ) ) { $GLOBALS['post'] = reset( $ids ); } foreach ( $to_display as $page_id => $level ) { echo "\t"; $this->single_row( $page_id, $level ); } } /** * Given a top level page ID, display the nested hierarchy of sub-pages * together with paging support * * @since 3.1.0 (Standalone function exists since 2.6.0) * @since 4.2.0 Added the `$to_display` parameter. * * @param array $children_pages * @param int $count * @param int $parent_page * @param int $level * @param int $pagenum * @param int $per_page * @param array $to_display List of pages to be displayed. Passed by reference. */ private function _page_rows( &$children_pages, &$count, $parent_page, $level, $pagenum, $per_page, &$to_display ) { if ( ! isset( $children_pages[ $parent_page ] ) ) { return; } $start = ( $pagenum - 1 ) * $per_page; $end = $start + $per_page; foreach ( $children_pages[ $parent_page ] as $page ) { if ( $count >= $end ) { break; } // If the page starts in a subtree, print the parents. if ( $count === $start && $page->post_parent > 0 ) { $my_parents = array(); $my_parent = $page->post_parent; while ( $my_parent ) { // Get the ID from the list or the attribute if my_parent is an object. $parent_id = $my_parent; if ( is_object( $my_parent ) ) { $parent_id = $my_parent->ID; } $my_parent = get_post( $parent_id ); $my_parents[] = $my_parent; if ( ! $my_parent->post_parent ) { break; } $my_parent = $my_parent->post_parent; } $num_parents = count( $my_parents ); while ( $my_parent = array_pop( $my_parents ) ) { $to_display[ $my_parent->ID ] = $level - $num_parents; $num_parents--; } } if ( $count >= $start ) { $to_display[ $page->ID ] = $level; } $count++; $this->_page_rows( $children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page, $to_display ); } unset( $children_pages[ $parent_page ] ); // Required in order to keep track of orphans. } /** * Handles the checkbox column output. * * @since 4.3.0 * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Post $item The current WP_Post object. */ public function column_cb( $item ) { // Restores the more descriptive, specific name for use within this method. $post = $item; $show = current_user_can( 'edit_post', $post->ID ); /** * Filters whether to show the bulk edit checkbox for a post in its list table. * * By default the checkbox is only shown if the current user can edit the post. * * @since 5.7.0 * * @param bool $show Whether to show the checkbox. * @param WP_Post $post The current WP_Post object. */ if ( apply_filters( 'wp_list_table_show_post_checkbox', $show, $post ) ) : ?> <label class="screen-reader-text" for="cb-select-<?php the_ID(); ?>"> <?php /* translators: %s: Post title. */ printf( __( 'Select %s' ), _draft_or_post_title() ); ?> </label> <input id="cb-select-<?php the_ID(); ?>" type="checkbox" name="post[]" value="<?php the_ID(); ?>" /> <div class="locked-indicator"> <span class="locked-indicator-icon" aria-hidden="true"></span> <span class="screen-reader-text"> <?php printf( /* translators: %s: Post title. */ __( '&#8220;%s&#8221; is locked' ), _draft_or_post_title() ); ?> </span> </div> <?php endif; } /** * @since 4.3.0 * * @param WP_Post $post * @param string $classes * @param string $data * @param string $primary */ protected function _column_title( $post, $classes, $data, $primary ) { echo '<td class="' . $classes . ' page-title" ', $data, '>'; echo $this->column_title( $post ); echo $this->handle_row_actions( $post, 'title', $primary ); echo '</td>'; } /** * Handles the title column output. * * @since 4.3.0 * * @global string $mode List table view mode. * * @param WP_Post $post The current WP_Post object. */ public function column_title( $post ) { global $mode; if ( $this->hierarchical_display ) { if ( 0 === $this->current_level && (int) $post->post_parent > 0 ) { // Sent level 0 by accident, by default, or because we don't know the actual level. $find_main_page = (int) $post->post_parent; while ( $find_main_page > 0 ) { $parent = get_post( $find_main_page ); if ( is_null( $parent ) ) { break; } $this->current_level++; $find_main_page = (int) $parent->post_parent; if ( ! isset( $parent_name ) ) { /** This filter is documented in wp-includes/post-template.php */ $parent_name = apply_filters( 'the_title', $parent->post_title, $parent->ID ); } } } } $can_edit_post = current_user_can( 'edit_post', $post->ID ); if ( $can_edit_post && 'trash' !== $post->post_status ) { $lock_holder = wp_check_post_lock( $post->ID ); if ( $lock_holder ) { $lock_holder = get_userdata( $lock_holder ); $locked_avatar = get_avatar( $lock_holder->ID, 18 ); /* translators: %s: User's display name. */ $locked_text = esc_html( sprintf( __( '%s is currently editing' ), $lock_holder->display_name ) ); } else { $locked_avatar = ''; $locked_text = ''; } echo '<div class="locked-info"><span class="locked-avatar">' . $locked_avatar . '</span> <span class="locked-text">' . $locked_text . "</span></div>\n"; } $pad = str_repeat( '&#8212; ', $this->current_level ); echo '<strong>'; $title = _draft_or_post_title(); if ( $can_edit_post && 'trash' !== $post->post_status ) { printf( '<a class="row-title" href="%s" aria-label="%s">%s%s</a>', get_edit_post_link( $post->ID ), /* translators: %s: Post title. */ esc_attr( sprintf( __( '&#8220;%s&#8221; (Edit)' ), $title ) ), $pad, $title ); } else { printf( '<span>%s%s</span>', $pad, $title ); } _post_states( $post ); if ( isset( $parent_name ) ) { $post_type_object = get_post_type_object( $post->post_type ); echo ' | ' . $post_type_object->labels->parent_item_colon . ' ' . esc_html( $parent_name ); } echo "</strong>\n"; if ( 'excerpt' === $mode && ! is_post_type_hierarchical( $this->screen->post_type ) && current_user_can( 'read_post', $post->ID ) ) { if ( post_password_required( $post ) ) { echo '<span class="protected-post-excerpt">' . esc_html( get_the_excerpt() ) . '</span>'; } else { echo esc_html( get_the_excerpt() ); } } get_inline_data( $post ); } /** * Handles the post date column output. * * @since 4.3.0 * * @global string $mode List table view mode. * * @param WP_Post $post The current WP_Post object. */ public function column_date( $post ) { global $mode; if ( '0000-00-00 00:00:00' === $post->post_date ) { $t_time = __( 'Unpublished' ); $time_diff = 0; } else { $t_time = sprintf( /* translators: 1: Post date, 2: Post time. */ __( '%1$s at %2$s' ), /* translators: Post date format. See https://www.php.net/manual/datetime.format.php */ get_the_time( __( 'Y/m/d' ), $post ), /* translators: Post time format. See https://www.php.net/manual/datetime.format.php */ get_the_time( __( 'g:i a' ), $post ) ); $time = get_post_timestamp( $post ); $time_diff = time() - $time; } if ( 'publish' === $post->post_status ) { $status = __( 'Published' ); } elseif ( 'future' === $post->post_status ) { if ( $time_diff > 0 ) { $status = '<strong class="error-message">' . __( 'Missed schedule' ) . '</strong>'; } else { $status = __( 'Scheduled' ); } } else { $status = __( 'Last Modified' ); } /** * Filters the status text of the post. * * @since 4.8.0 * * @param string $status The status text. * @param WP_Post $post Post object. * @param string $column_name The column name. * @param string $mode The list display mode ('excerpt' or 'list'). */ $status = apply_filters( 'post_date_column_status', $status, $post, 'date', $mode ); if ( $status ) { echo $status . '<br />'; } /** * Filters the published time of the post. * * @since 2.5.1 * @since 5.5.0 Removed the difference between 'excerpt' and 'list' modes. * The published time and date are both displayed now, * which is equivalent to the previous 'excerpt' mode. * * @param string $t_time The published time. * @param WP_Post $post Post object. * @param string $column_name The column name. * @param string $mode The list display mode ('excerpt' or 'list'). */ echo apply_filters( 'post_date_column_time', $t_time, $post, 'date', $mode ); } /** * Handles the comments column output. * * @since 4.3.0 * * @param WP_Post $post The current WP_Post object. */ public function column_comments( $post ) { ?> <div class="post-com-count-wrapper"> <?php $pending_comments = isset( $this->comment_pending_count[ $post->ID ] ) ? $this->comment_pending_count[ $post->ID ] : 0; $this->comments_bubble( $post->ID, $pending_comments ); ?> </div> <?php } /** * Handles the post author column output. * * @since 4.3.0 * * @param WP_Post $post The current WP_Post object. */ public function column_author( $post ) { $args = array( 'post_type' => $post->post_type, 'author' => get_the_author_meta( 'ID' ), ); echo $this->get_edit_link( $args, get_the_author() ); } /** * Handles the default column output. * * @since 4.3.0 * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Post $item The current WP_Post object. * @param string $column_name The current column name. */ public function column_default( $item, $column_name ) { // Restores the more descriptive, specific name for use within this method. $post = $item; if ( 'categories' === $column_name ) { $taxonomy = 'category'; } elseif ( 'tags' === $column_name ) { $taxonomy = 'post_tag'; } elseif ( 0 === strpos( $column_name, 'taxonomy-' ) ) { $taxonomy = substr( $column_name, 9 ); } else { $taxonomy = false; } if ( $taxonomy ) { $taxonomy_object = get_taxonomy( $taxonomy ); $terms = get_the_terms( $post->ID, $taxonomy ); if ( is_array( $terms ) ) { $term_links = array(); foreach ( $terms as $t ) { $posts_in_term_qv = array(); if ( 'post' !== $post->post_type ) { $posts_in_term_qv['post_type'] = $post->post_type; } if ( $taxonomy_object->query_var ) { $posts_in_term_qv[ $taxonomy_object->query_var ] = $t->slug; } else { $posts_in_term_qv['taxonomy'] = $taxonomy; $posts_in_term_qv['term'] = $t->slug; } $label = esc_html( sanitize_term_field( 'name', $t->name, $t->term_id, $taxonomy, 'display' ) ); $term_links[] = $this->get_edit_link( $posts_in_term_qv, $label ); } /** * Filters the links in `$taxonomy` column of edit.php. * * @since 5.2.0 * * @param string[] $term_links Array of term editing links. * @param string $taxonomy Taxonomy name. * @param WP_Term[] $terms Array of term objects appearing in the post row. */ $term_links = apply_filters( 'post_column_taxonomy_links', $term_links, $taxonomy, $terms ); echo implode( wp_get_list_item_separator(), $term_links ); } else { echo '<span aria-hidden="true">&#8212;</span><span class="screen-reader-text">' . $taxonomy_object->labels->no_terms . '</span>'; } return; } if ( is_post_type_hierarchical( $post->post_type ) ) { /** * Fires in each custom column on the Posts list table. * * This hook only fires if the current post type is hierarchical, * such as pages. * * @since 2.5.0 * * @param string $column_name The name of the column to display. * @param int $post_id The current post ID. */ do_action( 'manage_pages_custom_column', $column_name, $post->ID ); } else { /** * Fires in each custom column in the Posts list table. * * This hook only fires if the current post type is non-hierarchical, * such as posts. * * @since 1.5.0 * * @param string $column_name The name of the column to display. * @param int $post_id The current post ID. */ do_action( 'manage_posts_custom_column', $column_name, $post->ID ); } /** * Fires for each custom column of a specific post type in the Posts list table. * * The dynamic portion of the hook name, `$post->post_type`, refers to the post type. * * Possible hook names include: * * - `manage_post_posts_custom_column` * - `manage_page_posts_custom_column` * * @since 3.1.0 * * @param string $column_name The name of the column to display. * @param int $post_id The current post ID. */ do_action( "manage_{$post->post_type}_posts_custom_column", $column_name, $post->ID ); } /** * @global WP_Post $post Global post object. * * @param int|WP_Post $post * @param int $level */ public function single_row( $post, $level = 0 ) { $global_post = get_post(); $post = get_post( $post ); $this->current_level = $level; $GLOBALS['post'] = $post; setup_postdata( $post ); $classes = 'iedit author-' . ( get_current_user_id() === (int) $post->post_author ? 'self' : 'other' ); $lock_holder = wp_check_post_lock( $post->ID ); if ( $lock_holder ) { $classes .= ' wp-locked'; } if ( $post->post_parent ) { $count = count( get_post_ancestors( $post->ID ) ); $classes .= ' level-' . $count; } else { $classes .= ' level-0'; } ?> <tr id="post-<?php echo $post->ID; ?>" class="<?php echo implode( ' ', get_post_class( $classes, $post->ID ) ); ?>"> <?php $this->single_row_columns( $post ); ?> </tr> <?php $GLOBALS['post'] = $global_post; } /** * Gets the name of the default primary column. * * @since 4.3.0 * * @return string Name of the default primary column, in this case, 'title'. */ protected function get_default_primary_column_name() { return 'title'; } /** * Generates and displays row action links. * * @since 4.3.0 * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Post $item Post being acted upon. * @param string $column_name Current column name. * @param string $primary Primary column name. * @return string Row actions output for posts, or an empty string * if the current column is not the primary column. */ protected function handle_row_actions( $item, $column_name, $primary ) { if ( $primary !== $column_name ) { return ''; } // Restores the more descriptive, specific name for use within this method. $post = $item; $post_type_object = get_post_type_object( $post->post_type ); $can_edit_post = current_user_can( 'edit_post', $post->ID ); $actions = array(); $title = _draft_or_post_title(); if ( $can_edit_post && 'trash' !== $post->post_status ) { $actions['edit'] = sprintf( '<a href="%s" aria-label="%s">%s</a>', get_edit_post_link( $post->ID ), /* translators: %s: Post title. */ esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $title ) ), __( 'Edit' ) ); if ( 'wp_block' !== $post->post_type ) { $actions['inline hide-if-no-js'] = sprintf( '<button type="button" class="button-link editinline" aria-label="%s" aria-expanded="false">%s</button>', /* translators: %s: Post title. */ esc_attr( sprintf( __( 'Quick edit &#8220;%s&#8221; inline' ), $title ) ), __( 'Quick&nbsp;Edit' ) ); } } if ( current_user_can( 'delete_post', $post->ID ) ) { if ( 'trash' === $post->post_status ) { $actions['untrash'] = sprintf( '<a href="%s" aria-label="%s">%s</a>', wp_nonce_url( admin_url( sprintf( $post_type_object->_edit_link . '&amp;action=untrash', $post->ID ) ), 'untrash-post_' . $post->ID ), /* translators: %s: Post title. */ esc_attr( sprintf( __( 'Restore &#8220;%s&#8221; from the Trash' ), $title ) ), __( 'Restore' ) ); } elseif ( EMPTY_TRASH_DAYS ) { $actions['trash'] = sprintf( '<a href="%s" class="submitdelete" aria-label="%s">%s</a>', get_delete_post_link( $post->ID ), /* translators: %s: Post title. */ esc_attr( sprintf( __( 'Move &#8220;%s&#8221; to the Trash' ), $title ) ), _x( 'Trash', 'verb' ) ); } if ( 'trash' === $post->post_status || ! EMPTY_TRASH_DAYS ) { $actions['delete'] = sprintf( '<a href="%s" class="submitdelete" aria-label="%s">%s</a>', get_delete_post_link( $post->ID, '', true ), /* translators: %s: Post title. */ esc_attr( sprintf( __( 'Delete &#8220;%s&#8221; permanently' ), $title ) ), __( 'Delete Permanently' ) ); } } if ( is_post_type_viewable( $post_type_object ) ) { if ( in_array( $post->post_status, array( 'pending', 'draft', 'future' ), true ) ) { if ( $can_edit_post ) { $preview_link = get_preview_post_link( $post ); $actions['view'] = sprintf( '<a href="%s" rel="bookmark" aria-label="%s">%s</a>', esc_url( $preview_link ), /* translators: %s: Post title. */ esc_attr( sprintf( __( 'Preview &#8220;%s&#8221;' ), $title ) ), __( 'Preview' ) ); } } elseif ( 'trash' !== $post->post_status ) { $actions['view'] = sprintf( '<a href="%s" rel="bookmark" aria-label="%s">%s</a>', get_permalink( $post->ID ), /* translators: %s: Post title. */ esc_attr( sprintf( __( 'View &#8220;%s&#8221;' ), $title ) ), __( 'View' ) ); } } if ( 'wp_block' === $post->post_type ) { $actions['export'] = sprintf( '<button type="button" class="wp-list-reusable-blocks__export button-link" data-id="%s" aria-label="%s">%s</button>', $post->ID, /* translators: %s: Post title. */ esc_attr( sprintf( __( 'Export &#8220;%s&#8221; as JSON' ), $title ) ), __( 'Export as JSON' ) ); } if ( is_post_type_hierarchical( $post->post_type ) ) { /** * Filters the array of row action links on the Pages list table. * * The filter is evaluated only for hierarchical post types. * * @since 2.8.0 * * @param string[] $actions An array of row action links. Defaults are * 'Edit', 'Quick Edit', 'Restore', 'Trash', * 'Delete Permanently', 'Preview', and 'View'. * @param WP_Post $post The post object. */ $actions = apply_filters( 'page_row_actions', $actions, $post ); } else { /** * Filters the array of row action links on the Posts list table. * * The filter is evaluated only for non-hierarchical post types. * * @since 2.8.0 * * @param string[] $actions An array of row action links. Defaults are * 'Edit', 'Quick Edit', 'Restore', 'Trash', * 'Delete Permanently', 'Preview', and 'View'. * @param WP_Post $post The post object. */ $actions = apply_filters( 'post_row_actions', $actions, $post ); } return $this->row_actions( $actions ); } /** * Outputs the hidden row displayed when inline editing * * @since 3.1.0 * * @global string $mode List table view mode. */ public function inline_edit() { global $mode; $screen = $this->screen; $post = get_default_post_to_edit( $screen->post_type ); $post_type_object = get_post_type_object( $screen->post_type ); $taxonomy_names = get_object_taxonomies( $screen->post_type ); $hierarchical_taxonomies = array(); $flat_taxonomies = array(); foreach ( $taxonomy_names as $taxonomy_name ) { $taxonomy = get_taxonomy( $taxonomy_name ); $show_in_quick_edit = $taxonomy->show_in_quick_edit; /** * Filters whether the current taxonomy should be shown in the Quick Edit panel. * * @since 4.2.0 * * @param bool $show_in_quick_edit Whether to show the current taxonomy in Quick Edit. * @param string $taxonomy_name Taxonomy name. * @param string $post_type Post type of current Quick Edit post. */ if ( ! apply_filters( 'quick_edit_show_taxonomy', $show_in_quick_edit, $taxonomy_name, $screen->post_type ) ) { continue; } if ( $taxonomy->hierarchical ) { $hierarchical_taxonomies[] = $taxonomy; } else { $flat_taxonomies[] = $taxonomy; } } $m = ( isset( $mode ) && 'excerpt' === $mode ) ? 'excerpt' : 'list'; $can_publish = current_user_can( $post_type_object->cap->publish_posts ); $core_columns = array( 'cb' => true, 'date' => true, 'title' => true, 'categories' => true, 'tags' => true, 'comments' => true, 'author' => true, ); ?> <form method="get"> <table style="display: none"><tbody id="inlineedit"> <?php $hclass = count( $hierarchical_taxonomies ) ? 'post' : 'page'; $inline_edit_classes = "inline-edit-row inline-edit-row-$hclass"; $bulk_edit_classes = "bulk-edit-row bulk-edit-row-$hclass bulk-edit-{$screen->post_type}"; $quick_edit_classes = "quick-edit-row quick-edit-row-$hclass inline-edit-{$screen->post_type}"; $bulk = 0; while ( $bulk < 2 ) : $classes = $inline_edit_classes . ' '; $classes .= $bulk ? $bulk_edit_classes : $quick_edit_classes; ?> <tr id="<?php echo $bulk ? 'bulk-edit' : 'inline-edit'; ?>" class="<?php echo $classes; ?>" style="display: none"> <td colspan="<?php echo $this->get_column_count(); ?>" class="colspanchange"> <div class="inline-edit-wrapper" role="region" aria-labelledby="<?php echo $bulk ? 'bulk' : 'quick'; ?>-edit-legend"> <fieldset class="inline-edit-col-left"> <legend class="inline-edit-legend" id="<?php echo $bulk ? 'bulk' : 'quick'; ?>-edit-legend"><?php echo $bulk ? __( 'Bulk Edit' ) : __( 'Quick Edit' ); ?></legend> <div class="inline-edit-col"> <?php if ( post_type_supports( $screen->post_type, 'title' ) ) : ?> <?php if ( $bulk ) : ?> <div id="bulk-title-div"> <div id="bulk-titles"></div> </div> <?php else : // $bulk ?> <label> <span class="title"><?php _e( 'Title' ); ?></span> <span class="input-text-wrap"><input type="text" name="post_title" class="ptitle" value="" /></span> </label> <?php if ( is_post_type_viewable( $screen->post_type ) ) : ?> <label> <span class="title"><?php _e( 'Slug' ); ?></span> <span class="input-text-wrap"><input type="text" name="post_name" value="" autocomplete="off" spellcheck="false" /></span> </label> <?php endif; // is_post_type_viewable() ?> <?php endif; // $bulk ?> <?php endif; // post_type_supports( ... 'title' ) ?> <?php if ( ! $bulk ) : ?> <fieldset class="inline-edit-date"> <legend><span class="title"><?php _e( 'Date' ); ?></span></legend> <?php touch_time( 1, 1, 0, 1 ); ?> </fieldset> <br class="clear" /> <?php endif; // $bulk ?> <?php if ( post_type_supports( $screen->post_type, 'author' ) ) { $authors_dropdown = ''; if ( current_user_can( $post_type_object->cap->edit_others_posts ) ) { $dropdown_name = 'post_author'; $dropdown_class = 'authors'; if ( wp_is_large_user_count() ) { $authors_dropdown = sprintf( '<select name="%s" class="%s hidden"></select>', esc_attr( $dropdown_name ), esc_attr( $dropdown_class ) ); } else { $users_opt = array( 'hide_if_only_one_author' => false, 'capability' => array( $post_type_object->cap->edit_posts ), 'name' => $dropdown_name, 'class' => $dropdown_class, 'multi' => 1, 'echo' => 0, 'show' => 'display_name_with_login', ); if ( $bulk ) { $users_opt['show_option_none'] = __( '&mdash; No Change &mdash;' ); } /** * Filters the arguments used to generate the Quick Edit authors drop-down. * * @since 5.6.0 * * @see wp_dropdown_users() * * @param array $users_opt An array of arguments passed to wp_dropdown_users(). * @param bool $bulk A flag to denote if it's a bulk action. */ $users_opt = apply_filters( 'quick_edit_dropdown_authors_args', $users_opt, $bulk ); $authors = wp_dropdown_users( $users_opt ); if ( $authors ) { $authors_dropdown = '<label class="inline-edit-author">'; $authors_dropdown .= '<span class="title">' . __( 'Author' ) . '</span>'; $authors_dropdown .= $authors; $authors_dropdown .= '</label>'; } } } // current_user_can( 'edit_others_posts' ) if ( ! $bulk ) { echo $authors_dropdown; } } // post_type_supports( ... 'author' ) ?> <?php if ( ! $bulk && $can_publish ) : ?> <div class="inline-edit-group wp-clearfix"> <label class="alignleft"> <span class="title"><?php _e( 'Password' ); ?></span> <span class="input-text-wrap"><input type="text" name="post_password" class="inline-edit-password-input" value="" /></span> </label> <span class="alignleft inline-edit-or"> <?php /* translators: Between password field and private checkbox on post quick edit interface. */ _e( '&ndash;OR&ndash;' ); ?> </span> <label class="alignleft inline-edit-private"> <input type="checkbox" name="keep_private" value="private" /> <span class="checkbox-title"><?php _e( 'Private' ); ?></span> </label> </div> <?php endif; ?> </div> </fieldset> <?php if ( count( $hierarchical_taxonomies ) && ! $bulk ) : ?> <fieldset class="inline-edit-col-center inline-edit-categories"> <div class="inline-edit-col"> <?php foreach ( $hierarchical_taxonomies as $taxonomy ) : ?> <span class="title inline-edit-categories-label"><?php echo esc_html( $taxonomy->labels->name ); ?></span> <input type="hidden" name="<?php echo ( 'category' === $taxonomy->name ) ? 'post_category[]' : 'tax_input[' . esc_attr( $taxonomy->name ) . '][]'; ?>" value="0" /> <ul class="cat-checklist <?php echo esc_attr( $taxonomy->name ); ?>-checklist"> <?php wp_terms_checklist( 0, array( 'taxonomy' => $taxonomy->name ) ); ?> </ul> <?php endforeach; // $hierarchical_taxonomies as $taxonomy ?> </div> </fieldset> <?php endif; // count( $hierarchical_taxonomies ) && ! $bulk ?> <fieldset class="inline-edit-col-right"> <div class="inline-edit-col"> <?php if ( post_type_supports( $screen->post_type, 'author' ) && $bulk ) { echo $authors_dropdown; } ?> <?php if ( post_type_supports( $screen->post_type, 'page-attributes' ) ) : ?> <?php if ( $post_type_object->hierarchical ) : ?> <label> <span class="title"><?php _e( 'Parent' ); ?></span> <?php $dropdown_args = array( 'post_type' => $post_type_object->name, 'selected' => $post->post_parent, 'name' => 'post_parent', 'show_option_none' => __( 'Main Page (no parent)' ), 'option_none_value' => 0, 'sort_column' => 'menu_order, post_title', ); if ( $bulk ) { $dropdown_args['show_option_no_change'] = __( '&mdash; No Change &mdash;' ); } /** * Filters the arguments used to generate the Quick Edit page-parent drop-down. * * @since 2.7.0 * @since 5.6.0 The `$bulk` parameter was added. * * @see wp_dropdown_pages() * * @param array $dropdown_args An array of arguments passed to wp_dropdown_pages(). * @param bool $bulk A flag to denote if it's a bulk action. */ $dropdown_args = apply_filters( 'quick_edit_dropdown_pages_args', $dropdown_args, $bulk ); wp_dropdown_pages( $dropdown_args ); ?> </label> <?php endif; // hierarchical ?> <?php if ( ! $bulk ) : ?> <label> <span class="title"><?php _e( 'Order' ); ?></span> <span class="input-text-wrap"><input type="text" name="menu_order" class="inline-edit-menu-order-input" value="<?php echo $post->menu_order; ?>" /></span> </label> <?php endif; // ! $bulk ?> <?php endif; // post_type_supports( ... 'page-attributes' ) ?> <?php if ( 0 < count( get_page_templates( null, $screen->post_type ) ) ) : ?> <label> <span class="title"><?php _e( 'Template' ); ?></span> <select name="page_template"> <?php if ( $bulk ) : ?> <option value="-1"><?php _e( '&mdash; No Change &mdash;' ); ?></option> <?php endif; // $bulk ?> <?php /** This filter is documented in wp-admin/includes/meta-boxes.php */ $default_title = apply_filters( 'default_page_template_title', __( 'Default template' ), 'quick-edit' ); ?> <option value="default"><?php echo esc_html( $default_title ); ?></option> <?php page_template_dropdown( '', $screen->post_type ); ?> </select> </label> <?php endif; ?> <?php if ( count( $flat_taxonomies ) && ! $bulk ) : ?> <?php foreach ( $flat_taxonomies as $taxonomy ) : ?> <?php if ( current_user_can( $taxonomy->cap->assign_terms ) ) : ?> <?php $taxonomy_name = esc_attr( $taxonomy->name ); ?> <div class="inline-edit-tags-wrap"> <label class="inline-edit-tags"> <span class="title"><?php echo esc_html( $taxonomy->labels->name ); ?></span> <textarea data-wp-taxonomy="<?php echo $taxonomy_name; ?>" cols="22" rows="1" name="tax_input[<?php echo esc_attr( $taxonomy->name ); ?>]" class="tax_input_<?php echo esc_attr( $taxonomy->name ); ?>" aria-describedby="inline-edit-<?php echo esc_attr( $taxonomy->name ); ?>-desc"></textarea> </label> <p class="howto" id="inline-edit-<?php echo esc_attr( $taxonomy->name ); ?>-desc"><?php echo esc_html( $taxonomy->labels->separate_items_with_commas ); ?></p> </div> <?php endif; // current_user_can( 'assign_terms' ) ?> <?php endforeach; // $flat_taxonomies as $taxonomy ?> <?php endif; // count( $flat_taxonomies ) && ! $bulk ?> <?php if ( post_type_supports( $screen->post_type, 'comments' ) || post_type_supports( $screen->post_type, 'trackbacks' ) ) : ?> <?php if ( $bulk ) : ?> <div class="inline-edit-group wp-clearfix"> <?php if ( post_type_supports( $screen->post_type, 'comments' ) ) : ?> <label class="alignleft"> <span class="title"><?php _e( 'Comments' ); ?></span> <select name="comment_status"> <option value=""><?php _e( '&mdash; No Change &mdash;' ); ?></option> <option value="open"><?php _e( 'Allow' ); ?></option> <option value="closed"><?php _e( 'Do not allow' ); ?></option> </select> </label> <?php endif; ?> <?php if ( post_type_supports( $screen->post_type, 'trackbacks' ) ) : ?> <label class="alignright"> <span class="title"><?php _e( 'Pings' ); ?></span> <select name="ping_status"> <option value=""><?php _e( '&mdash; No Change &mdash;' ); ?></option> <option value="open"><?php _e( 'Allow' ); ?></option> <option value="closed"><?php _e( 'Do not allow' ); ?></option> </select> </label> <?php endif; ?> </div> <?php else : // $bulk ?> <div class="inline-edit-group wp-clearfix"> <?php if ( post_type_supports( $screen->post_type, 'comments' ) ) : ?> <label class="alignleft"> <input type="checkbox" name="comment_status" value="open" /> <span class="checkbox-title"><?php _e( 'Allow Comments' ); ?></span> </label> <?php endif; ?> <?php if ( post_type_supports( $screen->post_type, 'trackbacks' ) ) : ?> <label class="alignleft"> <input type="checkbox" name="ping_status" value="open" /> <span class="checkbox-title"><?php _e( 'Allow Pings' ); ?></span> </label> <?php endif; ?> </div> <?php endif; // $bulk ?> <?php endif; // post_type_supports( ... comments or pings ) ?> <div class="inline-edit-group wp-clearfix"> <label class="inline-edit-status alignleft"> <span class="title"><?php _e( 'Status' ); ?></span> <select name="_status"> <?php if ( $bulk ) : ?> <option value="-1"><?php _e( '&mdash; No Change &mdash;' ); ?></option> <?php endif; // $bulk ?> <?php if ( $can_publish ) : // Contributors only get "Unpublished" and "Pending Review". ?> <option value="publish"><?php _e( 'Published' ); ?></option> <option value="future"><?php _e( 'Scheduled' ); ?></option> <?php if ( $bulk ) : ?> <option value="private"><?php _e( 'Private' ); ?></option> <?php endif; // $bulk ?> <?php endif; ?> <option value="pending"><?php _e( 'Pending Review' ); ?></option> <option value="draft"><?php _e( 'Draft' ); ?></option> </select> </label> <?php if ( 'post' === $screen->post_type && $can_publish && current_user_can( $post_type_object->cap->edit_others_posts ) ) : ?> <?php if ( $bulk ) : ?> <label class="alignright"> <span class="title"><?php _e( 'Sticky' ); ?></span> <select name="sticky"> <option value="-1"><?php _e( '&mdash; No Change &mdash;' ); ?></option> <option value="sticky"><?php _e( 'Sticky' ); ?></option> <option value="unsticky"><?php _e( 'Not Sticky' ); ?></option> </select> </label> <?php else : // $bulk ?> <label class="alignleft"> <input type="checkbox" name="sticky" value="sticky" /> <span class="checkbox-title"><?php _e( 'Make this post sticky' ); ?></span> </label> <?php endif; // $bulk ?> <?php endif; // 'post' && $can_publish && current_user_can( 'edit_others_posts' ) ?> </div> <?php if ( $bulk && current_theme_supports( 'post-formats' ) && post_type_supports( $screen->post_type, 'post-formats' ) ) : ?> <?php $post_formats = get_theme_support( 'post-formats' ); ?> <label class="alignleft"> <span class="title"><?php _ex( 'Format', 'post format' ); ?></span> <select name="post_format"> <option value="-1"><?php _e( '&mdash; No Change &mdash;' ); ?></option> <option value="0"><?php echo get_post_format_string( 'standard' ); ?></option> <?php if ( is_array( $post_formats[0] ) ) : ?> <?php foreach ( $post_formats[0] as $format ) : ?> <option value="<?php echo esc_attr( $format ); ?>"><?php echo esc_html( get_post_format_string( $format ) ); ?></option> <?php endforeach; ?> <?php endif; ?> </select> </label> <?php endif; ?> </div> </fieldset> <?php list( $columns ) = $this->get_column_info(); foreach ( $columns as $column_name => $column_display_name ) { if ( isset( $core_columns[ $column_name ] ) ) { continue; } if ( $bulk ) { /** * Fires once for each column in Bulk Edit mode. * * @since 2.7.0 * * @param string $column_name Name of the column to edit. * @param string $post_type The post type slug. */ do_action( 'bulk_edit_custom_box', $column_name, $screen->post_type ); } else { /** * Fires once for each column in Quick Edit mode. * * @since 2.7.0 * * @param string $column_name Name of the column to edit. * @param string $post_type The post type slug, or current screen name if this is a taxonomy list table. * @param string $taxonomy The taxonomy name, if any. */ do_action( 'quick_edit_custom_box', $column_name, $screen->post_type, '' ); } } ?> <div class="submit inline-edit-save"> <?php if ( ! $bulk ) : ?> <?php wp_nonce_field( 'inlineeditnonce', '_inline_edit', false ); ?> <button type="button" class="button button-primary save"><?php _e( 'Update' ); ?></button> <?php else : ?> <?php submit_button( __( 'Update' ), 'primary', 'bulk_edit', false ); ?> <?php endif; ?> <button type="button" class="button cancel"><?php _e( 'Cancel' ); ?></button> <?php if ( ! $bulk ) : ?> <span class="spinner"></span> <?php endif; ?> <input type="hidden" name="post_view" value="<?php echo esc_attr( $m ); ?>" /> <input type="hidden" name="screen" value="<?php echo esc_attr( $screen->id ); ?>" /> <?php if ( ! $bulk && ! post_type_supports( $screen->post_type, 'author' ) ) : ?> <input type="hidden" name="post_author" value="<?php echo esc_attr( $post->post_author ); ?>" /> <?php endif; ?> <div class="notice notice-error notice-alt inline hidden"> <p class="error"></p> </div> </div> </div> <!-- end of .inline-edit-wrapper --> </td></tr> <?php $bulk++; endwhile; ?> </tbody></table> </form> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_List\_Table](wp_list_table) wp-admin/includes/class-wp-list-table.php | Base class for displaying a list of items in an ajaxified HTML table. | | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
programming_docs
wordpress class Requests_Exception_HTTP_500 {} class Requests\_Exception\_HTTP\_500 {} ======================================= Exception for 500 Internal Server Error responses File: `wp-includes/Requests/Exception/HTTP/500.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/500.php/) ``` class Requests_Exception_HTTP_500 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 500; /** * Reason phrase * * @var string */ protected $reason = 'Internal Server Error'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_Styles {} class WP\_Styles {} =================== Core class used to register styles. * [WP\_Dependencies](wp_dependencies) `WP_Styles` is a class that helps developers interact with a theme. It ensures registered stylesheets are output in the proper order, with dependent stylesheets coming after their dependencies. While more than one instance can be created, typically the global $wp\_styles is used to enqueue stylesheets, which are then output by `wp_print_styles` during the [wp\_head](../hooks/wp_head "Plugin API/Action Reference/wp head") action. `WP_Styles` extends `[WP\_Dependencies](wp_dependencies "Class Reference/WP Dependencies")`. `WP_Styles` handles both external and embedded stylesheets (though the latter must be associated with one of the former), outputting a <link> or <style> element as appropriate. For any stylesheet, an additional stylesheet can be loaded for right-to-left text (triggered by setting $wp\_styles->text\_direction to β€˜rtl’). The URL for this stylesheet is built by inserting β€˜-rtl’ into the URL of the left-to-right stylesheet. Normally, β€˜-rtl’ is inserted before the β€˜.css’ extension. If β€˜suffix’ is set in the stylesheet’s extra data (using `WP_Dependencies::add_data()` or `_WP_Dependency::add_data()`), β€˜-rtl’ will be inserted before the suffix and β€˜.css’ extension (`"${suffix}.css"`). When it comes time to output enqueued stylesheets, `WP_Styles` can print them, or accumulate them in instance variables ($print\_html for external and $print\_code for embedded). This behaviour is controlled by the boolean instance variable $do\_concat. If true, output is concatenated to the appropriate instance variable; if false, it’s printed. Any [unconditional](http://msdn.microsoft.com/en-us/library/ms537512.aspx), non-[alternate](http://www.w3.org/Style/Examples/007/alternatives.en.html) stylesheet in a default directory (as determined by `WP_Styles::in_default_dir()`) isn’t accumulated when $do\_concat is true. The media for a stylesheet is passed via the $args argument to `[WP\_Dependencies](wp_dependencies "Class Reference/WP Dependencies")::add()`. Note: Refer source code for the complete list of properties and hooks. $base\_url The base URL for the site, it gets prepended to the URL for an enqueued sheet in most cases (see $content\_url for an exception). Set to the site URL (as determined by `[site\_url()](../functions/site_url "Function Reference/site url")` or `wp_guess_url()`) by default. $content\_url The URL for the wp-content directory. Set to `WP_CONTENT_URL` by default. If a stylesheet URL begins with the content URL, the base URL isn’t prepended. $default\_version Default value used when a version isn’t specified in a call to [wp\_enqueue\_style()](../functions/wp_enqueue_style) or [wp\_register\_style()](../functions/wp_register_style) . $text\_direction = β€˜ltr’ If β€˜rtl’, an addtional stylesheet will be loaded, allowing custom styling targeting right-to-left. $do\_concat = false If true, concatenate output to $print\_html and $print\_code member variables rather than printing it. $print\_html = β€œβ€ holds accumulated HTML (<link> elements and conditional comments). $print\_code = β€œβ€ holds accumulated embedded style rules. $concat = β€œβ€ list of item handles that were accumulated, separated by commas. $concat\_version = β€œβ€ list of item handles & versions that were accumulated. $default\_dirs Path or array of paths. Used by `WP_Styles::in_default_dir()`. Compared directly to $src property of a stylesheet. Note: Refer source code for the complete list of hooks. * wp\_default\_styles – Invoked when a [WP\_Styles](wp_styles) is created. The instance is passed to action hooks. * print\_styles\_array – Filters list of stylesheets to be output. Called from `WP_Styles::all_deps()`. * style\_loader\_src – Filter a stylesheet URL in preparation for output. Happens after $base\_url has been prepended (if warranted). * style\_loader\_tag – Filter the <link> element for a stylesheet. * [\_\_construct](wp_styles/__construct) β€” Constructor. * [\_css\_href](wp_styles/_css_href) β€” Generates an enqueued style's fully-qualified URL. * [add\_inline\_style](wp_styles/add_inline_style) β€” Adds extra CSS styles to a registered stylesheet. * [all\_deps](wp_styles/all_deps) β€” Determines style dependencies. * [do\_footer\_items](wp_styles/do_footer_items) β€” Processes items and dependencies for the footer group. * [do\_item](wp_styles/do_item) β€” Processes a style dependency. * [in\_default\_dir](wp_styles/in_default_dir) β€” Whether a handle's source is in a default directory. * [print\_inline\_style](wp_styles/print_inline_style) β€” Prints extra CSS styles of a registered stylesheet. * [reset](wp_styles/reset) β€” Resets class properties. File: `wp-includes/class-wp-styles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes_class-wp-styles-php-2/) ``` class WP_Styles extends WP_Dependencies { /** * Base URL for styles. * * Full URL with trailing slash. * * @since 2.6.0 * @var string */ public $base_url; /** * URL of the content directory. * * @since 2.8.0 * @var string */ public $content_url; /** * Default version string for stylesheets. * * @since 2.6.0 * @var string */ public $default_version; /** * The current text direction. * * @since 2.6.0 * @var string */ public $text_direction = 'ltr'; /** * Holds a list of style handles which will be concatenated. * * @since 2.8.0 * @var string */ public $concat = ''; /** * Holds a string which contains style handles and their version. * * @since 2.8.0 * @deprecated 3.4.0 * @var string */ public $concat_version = ''; /** * Whether to perform concatenation. * * @since 2.8.0 * @var bool */ public $do_concat = false; /** * Holds HTML markup of styles and additional data if concatenation * is enabled. * * @since 2.8.0 * @var string */ public $print_html = ''; /** * Holds inline styles if concatenation is enabled. * * @since 3.3.0 * @var string */ public $print_code = ''; /** * List of default directories. * * @since 2.8.0 * @var array */ public $default_dirs; /** * Holds a string which contains the type attribute for style tag. * * If the active theme does not declare HTML5 support for 'style', * then it initializes as `type='text/css'`. * * @since 5.3.0 * @var string */ private $type_attr = ''; /** * Constructor. * * @since 2.6.0 */ public function __construct() { if ( function_exists( 'is_admin' ) && ! is_admin() && function_exists( 'current_theme_supports' ) && ! current_theme_supports( 'html5', 'style' ) ) { $this->type_attr = " type='text/css'"; } /** * Fires when the WP_Styles instance is initialized. * * @since 2.6.0 * * @param WP_Styles $wp_styles WP_Styles instance (passed by reference). */ do_action_ref_array( 'wp_default_styles', array( &$this ) ); } /** * Processes a style dependency. * * @since 2.6.0 * @since 5.5.0 Added the `$group` parameter. * * @see WP_Dependencies::do_item() * * @param string $handle The style's registered handle. * @param int|false $group Optional. Group level: level (int), no groups (false). * Default false. * @return bool True on success, false on failure. */ public function do_item( $handle, $group = false ) { if ( ! parent::do_item( $handle ) ) { return false; } $obj = $this->registered[ $handle ]; if ( null === $obj->ver ) { $ver = ''; } else { $ver = $obj->ver ? $obj->ver : $this->default_version; } if ( isset( $this->args[ $handle ] ) ) { $ver = $ver ? $ver . '&amp;' . $this->args[ $handle ] : $this->args[ $handle ]; } $src = $obj->src; $cond_before = ''; $cond_after = ''; $conditional = isset( $obj->extra['conditional'] ) ? $obj->extra['conditional'] : ''; if ( $conditional ) { $cond_before = "<!--[if {$conditional}]>\n"; $cond_after = "<![endif]-->\n"; } $inline_style = $this->print_inline_style( $handle, false ); if ( $inline_style ) { $inline_style_tag = sprintf( "<style id='%s-inline-css'%s>\n%s\n</style>\n", esc_attr( $handle ), $this->type_attr, $inline_style ); } else { $inline_style_tag = ''; } if ( $this->do_concat ) { if ( $this->in_default_dir( $src ) && ! $conditional && ! isset( $obj->extra['alt'] ) ) { $this->concat .= "$handle,"; $this->concat_version .= "$handle$ver"; $this->print_code .= $inline_style; return true; } } if ( isset( $obj->args ) ) { $media = esc_attr( $obj->args ); } else { $media = 'all'; } // A single item may alias a set of items, by having dependencies, but no source. if ( ! $src ) { if ( $inline_style_tag ) { if ( $this->do_concat ) { $this->print_html .= $inline_style_tag; } else { echo $inline_style_tag; } } return true; } $href = $this->_css_href( $src, $ver, $handle ); if ( ! $href ) { return true; } $rel = isset( $obj->extra['alt'] ) && $obj->extra['alt'] ? 'alternate stylesheet' : 'stylesheet'; $title = isset( $obj->extra['title'] ) ? sprintf( " title='%s'", esc_attr( $obj->extra['title'] ) ) : ''; $tag = sprintf( "<link rel='%s' id='%s-css'%s href='%s'%s media='%s' />\n", $rel, $handle, $title, $href, $this->type_attr, $media ); /** * Filters the HTML link tag of an enqueued style. * * @since 2.6.0 * @since 4.3.0 Introduced the `$href` parameter. * @since 4.5.0 Introduced the `$media` parameter. * * @param string $tag The link tag for the enqueued style. * @param string $handle The style's registered handle. * @param string $href The stylesheet's source URL. * @param string $media The stylesheet's media attribute. */ $tag = apply_filters( 'style_loader_tag', $tag, $handle, $href, $media ); if ( 'rtl' === $this->text_direction && isset( $obj->extra['rtl'] ) && $obj->extra['rtl'] ) { if ( is_bool( $obj->extra['rtl'] ) || 'replace' === $obj->extra['rtl'] ) { $suffix = isset( $obj->extra['suffix'] ) ? $obj->extra['suffix'] : ''; $rtl_href = str_replace( "{$suffix}.css", "-rtl{$suffix}.css", $this->_css_href( $src, $ver, "$handle-rtl" ) ); } else { $rtl_href = $this->_css_href( $obj->extra['rtl'], $ver, "$handle-rtl" ); } $rtl_tag = sprintf( "<link rel='%s' id='%s-rtl-css'%s href='%s'%s media='%s' />\n", $rel, $handle, $title, $rtl_href, $this->type_attr, $media ); /** This filter is documented in wp-includes/class-wp-styles.php */ $rtl_tag = apply_filters( 'style_loader_tag', $rtl_tag, $handle, $rtl_href, $media ); if ( 'replace' === $obj->extra['rtl'] ) { $tag = $rtl_tag; } else { $tag .= $rtl_tag; } } if ( $this->do_concat ) { $this->print_html .= $cond_before; $this->print_html .= $tag; if ( $inline_style_tag ) { $this->print_html .= $inline_style_tag; } $this->print_html .= $cond_after; } else { echo $cond_before; echo $tag; $this->print_inline_style( $handle ); echo $cond_after; } return true; } /** * Adds extra CSS styles to a registered stylesheet. * * @since 3.3.0 * * @param string $handle The style's registered handle. * @param string $code String containing the CSS styles to be added. * @return bool True on success, false on failure. */ public function add_inline_style( $handle, $code ) { if ( ! $code ) { return false; } $after = $this->get_data( $handle, 'after' ); if ( ! $after ) { $after = array(); } $after[] = $code; return $this->add_data( $handle, 'after', $after ); } /** * Prints extra CSS styles of a registered stylesheet. * * @since 3.3.0 * * @param string $handle The style's registered handle. * @param bool $display Optional. Whether to print the inline style * instead of just returning it. Default true. * @return string|bool False if no data exists, inline styles if `$display` is true, * true otherwise. */ public function print_inline_style( $handle, $display = true ) { $output = $this->get_data( $handle, 'after' ); if ( empty( $output ) ) { return false; } $output = implode( "\n", $output ); if ( ! $display ) { return $output; } printf( "<style id='%s-inline-css'%s>\n%s\n</style>\n", esc_attr( $handle ), $this->type_attr, $output ); return true; } /** * Determines style dependencies. * * @since 2.6.0 * * @see WP_Dependencies::all_deps() * * @param string|string[] $handles Item handle (string) or item handles (array of strings). * @param bool $recursion Optional. Internal flag that function is calling itself. * Default false. * @param int|false $group Optional. Group level: level (int), no groups (false). * Default false. * @return bool True on success, false on failure. */ public function all_deps( $handles, $recursion = false, $group = false ) { $r = parent::all_deps( $handles, $recursion, $group ); if ( ! $recursion ) { /** * Filters the array of enqueued styles before processing for output. * * @since 2.6.0 * * @param string[] $to_do The list of enqueued style handles about to be processed. */ $this->to_do = apply_filters( 'print_styles_array', $this->to_do ); } return $r; } /** * Generates an enqueued style's fully-qualified URL. * * @since 2.6.0 * * @param string $src The source of the enqueued style. * @param string $ver The version of the enqueued style. * @param string $handle The style's registered handle. * @return string Style's fully-qualified URL. */ public function _css_href( $src, $ver, $handle ) { if ( ! is_bool( $src ) && ! preg_match( '|^(https?:)?//|', $src ) && ! ( $this->content_url && 0 === strpos( $src, $this->content_url ) ) ) { $src = $this->base_url . $src; } if ( ! empty( $ver ) ) { $src = add_query_arg( 'ver', $ver, $src ); } /** * Filters an enqueued style's fully-qualified URL. * * @since 2.6.0 * * @param string $src The source URL of the enqueued style. * @param string $handle The style's registered handle. */ $src = apply_filters( 'style_loader_src', $src, $handle ); return esc_url( $src ); } /** * Whether a handle's source is in a default directory. * * @since 2.8.0 * * @param string $src The source of the enqueued style. * @return bool True if found, false if not. */ public function in_default_dir( $src ) { if ( ! $this->default_dirs ) { return true; } foreach ( (array) $this->default_dirs as $test ) { if ( 0 === strpos( $src, $test ) ) { return true; } } return false; } /** * Processes items and dependencies for the footer group. * * HTML 5 allows styles in the body, grab late enqueued items and output them in the footer. * * @since 3.3.0 * * @see WP_Dependencies::do_items() * * @return string[] Handles of items that have been processed. */ public function do_footer_items() { $this->do_items( false, 1 ); return $this->done; } /** * Resets class properties. * * @since 3.3.0 */ public function reset() { $this->do_concat = false; $this->concat = ''; $this->concat_version = ''; $this->print_html = ''; } } ``` | Uses | Description | | --- | --- | | [WP\_Dependencies](wp_dependencies) wp-includes/class-wp-dependencies.php | Core base class extended to register items. | | Version | Description | | --- | --- | | [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. | wordpress class WP_Widget_Recent_Posts {} class WP\_Widget\_Recent\_Posts {} ================================== Core class used to implement a Recent Posts widget. * [WP\_Widget](wp_widget) * [\_\_construct](wp_widget_recent_posts/__construct) β€” Sets up a new Recent Posts widget instance. * [form](wp_widget_recent_posts/form) β€” Outputs the settings form for the Recent Posts widget. * [update](wp_widget_recent_posts/update) β€” Handles updating the settings for the current Recent Posts widget instance. * [widget](wp_widget_recent_posts/widget) β€” Outputs the content for the current Recent Posts widget instance. File: `wp-includes/widgets/class-wp-widget-recent-posts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-recent-posts.php/) ``` class WP_Widget_Recent_Posts extends WP_Widget { /** * Sets up a new Recent Posts widget instance. * * @since 2.8.0 */ public function __construct() { $widget_ops = array( 'classname' => 'widget_recent_entries', 'description' => __( 'Your site&#8217;s most recent Posts.' ), 'customize_selective_refresh' => true, 'show_instance_in_rest' => true, ); parent::__construct( 'recent-posts', __( 'Recent Posts' ), $widget_ops ); $this->alt_option_name = 'widget_recent_entries'; } /** * Outputs the content for the current Recent Posts widget instance. * * @since 2.8.0 * * @param array $args Display arguments including 'before_title', 'after_title', * 'before_widget', and 'after_widget'. * @param array $instance Settings for the current Recent Posts widget instance. */ public function widget( $args, $instance ) { if ( ! isset( $args['widget_id'] ) ) { $args['widget_id'] = $this->id; } $default_title = __( 'Recent Posts' ); $title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : $default_title; /** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */ $title = apply_filters( 'widget_title', $title, $instance, $this->id_base ); $number = ( ! empty( $instance['number'] ) ) ? absint( $instance['number'] ) : 5; if ( ! $number ) { $number = 5; } $show_date = isset( $instance['show_date'] ) ? $instance['show_date'] : false; $r = new WP_Query( /** * Filters the arguments for the Recent Posts widget. * * @since 3.4.0 * @since 4.9.0 Added the `$instance` parameter. * * @see WP_Query::get_posts() * * @param array $args An array of arguments used to retrieve the recent posts. * @param array $instance Array of settings for the current widget. */ apply_filters( 'widget_posts_args', array( 'posts_per_page' => $number, 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true, ), $instance ) ); if ( ! $r->have_posts() ) { return; } ?> <?php echo $args['before_widget']; ?> <?php 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 ) . '">'; } ?> <ul> <?php foreach ( $r->posts as $recent_post ) : ?> <?php $post_title = get_the_title( $recent_post->ID ); $title = ( ! empty( $post_title ) ) ? $post_title : __( '(no title)' ); $aria_current = ''; if ( get_queried_object_id() === $recent_post->ID ) { $aria_current = ' aria-current="page"'; } ?> <li> <a href="<?php the_permalink( $recent_post->ID ); ?>"<?php echo $aria_current; ?>><?php echo $title; ?></a> <?php if ( $show_date ) : ?> <span class="post-date"><?php echo get_the_date( '', $recent_post->ID ); ?></span> <?php endif; ?> </li> <?php endforeach; ?> </ul> <?php if ( 'html5' === $format ) { echo '</nav>'; } echo $args['after_widget']; } /** * Handles updating the settings for the current Recent Posts widget instance. * * @since 2.8.0 * * @param array $new_instance New settings for this instance as input by the user via * WP_Widget::form(). * @param array $old_instance Old settings for this instance. * @return array Updated settings to save. */ public function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = sanitize_text_field( $new_instance['title'] ); $instance['number'] = (int) $new_instance['number']; $instance['show_date'] = isset( $new_instance['show_date'] ) ? (bool) $new_instance['show_date'] : false; return $instance; } /** * Outputs the settings form for the Recent Posts widget. * * @since 2.8.0 * * @param array $instance Current settings. */ public function form( $instance ) { $title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : ''; $number = isset( $instance['number'] ) ? absint( $instance['number'] ) : 5; $show_date = isset( $instance['show_date'] ) ? (bool) $instance['show_date'] : false; ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e( 'Number of posts to show:' ); ?></label> <input class="tiny-text" id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" type="number" step="1" min="1" value="<?php echo $number; ?>" size="3" /> </p> <p> <input class="checkbox" type="checkbox"<?php checked( $show_date ); ?> id="<?php echo $this->get_field_id( 'show_date' ); ?>" name="<?php echo $this->get_field_name( 'show_date' ); ?>" /> <label for="<?php echo $this->get_field_id( 'show_date' ); ?>"><?php _e( 'Display post date?' ); ?></label> </p> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Widget](wp_widget) wp-includes/class-wp-widget.php | Core base class extended to register widgets. | | Version | Description | | --- | --- | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
programming_docs
wordpress class Core_Upgrader {} class Core\_Upgrader {} ======================= Core class used for updating core. It allows for WordPress to upgrade itself in combination with the wp-admin/includes/update-core.php file. * [WP\_Upgrader](wp_upgrader) * [check\_files](core_upgrader/check_files) β€” Compare the disk file checksums against the expected checksums. * [should\_update\_to\_version](core_upgrader/should_update_to_version) β€” Determines if this WordPress Core version should update to an offered version or not. * [upgrade](core_upgrader/upgrade) β€” Upgrade WordPress core. * [upgrade\_strings](core_upgrader/upgrade_strings) β€” Initialize the upgrade strings. File: `wp-admin/includes/class-core-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-core-upgrader.php/) ``` class Core_Upgrader extends WP_Upgrader { /** * Initialize the upgrade strings. * * @since 2.8.0 */ public function upgrade_strings() { $this->strings['up_to_date'] = __( 'WordPress is at the latest version.' ); $this->strings['locked'] = __( 'Another update is currently in progress.' ); $this->strings['no_package'] = __( 'Update package not available.' ); /* translators: %s: Package URL. */ $this->strings['downloading_package'] = sprintf( __( 'Downloading update from %s&#8230;' ), '<span class="code">%s</span>' ); $this->strings['unpack_package'] = __( 'Unpacking the update&#8230;' ); $this->strings['copy_failed'] = __( 'Could not copy files.' ); $this->strings['copy_failed_space'] = __( 'Could not copy files. You may have run out of disk space.' ); $this->strings['start_rollback'] = __( 'Attempting to roll back to previous version.' ); $this->strings['rollback_was_required'] = __( 'Due to an error during updating, WordPress has rolled back to your previous version.' ); } /** * Upgrade WordPress core. * * @since 2.8.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * @global callable $_wp_filesystem_direct_method * * @param object $current Response object for whether WordPress is current. * @param array $args { * Optional. Arguments for upgrading WordPress core. Default empty array. * * @type bool $pre_check_md5 Whether to check the file checksums before * attempting the upgrade. Default true. * @type bool $attempt_rollback Whether to attempt to rollback the chances if * there is a problem. Default false. * @type bool $do_rollback Whether to perform this "upgrade" as a rollback. * Default false. * } * @return string|false|WP_Error New WordPress version on success, false or WP_Error on failure. */ public function upgrade( $current, $args = array() ) { global $wp_filesystem; require ABSPATH . WPINC . '/version.php'; // $wp_version; $start_time = time(); $defaults = array( 'pre_check_md5' => true, 'attempt_rollback' => false, 'do_rollback' => false, 'allow_relaxed_file_ownership' => false, ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->upgrade_strings(); // Is an update available? if ( ! isset( $current->response ) || 'latest' === $current->response ) { return new WP_Error( 'up_to_date', $this->strings['up_to_date'] ); } $res = $this->fs_connect( array( ABSPATH, WP_CONTENT_DIR ), $parsed_args['allow_relaxed_file_ownership'] ); if ( ! $res || is_wp_error( $res ) ) { return $res; } $wp_dir = trailingslashit( $wp_filesystem->abspath() ); $partial = true; if ( $parsed_args['do_rollback'] ) { $partial = false; } elseif ( $parsed_args['pre_check_md5'] && ! $this->check_files() ) { $partial = false; } /* * If partial update is returned from the API, use that, unless we're doing * a reinstallation. If we cross the new_bundled version number, then use * the new_bundled zip. Don't though if the constant is set to skip bundled items. * If the API returns a no_content zip, go with it. Finally, default to the full zip. */ if ( $parsed_args['do_rollback'] && $current->packages->rollback ) { $to_download = 'rollback'; } elseif ( $current->packages->partial && 'reinstall' !== $current->response && $wp_version === $current->partial_version && $partial ) { $to_download = 'partial'; } elseif ( $current->packages->new_bundled && version_compare( $wp_version, $current->new_bundled, '<' ) && ( ! defined( 'CORE_UPGRADE_SKIP_NEW_BUNDLED' ) || ! CORE_UPGRADE_SKIP_NEW_BUNDLED ) ) { $to_download = 'new_bundled'; } elseif ( $current->packages->no_content ) { $to_download = 'no_content'; } else { $to_download = 'full'; } // Lock to prevent multiple Core Updates occurring. $lock = WP_Upgrader::create_lock( 'core_updater', 15 * MINUTE_IN_SECONDS ); if ( ! $lock ) { return new WP_Error( 'locked', $this->strings['locked'] ); } $download = $this->download_package( $current->packages->$to_download, true ); // Allow for signature soft-fail. // WARNING: This may be removed in the future. if ( is_wp_error( $download ) && $download->get_error_data( 'softfail-filename' ) ) { // Output the failure error as a normal feedback, and not as an error: /** This filter is documented in wp-admin/includes/update-core.php */ apply_filters( 'update_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 ) ) { WP_Upgrader::release_lock( 'core_updater' ); return $download; } $working_dir = $this->unpack_package( $download ); if ( is_wp_error( $working_dir ) ) { WP_Upgrader::release_lock( 'core_updater' ); return $working_dir; } // Copy update-core.php from the new version into place. if ( ! $wp_filesystem->copy( $working_dir . '/wordpress/wp-admin/includes/update-core.php', $wp_dir . 'wp-admin/includes/update-core.php', true ) ) { $wp_filesystem->delete( $working_dir, true ); WP_Upgrader::release_lock( 'core_updater' ); return new WP_Error( 'copy_failed_for_update_core_file', __( 'The update cannot be installed because some files could not be copied. This is usually due to inconsistent file permissions.' ), 'wp-admin/includes/update-core.php' ); } $wp_filesystem->chmod( $wp_dir . 'wp-admin/includes/update-core.php', FS_CHMOD_FILE ); wp_opcache_invalidate( ABSPATH . 'wp-admin/includes/update-core.php' ); require_once ABSPATH . 'wp-admin/includes/update-core.php'; if ( ! function_exists( 'update_core' ) ) { WP_Upgrader::release_lock( 'core_updater' ); return new WP_Error( 'copy_failed_space', $this->strings['copy_failed_space'] ); } $result = update_core( $working_dir, $wp_dir ); // In the event of an issue, we may be able to roll back. if ( $parsed_args['attempt_rollback'] && $current->packages->rollback && ! $parsed_args['do_rollback'] ) { $try_rollback = false; if ( is_wp_error( $result ) ) { $error_code = $result->get_error_code(); /* * Not all errors are equal. These codes are critical: copy_failed__copy_dir, * mkdir_failed__copy_dir, copy_failed__copy_dir_retry, and disk_full. * do_rollback allows for update_core() to trigger a rollback if needed. */ if ( false !== strpos( $error_code, 'do_rollback' ) ) { $try_rollback = true; } elseif ( false !== strpos( $error_code, '__copy_dir' ) ) { $try_rollback = true; } elseif ( 'disk_full' === $error_code ) { $try_rollback = true; } } if ( $try_rollback ) { /** This filter is documented in wp-admin/includes/update-core.php */ apply_filters( 'update_feedback', $result ); /** This filter is documented in wp-admin/includes/update-core.php */ apply_filters( 'update_feedback', $this->strings['start_rollback'] ); $rollback_result = $this->upgrade( $current, array_merge( $parsed_args, array( 'do_rollback' => true ) ) ); $original_result = $result; $result = new WP_Error( 'rollback_was_required', $this->strings['rollback_was_required'], (object) array( 'update' => $original_result, 'rollback' => $rollback_result, ) ); } } /** This action is documented in wp-admin/includes/class-wp-upgrader.php */ do_action( 'upgrader_process_complete', $this, array( 'action' => 'update', 'type' => 'core', ) ); // Clear the current updates. delete_site_transient( 'update_core' ); if ( ! $parsed_args['do_rollback'] ) { $stats = array( 'update_type' => $current->response, 'success' => true, 'fs_method' => $wp_filesystem->method, 'fs_method_forced' => defined( 'FS_METHOD' ) || has_filter( 'filesystem_method' ), 'fs_method_direct' => ! empty( $GLOBALS['_wp_filesystem_direct_method'] ) ? $GLOBALS['_wp_filesystem_direct_method'] : '', 'time_taken' => time() - $start_time, 'reported' => $wp_version, 'attempted' => $current->version, ); if ( is_wp_error( $result ) ) { $stats['success'] = false; // Did a rollback occur? if ( ! empty( $try_rollback ) ) { $stats['error_code'] = $original_result->get_error_code(); $stats['error_data'] = $original_result->get_error_data(); // Was the rollback successful? If not, collect its error too. $stats['rollback'] = ! is_wp_error( $rollback_result ); if ( is_wp_error( $rollback_result ) ) { $stats['rollback_code'] = $rollback_result->get_error_code(); $stats['rollback_data'] = $rollback_result->get_error_data(); } } else { $stats['error_code'] = $result->get_error_code(); $stats['error_data'] = $result->get_error_data(); } } wp_version_check( $stats ); } WP_Upgrader::release_lock( 'core_updater' ); return $result; } /** * Determines if this WordPress Core version should update to an offered version or not. * * @since 3.7.0 * * @param string $offered_ver The offered version, of the format x.y.z. * @return bool True if we should update to the offered version, otherwise false. */ public static function should_update_to_version( $offered_ver ) { require ABSPATH . WPINC . '/version.php'; // $wp_version; // x.y.z $current_branch = implode( '.', array_slice( preg_split( '/[.-]/', $wp_version ), 0, 2 ) ); // x.y $new_branch = implode( '.', array_slice( preg_split( '/[.-]/', $offered_ver ), 0, 2 ) ); // x.y $current_is_development_version = (bool) strpos( $wp_version, '-' ); // Defaults: $upgrade_dev = get_site_option( 'auto_update_core_dev', 'enabled' ) === 'enabled'; $upgrade_minor = get_site_option( 'auto_update_core_minor', 'enabled' ) === 'enabled'; $upgrade_major = get_site_option( 'auto_update_core_major', 'unset' ) === 'enabled'; // WP_AUTO_UPDATE_CORE = true (all), 'beta', 'rc', 'development', 'branch-development', 'minor', false. if ( defined( 'WP_AUTO_UPDATE_CORE' ) ) { if ( false === WP_AUTO_UPDATE_CORE ) { // Defaults to turned off, unless a filter allows it. $upgrade_dev = false; $upgrade_minor = false; $upgrade_major = false; } elseif ( true === WP_AUTO_UPDATE_CORE || in_array( WP_AUTO_UPDATE_CORE, array( 'beta', 'rc', 'development', 'branch-development' ), true ) ) { // ALL updates for core. $upgrade_dev = true; $upgrade_minor = true; $upgrade_major = true; } elseif ( 'minor' === WP_AUTO_UPDATE_CORE ) { // Only minor updates for core. $upgrade_dev = false; $upgrade_minor = true; $upgrade_major = false; } } // 1: If we're already on that version, not much point in updating? if ( $offered_ver === $wp_version ) { return false; } // 2: If we're running a newer version, that's a nope. if ( version_compare( $wp_version, $offered_ver, '>' ) ) { return false; } $failure_data = get_site_option( 'auto_core_update_failed' ); if ( $failure_data ) { // If this was a critical update failure, cannot update. if ( ! empty( $failure_data['critical'] ) ) { return false; } // Don't claim we can update on update-core.php if we have a non-critical failure logged. if ( $wp_version === $failure_data['current'] && false !== strpos( $offered_ver, '.1.next.minor' ) ) { return false; } /* * Cannot update if we're retrying the same A to B update that caused a non-critical failure. * Some non-critical failures do allow retries, like download_failed. * 3.7.1 => 3.7.2 resulted in files_not_writable, if we are still on 3.7.1 and still trying to update to 3.7.2. */ if ( empty( $failure_data['retry'] ) && $wp_version === $failure_data['current'] && $offered_ver === $failure_data['attempted'] ) { return false; } } // 3: 3.7-alpha-25000 -> 3.7-alpha-25678 -> 3.7-beta1 -> 3.7-beta2. if ( $current_is_development_version ) { /** * Filters whether to enable automatic core updates for development versions. * * @since 3.7.0 * * @param bool $upgrade_dev Whether to enable automatic updates for * development versions. */ if ( ! apply_filters( 'allow_dev_auto_core_updates', $upgrade_dev ) ) { return false; } // Else fall through to minor + major branches below. } // 4: Minor in-branch updates (3.7.0 -> 3.7.1 -> 3.7.2 -> 3.7.4). if ( $current_branch === $new_branch ) { /** * Filters whether to enable minor automatic core updates. * * @since 3.7.0 * * @param bool $upgrade_minor Whether to enable minor automatic core updates. */ return apply_filters( 'allow_minor_auto_core_updates', $upgrade_minor ); } // 5: Major version updates (3.7.0 -> 3.8.0 -> 3.9.1). if ( version_compare( $new_branch, $current_branch, '>' ) ) { /** * Filters whether to enable major automatic core updates. * * @since 3.7.0 * * @param bool $upgrade_major Whether to enable major automatic core updates. */ return apply_filters( 'allow_major_auto_core_updates', $upgrade_major ); } // If we're not sure, we don't want it. return false; } /** * Compare the disk file checksums against the expected checksums. * * @since 3.7.0 * * @global string $wp_version The WordPress version string. * @global string $wp_local_package Locale code of the package. * * @return bool True if the checksums match, otherwise false. */ public function check_files() { global $wp_version, $wp_local_package; $checksums = get_core_checksums( $wp_version, isset( $wp_local_package ) ? $wp_local_package : 'en_US' ); if ( ! is_array( $checksums ) ) { return false; } foreach ( $checksums as $file => $checksum ) { // Skip files which get updated. if ( 'wp-content' === substr( $file, 0, 10 ) ) { continue; } if ( ! file_exists( ABSPATH . $file ) || md5_file( ABSPATH . $file ) !== $checksum ) { return false; } } return true; } } ``` | Uses | Description | | --- | --- | | [WP\_Upgrader](wp_upgrader) wp-admin/includes/class-wp-upgrader.php | | | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Moved to its own file from wp-admin/includes/class-wp-upgrader.php. | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. | wordpress class Plugin_Installer_Skin {} class Plugin\_Installer\_Skin {} ================================ Plugin Installer Skin for WordPress Plugin Installer. * [WP\_Upgrader\_Skin](wp_upgrader_skin) * [\_\_construct](plugin_installer_skin/__construct) * [after](plugin_installer_skin/after) β€” Action to perform following a plugin install. * [before](plugin_installer_skin/before) β€” Action to perform before installing a plugin. * [do\_overwrite](plugin_installer_skin/do_overwrite) β€” Check if the plugin can be overwritten and output the HTML for overwriting a plugin on upload. * [hide\_process\_failed](plugin_installer_skin/hide_process_failed) β€” Hides the `process\_failed` error when updating a plugin by uploading a zip file. File: `wp-admin/includes/class-plugin-installer-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-plugin-installer-skin.php/) ``` class Plugin_Installer_Skin extends WP_Upgrader_Skin { public $api; public $type; public $url; public $overwrite; private $is_downgrading = false; /** * @param array $args */ public function __construct( $args = array() ) { $defaults = array( 'type' => 'web', 'url' => '', 'plugin' => '', 'nonce' => '', 'title' => '', 'overwrite' => '', ); $args = wp_parse_args( $args, $defaults ); $this->type = $args['type']; $this->url = $args['url']; $this->api = isset( $args['api'] ) ? $args['api'] : array(); $this->overwrite = $args['overwrite']; parent::__construct( $args ); } /** * Action to perform before installing a plugin. * * @since 2.8.0 */ public function before() { if ( ! empty( $this->api ) ) { $this->upgrader->strings['process_success'] = sprintf( $this->upgrader->strings['process_success_specific'], $this->api->name, $this->api->version ); } } /** * Hides the `process_failed` error when updating a plugin by uploading a zip file. * * @since 5.5.0 * * @param WP_Error $wp_error WP_Error object. * @return bool */ public function hide_process_failed( $wp_error ) { if ( 'upload' === $this->type && '' === $this->overwrite && $wp_error->get_error_code() === 'folder_exists' ) { return true; } return false; } /** * Action to perform following a plugin install. * * @since 2.8.0 */ public function after() { // Check if the plugin can be overwritten and output the HTML. if ( $this->do_overwrite() ) { return; } $plugin_file = $this->upgrader->plugin_info(); $install_actions = array(); $from = isset( $_GET['from'] ) ? wp_unslash( $_GET['from'] ) : 'plugins'; if ( 'import' === $from ) { $install_actions['activate_plugin'] = sprintf( '<a class="button button-primary" href="%s" target="_parent">%s</a>', wp_nonce_url( 'plugins.php?action=activate&amp;from=import&amp;plugin=' . urlencode( $plugin_file ), 'activate-plugin_' . $plugin_file ), __( 'Activate Plugin &amp; Run Importer' ) ); } elseif ( 'press-this' === $from ) { $install_actions['activate_plugin'] = sprintf( '<a class="button button-primary" href="%s" target="_parent">%s</a>', wp_nonce_url( 'plugins.php?action=activate&amp;from=press-this&amp;plugin=' . urlencode( $plugin_file ), 'activate-plugin_' . $plugin_file ), __( 'Activate Plugin &amp; Go to Press This' ) ); } else { $install_actions['activate_plugin'] = sprintf( '<a class="button button-primary" href="%s" target="_parent">%s</a>', wp_nonce_url( 'plugins.php?action=activate&amp;plugin=' . urlencode( $plugin_file ), 'activate-plugin_' . $plugin_file ), __( 'Activate Plugin' ) ); } if ( is_multisite() && current_user_can( 'manage_network_plugins' ) ) { $install_actions['network_activate'] = sprintf( '<a class="button button-primary" href="%s" target="_parent">%s</a>', wp_nonce_url( 'plugins.php?action=activate&amp;networkwide=1&amp;plugin=' . urlencode( $plugin_file ), 'activate-plugin_' . $plugin_file ), __( 'Network Activate' ) ); unset( $install_actions['activate_plugin'] ); } if ( 'import' === $from ) { $install_actions['importers_page'] = sprintf( '<a href="%s" target="_parent">%s</a>', admin_url( 'import.php' ), __( 'Go to Importers' ) ); } elseif ( 'web' === $this->type ) { $install_actions['plugins_page'] = sprintf( '<a href="%s" target="_parent">%s</a>', self_admin_url( 'plugin-install.php' ), __( 'Go to Plugin Installer' ) ); } elseif ( 'upload' === $this->type && 'plugins' === $from ) { $install_actions['plugins_page'] = sprintf( '<a href="%s">%s</a>', self_admin_url( 'plugin-install.php' ), __( 'Go to Plugin Installer' ) ); } else { $install_actions['plugins_page'] = sprintf( '<a href="%s" target="_parent">%s</a>', self_admin_url( 'plugins.php' ), __( 'Go to Plugins page' ) ); } if ( ! $this->result || is_wp_error( $this->result ) ) { unset( $install_actions['activate_plugin'], $install_actions['network_activate'] ); } elseif ( ! current_user_can( 'activate_plugin', $plugin_file ) || is_plugin_active( $plugin_file ) ) { unset( $install_actions['activate_plugin'] ); } /** * Filters the list of action links available following a single plugin installation. * * @since 2.7.0 * * @param string[] $install_actions Array of plugin action links. * @param object $api Object containing WordPress.org API plugin data. Empty * for non-API installs, such as when a plugin is installed * via upload. * @param string $plugin_file Path to the plugin file relative to the plugins directory. */ $install_actions = apply_filters( 'install_plugin_complete_actions', $install_actions, $this->api, $plugin_file ); if ( ! empty( $install_actions ) ) { $this->feedback( implode( ' ', (array) $install_actions ) ); } } /** * Check if the plugin can be overwritten and output the HTML for overwriting a plugin on upload. * * @since 5.5.0 * * @return bool Whether the plugin can be overwritten and HTML was outputted. */ private function do_overwrite() { if ( 'upload' !== $this->type || ! is_wp_error( $this->result ) || 'folder_exists' !== $this->result->get_error_code() ) { return false; } $folder = $this->result->get_error_data( 'folder_exists' ); $folder = ltrim( substr( $folder, strlen( WP_PLUGIN_DIR ) ), '/' ); $current_plugin_data = false; $all_plugins = get_plugins(); foreach ( $all_plugins as $plugin => $plugin_data ) { if ( strrpos( $plugin, $folder ) !== 0 ) { continue; } $current_plugin_data = $plugin_data; } $new_plugin_data = $this->upgrader->new_plugin_data; if ( ! $current_plugin_data || ! $new_plugin_data ) { return false; } echo '<h2 class="update-from-upload-heading">' . esc_html__( 'This plugin is already installed.' ) . '</h2>'; $this->is_downgrading = version_compare( $current_plugin_data['Version'], $new_plugin_data['Version'], '>' ); $rows = array( 'Name' => __( 'Plugin name' ), 'Version' => __( 'Version' ), 'Author' => __( 'Author' ), 'RequiresWP' => __( 'Required WordPress version' ), 'RequiresPHP' => __( 'Required PHP version' ), ); $table = '<table class="update-from-upload-comparison"><tbody>'; $table .= '<tr><th></th><th>' . esc_html_x( 'Current', 'plugin' ) . '</th>'; $table .= '<th>' . esc_html_x( 'Uploaded', 'plugin' ) . '</th></tr>'; $is_same_plugin = true; // Let's consider only these rows. foreach ( $rows as $field => $label ) { $old_value = ! empty( $current_plugin_data[ $field ] ) ? (string) $current_plugin_data[ $field ] : '-'; $new_value = ! empty( $new_plugin_data[ $field ] ) ? (string) $new_plugin_data[ $field ] : '-'; $is_same_plugin = $is_same_plugin && ( $old_value === $new_value ); $diff_field = ( 'Version' !== $field && $new_value !== $old_value ); $diff_version = ( 'Version' === $field && $this->is_downgrading ); $table .= '<tr><td class="name-label">' . $label . '</td><td>' . wp_strip_all_tags( $old_value ) . '</td>'; $table .= ( $diff_field || $diff_version ) ? '<td class="warning">' : '<td>'; $table .= wp_strip_all_tags( $new_value ) . '</td></tr>'; } $table .= '</tbody></table>'; /** * Filters the compare table output for overwriting a plugin package on upload. * * @since 5.5.0 * * @param string $table The output table with Name, Version, Author, RequiresWP, and RequiresPHP info. * @param array $current_plugin_data Array with current plugin data. * @param array $new_plugin_data Array with uploaded plugin data. */ echo apply_filters( 'install_plugin_overwrite_comparison', $table, $current_plugin_data, $new_plugin_data ); $install_actions = array(); $can_update = true; $blocked_message = '<p>' . esc_html__( 'The plugin cannot be updated due to the following:' ) . '</p>'; $blocked_message .= '<ul class="ul-disc">'; $requires_php = isset( $new_plugin_data['RequiresPHP'] ) ? $new_plugin_data['RequiresPHP'] : null; $requires_wp = isset( $new_plugin_data['RequiresWP'] ) ? $new_plugin_data['RequiresWP'] : null; if ( ! is_php_version_compatible( $requires_php ) ) { $error = sprintf( /* translators: 1: Current PHP version, 2: Version required by the uploaded plugin. */ __( 'The PHP version on your server is %1$s, however the uploaded plugin requires %2$s.' ), PHP_VERSION, $requires_php ); $blocked_message .= '<li>' . esc_html( $error ) . '</li>'; $can_update = false; } if ( ! is_wp_version_compatible( $requires_wp ) ) { $error = sprintf( /* translators: 1: Current WordPress version, 2: Version required by the uploaded plugin. */ __( 'Your WordPress version is %1$s, however the uploaded plugin requires %2$s.' ), get_bloginfo( 'version' ), $requires_wp ); $blocked_message .= '<li>' . esc_html( $error ) . '</li>'; $can_update = false; } $blocked_message .= '</ul>'; if ( $can_update ) { if ( $this->is_downgrading ) { $warning = sprintf( /* translators: %s: Documentation URL. */ __( 'You are uploading an older version of a current plugin. You can continue to install the older version, but be sure to <a href="%s">back up your database and files</a> first.' ), __( 'https://wordpress.org/support/article/wordpress-backups/' ) ); } else { $warning = sprintf( /* translators: %s: Documentation URL. */ __( 'You are updating a plugin. Be sure to <a href="%s">back up your database and files</a> first.' ), __( 'https://wordpress.org/support/article/wordpress-backups/' ) ); } echo '<p class="update-from-upload-notice">' . $warning . '</p>'; $overwrite = $this->is_downgrading ? 'downgrade-plugin' : 'update-plugin'; $install_actions['overwrite_plugin'] = sprintf( '<a class="button button-primary update-from-upload-overwrite" href="%s" target="_parent">%s</a>', wp_nonce_url( add_query_arg( 'overwrite', $overwrite, $this->url ), 'plugin-upload' ), _x( 'Replace current with uploaded', 'plugin' ) ); } else { echo $blocked_message; } $cancel_url = add_query_arg( 'action', 'upload-plugin-cancel-overwrite', $this->url ); $install_actions['plugins_page'] = sprintf( '<a class="button" href="%s">%s</a>', wp_nonce_url( $cancel_url, 'plugin-upload-cancel-overwrite' ), __( 'Cancel and go back' ) ); /** * Filters the list of action links available following a single plugin installation failure * when overwriting is allowed. * * @since 5.5.0 * * @param string[] $install_actions Array of plugin action links. * @param object $api Object containing WordPress.org API plugin data. * @param array $new_plugin_data Array with uploaded plugin data. */ $install_actions = apply_filters( 'install_plugin_overwrite_actions', $install_actions, $this->api, $new_plugin_data ); if ( ! empty( $install_actions ) ) { printf( '<p class="update-from-upload-expired hidden">%s</p>', __( 'The uploaded file has expired. Please go back and upload it again.' ) ); echo '<p class="update-from-upload-actions">' . implode( ' ', (array) $install_actions ) . '</p>'; } return true; } } ``` | Uses | Description | | --- | --- | | [WP\_Upgrader\_Skin](wp_upgrader_skin) wp-admin/includes/class-wp-upgrader-skin.php | Generic Skin for the WordPress Upgrader classes. This skin is designed to be extended for specific purposes. | | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php. | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
programming_docs
wordpress class Requests_Exception_HTTP_412 {} class Requests\_Exception\_HTTP\_412 {} ======================================= Exception for 412 Precondition Failed responses File: `wp-includes/Requests/Exception/HTTP/412.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/412.php/) ``` class Requests_Exception_HTTP_412 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 412; /** * Reason phrase * * @var string */ protected $reason = 'Precondition Failed'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_MS_Users_List_Table {} class WP\_MS\_Users\_List\_Table {} =================================== Core class used to implement displaying users in a list table for the network admin. * [WP\_List\_Table](wp_list_table) * [\_column\_blogs](wp_ms_users_list_table/_column_blogs) * [ajax\_user\_can](wp_ms_users_list_table/ajax_user_can) * [column\_blogs](wp_ms_users_list_table/column_blogs) β€” Handles the sites column output. * [column\_cb](wp_ms_users_list_table/column_cb) β€” Handles the checkbox column output. * [column\_default](wp_ms_users_list_table/column_default) β€” Handles the default column output. * [column\_email](wp_ms_users_list_table/column_email) β€” Handles the email column output. * [column\_id](wp_ms_users_list_table/column_id) β€” Handles the ID column output. * [column\_name](wp_ms_users_list_table/column_name) β€” Handles the name column output. * [column\_registered](wp_ms_users_list_table/column_registered) β€” Handles the registered date column output. * [column\_username](wp_ms_users_list_table/column_username) β€” Handles the username column output. * [display\_rows](wp_ms_users_list_table/display_rows) * [get\_bulk\_actions](wp_ms_users_list_table/get_bulk_actions) * [get\_columns](wp_ms_users_list_table/get_columns) * [get\_default\_primary\_column\_name](wp_ms_users_list_table/get_default_primary_column_name) β€” Gets the name of the default primary column. * [get\_sortable\_columns](wp_ms_users_list_table/get_sortable_columns) * [get\_views](wp_ms_users_list_table/get_views) * [handle\_row\_actions](wp_ms_users_list_table/handle_row_actions) β€” Generates and displays row action links. * [no\_items](wp_ms_users_list_table/no_items) * [pagination](wp_ms_users_list_table/pagination) * [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/) ``` class WP_MS_Users_List_Table extends WP_List_Table { /** * @return bool */ public function ajax_user_can() { return current_user_can( 'manage_network_users' ); } /** * @global string $mode List table view mode. * @global string $usersearch * @global string $role */ 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, ) ); } /** * @return array */ 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; } /** */ public function no_items() { _e( 'No users found.' ); } /** * @global string $role * @return array */ 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 ); } /** * @global string $mode List table view mode. * * @param string $which */ protected function pagination( $which ) { global $mode; parent::pagination( $which ); if ( 'top' === $which ) { $this->view_switcher( $mode ); } } /** * @return array */ 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 ); } /** * @return array */ protected function get_sortable_columns() { return array( 'username' => 'login', 'name' => 'name', 'email' => 'email', 'registered' => 'id', ); } /** * Handles the checkbox column output. * * @since 4.3.0 * @since 5.9.0 Renamed `$user` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_User $item The current WP_User object. */ 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 } /** * Handles the ID column output. * * @since 4.4.0 * * @param WP_User $user The current WP_User object. */ public function column_id( $user ) { echo $user->ID; } /** * Handles the username column output. * * @since 4.3.0 * * @param WP_User $user The current WP_User object. */ 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 ' &mdash; ' . __( 'Super Admin' ); } ?> </strong> <?php } /** * Handles the name column output. * * @since 4.3.0 * * @param WP_User $user The current WP_User object. */ 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">&#8212;</span><span class="screen-reader-text">' . _x( 'Unknown', 'name' ) . '</span>'; } } /** * Handles the email column output. * * @since 4.3.0 * * @param WP_User $user The current WP_User object. */ public function column_email( $user ) { echo "<a href='" . esc_url( "mailto:$user->user_email" ) . "'>$user->user_email</a>"; } /** * Handles the registered date column output. * * @since 4.3.0 * * @global string $mode List table view mode. * * @param WP_User $user The current WP_User object. */ 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 ); } /** * @since 4.3.0 * * @param WP_User $user * @param string $classes * @param string $data * @param string $primary */ 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>'; } /** * Handles the sites column output. * * @since 4.3.0 * * @param WP_User $user The current WP_User object. */ 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 />'; } } /** * Handles the default column output. * * @since 4.3.0 * @since 5.9.0 Renamed `$user` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_User $item The current WP_User object. * @param string $column_name The current column name. */ 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. ); } 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 } } /** * Gets the name of the default primary column. * * @since 4.3.0 * * @return string Name of the default primary column, in this case, 'username'. */ protected function get_default_primary_column_name() { return 'username'; } /** * Generates and displays row action links. * * @since 4.3.0 * @since 5.9.0 Renamed `$user` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_User $item User being acted upon. * @param string $column_name Current column name. * @param string $primary Primary column name. * @return string Row actions output for users in Multisite, or an empty string * if the current column is not the primary column. */ 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' ) . '&amp;action=deleteuser&amp;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 ); } } ``` | Uses | Description | | --- | --- | | [WP\_List\_Table](wp_list_table) wp-admin/includes/class-wp-list-table.php | Base class for displaying a list of items in an ajaxified HTML table. | | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. | wordpress class WP_Recovery_Mode {} class WP\_Recovery\_Mode {} =========================== Core class used to implement Recovery Mode. * [\_\_construct](wp_recovery_mode/__construct) β€” WP\_Recovery\_Mode constructor. * [clean\_expired\_keys](wp_recovery_mode/clean_expired_keys) β€” Cleans any recovery mode keys that have expired according to the link TTL. * [exit\_recovery\_mode](wp_recovery_mode/exit_recovery_mode) β€” Ends the current recovery mode session. * [get\_email\_rate\_limit](wp_recovery_mode/get_email_rate_limit) β€” Gets the rate limit between sending new recovery mode email links. * [get\_extension\_for\_error](wp_recovery_mode/get_extension_for_error) β€” Gets the extension that the error occurred in. * [get\_link\_ttl](wp_recovery_mode/get_link_ttl) β€” Gets the number of seconds the recovery mode link is valid for. * [get\_session\_id](wp_recovery_mode/get_session_id) β€” Gets the recovery mode session ID. * [handle\_cookie](wp_recovery_mode/handle_cookie) β€” Handles checking for the recovery mode cookie and validating it. * [handle\_error](wp_recovery_mode/handle_error) β€” Handles a fatal error occurring. * [handle\_exit\_recovery\_mode](wp_recovery_mode/handle_exit_recovery_mode) β€” Handles a request to exit Recovery Mode. * [initialize](wp_recovery_mode/initialize) β€” Initialize recovery mode for the current request. * [is\_active](wp_recovery_mode/is_active) β€” Checks whether recovery mode is active. * [is\_initialized](wp_recovery_mode/is_initialized) β€” Checks whether recovery mode has been initialized. * [is\_network\_plugin](wp_recovery_mode/is_network_plugin) β€” Checks whether the given extension a network activated plugin. * [redirect\_protected](wp_recovery_mode/redirect_protected) β€” Redirects the current request to allow recovering multiple errors in one go. * [store\_error](wp_recovery_mode/store_error) β€” Stores the given error so that the extension causing it is paused. File: `wp-includes/class-wp-recovery-mode.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode.php/) ``` class WP_Recovery_Mode { const EXIT_ACTION = 'exit_recovery_mode'; /** * Service to handle cookies. * * @since 5.2.0 * @var WP_Recovery_Mode_Cookie_Service */ private $cookie_service; /** * Service to generate a recovery mode key. * * @since 5.2.0 * @var WP_Recovery_Mode_Key_Service */ private $key_service; /** * Service to generate and validate recovery mode links. * * @since 5.2.0 * @var WP_Recovery_Mode_Link_Service */ private $link_service; /** * Service to handle sending an email with a recovery mode link. * * @since 5.2.0 * @var WP_Recovery_Mode_Email_Service */ private $email_service; /** * Is recovery mode initialized. * * @since 5.2.0 * @var bool */ private $is_initialized = false; /** * Is recovery mode active in this session. * * @since 5.2.0 * @var bool */ private $is_active = false; /** * Get an ID representing the current recovery mode session. * * @since 5.2.0 * @var string */ private $session_id = ''; /** * WP_Recovery_Mode constructor. * * @since 5.2.0 */ public function __construct() { $this->cookie_service = new WP_Recovery_Mode_Cookie_Service(); $this->key_service = new WP_Recovery_Mode_Key_Service(); $this->link_service = new WP_Recovery_Mode_Link_Service( $this->cookie_service, $this->key_service ); $this->email_service = new WP_Recovery_Mode_Email_Service( $this->link_service ); } /** * Initialize recovery mode for the current request. * * @since 5.2.0 */ public function initialize() { $this->is_initialized = true; add_action( 'wp_logout', array( $this, 'exit_recovery_mode' ) ); add_action( 'login_form_' . self::EXIT_ACTION, array( $this, 'handle_exit_recovery_mode' ) ); add_action( 'recovery_mode_clean_expired_keys', array( $this, 'clean_expired_keys' ) ); if ( ! wp_next_scheduled( 'recovery_mode_clean_expired_keys' ) && ! wp_installing() ) { wp_schedule_event( time(), 'daily', 'recovery_mode_clean_expired_keys' ); } if ( defined( 'WP_RECOVERY_MODE_SESSION_ID' ) ) { $this->is_active = true; $this->session_id = WP_RECOVERY_MODE_SESSION_ID; return; } if ( $this->cookie_service->is_cookie_set() ) { $this->handle_cookie(); return; } $this->link_service->handle_begin_link( $this->get_link_ttl() ); } /** * Checks whether recovery mode is active. * * This will not change after recovery mode has been initialized. {@see WP_Recovery_Mode::run()}. * * @since 5.2.0 * * @return bool True if recovery mode is active, false otherwise. */ public function is_active() { return $this->is_active; } /** * Gets the recovery mode session ID. * * @since 5.2.0 * * @return string The session ID if recovery mode is active, empty string otherwise. */ public function get_session_id() { return $this->session_id; } /** * Checks whether recovery mode has been initialized. * * Recovery mode should not be used until this point. Initialization happens immediately before loading plugins. * * @since 5.2.0 * * @return bool */ public function is_initialized() { return $this->is_initialized; } /** * Handles a fatal error occurring. * * The calling API should immediately die() after calling this function. * * @since 5.2.0 * * @param array $error Error details from `error_get_last()`. * @return true|WP_Error True if the error was handled and headers have already been sent. * Or the request will exit to try and catch multiple errors at once. * WP_Error if an error occurred preventing it from being handled. */ public function handle_error( array $error ) { $extension = $this->get_extension_for_error( $error ); if ( ! $extension || $this->is_network_plugin( $extension ) ) { return new WP_Error( 'invalid_source', __( 'Error not caused by a plugin or theme.' ) ); } if ( ! $this->is_active() ) { if ( ! is_protected_endpoint() ) { return new WP_Error( 'non_protected_endpoint', __( 'Error occurred on a non-protected endpoint.' ) ); } if ( ! function_exists( 'wp_generate_password' ) ) { require_once ABSPATH . WPINC . '/pluggable.php'; } return $this->email_service->maybe_send_recovery_mode_email( $this->get_email_rate_limit(), $error, $extension ); } if ( ! $this->store_error( $error ) ) { return new WP_Error( 'storage_error', __( 'Failed to store the error.' ) ); } if ( headers_sent() ) { return true; } $this->redirect_protected(); } /** * Ends the current recovery mode session. * * @since 5.2.0 * * @return bool True on success, false on failure. */ public function exit_recovery_mode() { if ( ! $this->is_active() ) { return false; } $this->email_service->clear_rate_limit(); $this->cookie_service->clear_cookie(); wp_paused_plugins()->delete_all(); wp_paused_themes()->delete_all(); return true; } /** * Handles a request to exit Recovery Mode. * * @since 5.2.0 */ public function handle_exit_recovery_mode() { $redirect_to = wp_get_referer(); // Safety check in case referrer returns false. if ( ! $redirect_to ) { $redirect_to = is_user_logged_in() ? admin_url() : home_url(); } if ( ! $this->is_active() ) { wp_safe_redirect( $redirect_to ); die; } if ( ! isset( $_GET['action'] ) || self::EXIT_ACTION !== $_GET['action'] ) { return; } if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( $_GET['_wpnonce'], self::EXIT_ACTION ) ) { wp_die( __( 'Exit recovery mode link expired.' ), 403 ); } if ( ! $this->exit_recovery_mode() ) { wp_die( __( 'Failed to exit recovery mode. Please try again later.' ) ); } wp_safe_redirect( $redirect_to ); die; } /** * Cleans any recovery mode keys that have expired according to the link TTL. * * Executes on a daily cron schedule. * * @since 5.2.0 */ public function clean_expired_keys() { $this->key_service->clean_expired_keys( $this->get_link_ttl() ); } /** * Handles checking for the recovery mode cookie and validating it. * * @since 5.2.0 */ protected function handle_cookie() { $validated = $this->cookie_service->validate_cookie(); if ( is_wp_error( $validated ) ) { $this->cookie_service->clear_cookie(); $validated->add_data( array( 'status' => 403 ) ); wp_die( $validated ); } $session_id = $this->cookie_service->get_session_id_from_cookie(); if ( is_wp_error( $session_id ) ) { $this->cookie_service->clear_cookie(); $session_id->add_data( array( 'status' => 403 ) ); wp_die( $session_id ); } $this->is_active = true; $this->session_id = $session_id; } /** * Gets the rate limit between sending new recovery mode email links. * * @since 5.2.0 * * @return int Rate limit in seconds. */ protected function get_email_rate_limit() { /** * Filters the rate limit between sending new recovery mode email links. * * @since 5.2.0 * * @param int $rate_limit Time to wait in seconds. Defaults to 1 day. */ return apply_filters( 'recovery_mode_email_rate_limit', DAY_IN_SECONDS ); } /** * Gets the number of seconds the recovery mode link is valid for. * * @since 5.2.0 * * @return int Interval in seconds. */ protected function get_link_ttl() { $rate_limit = $this->get_email_rate_limit(); $valid_for = $rate_limit; /** * Filters the amount of time the recovery mode email link is valid for. * * The ttl must be at least as long as the email rate limit. * * @since 5.2.0 * * @param int $valid_for The number of seconds the link is valid for. */ $valid_for = apply_filters( 'recovery_mode_email_link_ttl', $valid_for ); return max( $valid_for, $rate_limit ); } /** * Gets the extension that the error occurred in. * * @since 5.2.0 * * @global array $wp_theme_directories * * @param array $error Error details from `error_get_last()`. * @return array|false { * Extension details. * * @type string $slug The extension slug. This is the plugin or theme's directory. * @type string $type The extension type. Either 'plugin' or 'theme'. * } */ protected function get_extension_for_error( $error ) { global $wp_theme_directories; if ( ! isset( $error['file'] ) ) { return false; } if ( ! defined( 'WP_PLUGIN_DIR' ) ) { return false; } $error_file = wp_normalize_path( $error['file'] ); $wp_plugin_dir = wp_normalize_path( WP_PLUGIN_DIR ); if ( 0 === strpos( $error_file, $wp_plugin_dir ) ) { $path = str_replace( $wp_plugin_dir . '/', '', $error_file ); $parts = explode( '/', $path ); return array( 'type' => 'plugin', 'slug' => $parts[0], ); } if ( empty( $wp_theme_directories ) ) { return false; } foreach ( $wp_theme_directories as $theme_directory ) { $theme_directory = wp_normalize_path( $theme_directory ); if ( 0 === strpos( $error_file, $theme_directory ) ) { $path = str_replace( $theme_directory . '/', '', $error_file ); $parts = explode( '/', $path ); return array( 'type' => 'theme', 'slug' => $parts[0], ); } } return false; } /** * Checks whether the given extension a network activated plugin. * * @since 5.2.0 * * @param array $extension Extension data. * @return bool True if network plugin, false otherwise. */ protected function is_network_plugin( $extension ) { if ( 'plugin' !== $extension['type'] ) { return false; } if ( ! is_multisite() ) { return false; } $network_plugins = wp_get_active_network_plugins(); foreach ( $network_plugins as $plugin ) { if ( 0 === strpos( $plugin, $extension['slug'] . '/' ) ) { return true; } } return false; } /** * Stores the given error so that the extension causing it is paused. * * @since 5.2.0 * * @param array $error Error details from `error_get_last()`. * @return bool True if the error was stored successfully, false otherwise. */ protected function store_error( $error ) { $extension = $this->get_extension_for_error( $error ); if ( ! $extension ) { return false; } switch ( $extension['type'] ) { case 'plugin': return wp_paused_plugins()->set( $extension['slug'], $error ); case 'theme': return wp_paused_themes()->set( $extension['slug'], $error ); default: return false; } } /** * Redirects the current request to allow recovering multiple errors in one go. * * The redirection will only happen when on a protected endpoint. * * It must be ensured that this method is only called when an error actually occurred and will not occur on the * next request again. Otherwise it will create a redirect loop. * * @since 5.2.0 */ protected function redirect_protected() { // Pluggable is usually loaded after plugins, so we manually include it here for redirection functionality. if ( ! function_exists( 'wp_safe_redirect' ) ) { require_once ABSPATH . WPINC . '/pluggable.php'; } $scheme = is_ssl() ? 'https://' : 'http://'; $url = "{$scheme}{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; wp_safe_redirect( $url ); exit; } } ``` | Version | Description | | --- | --- | | [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Autosaves_Controller {} class WP\_REST\_Autosaves\_Controller {} ======================================== Core class used to access autosaves via the REST API. * [WP\_REST\_Revisions\_Controller](wp_rest_revisions_controller) * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_autosaves_controller/__construct) β€” Constructor. * [create\_item](wp_rest_autosaves_controller/create_item) β€” Creates, updates or deletes an autosave revision. * [create\_item\_permissions\_check](wp_rest_autosaves_controller/create_item_permissions_check) β€” Checks if a given request has access to create an autosave revision. * [create\_post\_autosave](wp_rest_autosaves_controller/create_post_autosave) β€” Creates autosave for the specified post. * [get\_collection\_params](wp_rest_autosaves_controller/get_collection_params) β€” Retrieves the query params for the autosaves collection. * [get\_item](wp_rest_autosaves_controller/get_item) β€” Get the autosave, if the ID is valid. * [get\_item\_schema](wp_rest_autosaves_controller/get_item_schema) β€” Retrieves the autosave's schema, conforming to JSON Schema. * [get\_items](wp_rest_autosaves_controller/get_items) β€” Gets a collection of autosaves using wp\_get\_post\_autosave. * [get\_items\_permissions\_check](wp_rest_autosaves_controller/get_items_permissions_check) β€” Checks if a given request has access to get autosaves. * [get\_parent](wp_rest_autosaves_controller/get_parent) β€” Get the parent post. * [prepare\_item\_for\_response](wp_rest_autosaves_controller/prepare_item_for_response) β€” Prepares the revision for the REST response. * [register\_routes](wp_rest_autosaves_controller/register_routes) β€” Registers the routes for autosaves. 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/) ``` class WP_REST_Autosaves_Controller extends WP_REST_Revisions_Controller { /** * Parent post type. * * @since 5.0.0 * @var string */ private $parent_post_type; /** * Parent post controller. * * @since 5.0.0 * @var WP_REST_Controller */ private $parent_controller; /** * Revision controller. * * @since 5.0.0 * @var WP_REST_Revisions_Controller */ private $revisions_controller; /** * The base of the parent controller's route. * * @since 5.0.0 * @var string */ private $parent_base; /** * Constructor. * * @since 5.0.0 * * @param string $parent_post_type Post type of the parent. */ 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; } /** * Registers the routes for autosaves. * * @since 5.0.0 * * @see register_rest_route() */ 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' ), ) ); } /** * Get the parent post. * * @since 5.0.0 * * @param int $parent_id Supplied ID. * @return WP_Post|WP_Error Post object if ID is valid, WP_Error otherwise. */ protected function get_parent( $parent_id ) { return $this->revisions_controller->get_parent( $parent_id ); } /** * Checks if a given request has access to get autosaves. * * @since 5.0.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ 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; } /** * 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. * * @since 5.0.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has access to create the item, WP_Error object otherwise. */ 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 ); } /** * Creates, updates or deletes an autosave revision. * * @since 5.0.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ 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; } /** * Get the autosave, if the ID is valid. * * @since 5.0.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_Post|WP_Error Revision post object if ID is valid, WP_Error otherwise. */ 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; } /** * Gets a collection of autosaves using wp_get_post_autosave. * * Contains the user's autosave, for empty if it doesn't exist. * * @since 5.0.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ 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 ); } /** * Retrieves the autosave's schema, conforming to JSON Schema. * * @since 5.0.0 * * @return array Item schema data. */ 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 ); } /** * Creates autosave for the specified post. * * From wp-admin/post.php. * * @since 5.0.0 * * @param array $post_data Associative array containing the post data. * @return mixed The autosave revision ID or WP_Error. */ 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 ); } /** * Prepares the revision for the REST response. * * @since 5.0.0 * @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Post $item Post revision object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ 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 ); } /** * Retrieves the query params for the autosaves collection. * * @since 5.0.0 * * @return array Collection parameters. */ public function get_collection_params() { return array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Revisions\_Controller](wp_rest_revisions_controller) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Core class used to access revisions via the REST API. | | Version | Description | | --- | --- | | [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. | wordpress class WP_Paused_Extensions_Storage {} class WP\_Paused\_Extensions\_Storage {} ======================================== Core class used for storing paused extensions. * [\_\_construct](wp_paused_extensions_storage/__construct) β€” Constructor. * [delete](wp_paused_extensions_storage/delete) β€” Forgets a previously recorded extension error. * [delete\_all](wp_paused_extensions_storage/delete_all) β€” Remove all paused extensions. * [get](wp_paused_extensions_storage/get) β€” Gets the error for an extension, if paused. * [get\_all](wp_paused_extensions_storage/get_all) β€” Gets the paused extensions with their errors. * [get\_option\_name](wp_paused_extensions_storage/get_option_name) β€” Get the option name for storing paused extensions. * [is\_api\_loaded](wp_paused_extensions_storage/is_api_loaded) β€” Checks whether the underlying API to store paused extensions is loaded. * [set](wp_paused_extensions_storage/set) β€” Records an extension error. File: `wp-includes/class-wp-paused-extensions-storage.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-paused-extensions-storage.php/) ``` class WP_Paused_Extensions_Storage { /** * Type of extension. Used to key extension storage. * * @since 5.2.0 * @var string */ protected $type; /** * Constructor. * * @since 5.2.0 * * @param string $extension_type Extension type. Either 'plugin' or 'theme'. */ public function __construct( $extension_type ) { $this->type = $extension_type; } /** * Records an extension error. * * Only one error is stored per extension, with subsequent errors for the same extension overriding the * previously stored error. * * @since 5.2.0 * * @param string $extension Plugin or theme directory name. * @param array $error { * Error information returned by `error_get_last()`. * * @type int $type The error type. * @type string $file The name of the file in which the error occurred. * @type int $line The line number in which the error occurred. * @type string $message The error message. * } * @return bool True on success, false on failure. */ public function set( $extension, $error ) { if ( ! $this->is_api_loaded() ) { return false; } $option_name = $this->get_option_name(); if ( ! $option_name ) { return false; } $paused_extensions = (array) get_option( $option_name, array() ); // Do not update if the error is already stored. if ( isset( $paused_extensions[ $this->type ][ $extension ] ) && $paused_extensions[ $this->type ][ $extension ] === $error ) { return true; } $paused_extensions[ $this->type ][ $extension ] = $error; return update_option( $option_name, $paused_extensions ); } /** * Forgets a previously recorded extension error. * * @since 5.2.0 * * @param string $extension Plugin or theme directory name. * @return bool True on success, false on failure. */ public function delete( $extension ) { if ( ! $this->is_api_loaded() ) { return false; } $option_name = $this->get_option_name(); if ( ! $option_name ) { return false; } $paused_extensions = (array) get_option( $option_name, array() ); // Do not delete if no error is stored. if ( ! isset( $paused_extensions[ $this->type ][ $extension ] ) ) { return true; } unset( $paused_extensions[ $this->type ][ $extension ] ); if ( empty( $paused_extensions[ $this->type ] ) ) { unset( $paused_extensions[ $this->type ] ); } // Clean up the entire option if we're removing the only error. if ( ! $paused_extensions ) { return delete_option( $option_name ); } return update_option( $option_name, $paused_extensions ); } /** * Gets the error for an extension, if paused. * * @since 5.2.0 * * @param string $extension Plugin or theme directory name. * @return array|null Error that is stored, or null if the extension is not paused. */ public function get( $extension ) { if ( ! $this->is_api_loaded() ) { return null; } $paused_extensions = $this->get_all(); if ( ! isset( $paused_extensions[ $extension ] ) ) { return null; } return $paused_extensions[ $extension ]; } /** * Gets the paused extensions with their errors. * * @since 5.2.0 * * @return array { * Associative array of errors keyed by extension slug. * * @type array ...$0 Error information returned by `error_get_last()`. * } */ public function get_all() { if ( ! $this->is_api_loaded() ) { return array(); } $option_name = $this->get_option_name(); if ( ! $option_name ) { return array(); } $paused_extensions = (array) get_option( $option_name, array() ); return isset( $paused_extensions[ $this->type ] ) ? $paused_extensions[ $this->type ] : array(); } /** * Remove all paused extensions. * * @since 5.2.0 * * @return bool */ public function delete_all() { if ( ! $this->is_api_loaded() ) { return false; } $option_name = $this->get_option_name(); if ( ! $option_name ) { return false; } $paused_extensions = (array) get_option( $option_name, array() ); unset( $paused_extensions[ $this->type ] ); if ( ! $paused_extensions ) { return delete_option( $option_name ); } return update_option( $option_name, $paused_extensions ); } /** * Checks whether the underlying API to store paused extensions is loaded. * * @since 5.2.0 * * @return bool True if the API is loaded, false otherwise. */ protected function is_api_loaded() { return function_exists( 'get_option' ); } /** * Get the option name for storing paused extensions. * * @since 5.2.0 * * @return string */ protected function get_option_name() { if ( ! wp_recovery_mode()->is_active() ) { return ''; } $session_id = wp_recovery_mode()->get_session_id(); if ( empty( $session_id ) ) { return ''; } return "{$session_id}_paused_extensions"; } } ``` | Version | Description | | --- | --- | | [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
programming_docs
wordpress class WP_Application_Passwords_List_Table {} class WP\_Application\_Passwords\_List\_Table {} ================================================ Class for displaying the list of application password items. * [WP\_List\_Table](wp_list_table) * [column\_created](wp_application_passwords_list_table/column_created) β€” Handles the created column output. * [column\_default](wp_application_passwords_list_table/column_default) β€” Generates content for a single row of the table * [column\_last\_ip](wp_application_passwords_list_table/column_last_ip) β€” Handles the last ip column output. * [column\_last\_used](wp_application_passwords_list_table/column_last_used) β€” Handles the last used column output. * [column\_name](wp_application_passwords_list_table/column_name) β€” Handles the name column output. * [column\_revoke](wp_application_passwords_list_table/column_revoke) β€” Handles the revoke column output. * [display\_tablenav](wp_application_passwords_list_table/display_tablenav) β€” Generates custom table navigation to prevent conflicting nonces. * [get\_columns](wp_application_passwords_list_table/get_columns) β€” Gets the list of columns. * [get\_default\_primary\_column\_name](wp_application_passwords_list_table/get_default_primary_column_name) β€” Gets the name of the default primary column. * [prepare\_items](wp_application_passwords_list_table/prepare_items) β€” Prepares the list of items for displaying. * [print\_js\_template\_row](wp_application_passwords_list_table/print_js_template_row) β€” Prints the JavaScript template for the new row item. * [single\_row](wp_application_passwords_list_table/single_row) β€” Generates content for a single row of the table. File: `wp-admin/includes/class-wp-application-passwords-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-application-passwords-list-table.php/) ``` class WP_Application_Passwords_List_Table extends WP_List_Table { /** * Gets the list of columns. * * @since 5.6.0 * * @return array */ public function get_columns() { return array( 'name' => __( 'Name' ), 'created' => __( 'Created' ), 'last_used' => __( 'Last Used' ), 'last_ip' => __( 'Last IP' ), 'revoke' => __( 'Revoke' ), ); } /** * Prepares the list of items for displaying. * * @since 5.6.0 * * @global int $user_id User ID. */ public function prepare_items() { global $user_id; $this->items = array_reverse( WP_Application_Passwords::get_user_application_passwords( $user_id ) ); } /** * Handles the name column output. * * @since 5.6.0 * * @param array $item The current application password item. */ public function column_name( $item ) { echo esc_html( $item['name'] ); } /** * Handles the created column output. * * @since 5.6.0 * * @param array $item The current application password item. */ public function column_created( $item ) { if ( empty( $item['created'] ) ) { echo '&mdash;'; } else { echo date_i18n( __( 'F j, Y' ), $item['created'] ); } } /** * Handles the last used column output. * * @since 5.6.0 * * @param array $item The current application password item. */ public function column_last_used( $item ) { if ( empty( $item['last_used'] ) ) { echo '&mdash;'; } else { echo date_i18n( __( 'F j, Y' ), $item['last_used'] ); } } /** * Handles the last ip column output. * * @since 5.6.0 * * @param array $item The current application password item. */ public function column_last_ip( $item ) { if ( empty( $item['last_ip'] ) ) { echo '&mdash;'; } else { echo $item['last_ip']; } } /** * Handles the revoke column output. * * @since 5.6.0 * * @param array $item The current application password item. */ public function column_revoke( $item ) { $name = 'revoke-application-password-' . $item['uuid']; printf( '<button type="button" name="%1$s" id="%1$s" class="button delete" aria-label="%2$s">%3$s</button>', esc_attr( $name ), /* translators: %s: the application password's given name. */ esc_attr( sprintf( __( 'Revoke "%s"' ), $item['name'] ) ), __( 'Revoke' ) ); } /** * Generates content for a single row of the table * * @since 5.6.0 * * @param array $item The current item. * @param string $column_name The current column name. */ protected function column_default( $item, $column_name ) { /** * Fires for each custom column in the Application Passwords list table. * * Custom columns are registered using the {@see 'manage_application-passwords-user_columns'} filter. * * @since 5.6.0 * * @param string $column_name Name of the custom column. * @param array $item The application password item. */ do_action( "manage_{$this->screen->id}_custom_column", $column_name, $item ); } /** * Generates custom table navigation to prevent conflicting nonces. * * @since 5.6.0 * * @param string $which The location of the bulk actions: 'top' or 'bottom'. */ protected function display_tablenav( $which ) { ?> <div class="tablenav <?php echo esc_attr( $which ); ?>"> <?php if ( 'bottom' === $which ) : ?> <div class="alignright"> <button type="button" name="revoke-all-application-passwords" id="revoke-all-application-passwords" class="button delete"><?php _e( 'Revoke all application passwords' ); ?></button> </div> <?php endif; ?> <div class="alignleft actions bulkactions"> <?php $this->bulk_actions( $which ); ?> </div> <?php $this->extra_tablenav( $which ); $this->pagination( $which ); ?> <br class="clear" /> </div> <?php } /** * Generates content for a single row of the table. * * @since 5.6.0 * * @param array $item The current item. */ public function single_row( $item ) { echo '<tr data-uuid="' . esc_attr( $item['uuid'] ) . '">'; $this->single_row_columns( $item ); echo '</tr>'; } /** * Gets the name of the default primary column. * * @since 5.6.0 * * @return string Name of the default primary column, in this case, 'name'. */ protected function get_default_primary_column_name() { return 'name'; } /** * Prints the JavaScript template for the new row item. * * @since 5.6.0 */ public function print_js_template_row() { list( $columns, $hidden, , $primary ) = $this->get_column_info(); echo '<tr data-uuid="{{ data.uuid }}">'; foreach ( $columns as $column_name => $display_name ) { $is_primary = $primary === $column_name; $classes = "{$column_name} column-{$column_name}"; if ( $is_primary ) { $classes .= ' has-row-actions column-primary'; } if ( in_array( $column_name, $hidden, true ) ) { $classes .= ' hidden'; } printf( '<td class="%s" data-colname="%s">', esc_attr( $classes ), esc_attr( wp_strip_all_tags( $display_name ) ) ); switch ( $column_name ) { case 'name': echo '{{ data.name }}'; break; case 'created': // JSON encoding automatically doubles backslashes to ensure they don't get lost when printing the inline JS. echo '<# print( wp.date.dateI18n( ' . wp_json_encode( __( 'F j, Y' ) ) . ', data.created ) ) #>'; break; case 'last_used': echo '<# print( data.last_used !== null ? wp.date.dateI18n( ' . wp_json_encode( __( 'F j, Y' ) ) . ", data.last_used ) : 'β€”' ) #>"; break; case 'last_ip': echo "{{ data.last_ip || 'β€”' }}"; break; case 'revoke': printf( '<button type="button" class="button delete" aria-label="%1$s">%2$s</button>', /* translators: %s: the application password's given name. */ esc_attr( sprintf( __( 'Revoke "%s"' ), '{{ data.name }}' ) ), esc_html__( 'Revoke' ) ); break; default: /** * Fires in the JavaScript row template for each custom column in the Application Passwords list table. * * Custom columns are registered using the {@see 'manage_application-passwords-user_columns'} filter. * * @since 5.6.0 * * @param string $column_name Name of the custom column. */ do_action( "manage_{$this->screen->id}_custom_column_js_template", $column_name ); break; } if ( $is_primary ) { echo '<button type="button" class="toggle-row"><span class="screen-reader-text">' . __( 'Show more details' ) . '</span></button>'; } echo '</td>'; } echo '</tr>'; } } ``` | Uses | Description | | --- | --- | | [WP\_List\_Table](wp_list_table) wp-admin/includes/class-wp-list-table.php | Base class for displaying a list of items in an ajaxified HTML table. | | Version | Description | | --- | --- | | [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. | wordpress class WP_Error {} class WP\_Error {} ================== WordPress Error class. Container for checking for WordPress errors and error messages. Return [WP\_Error](wp_error) and use [is\_wp\_error()](../functions/is_wp_error) to check if this class is returned. Many core WordPress functions pass this class in the event of an error and if not handled properly will result in code errors. [WP\_Error](wp_error) is a class that makes error handling within plugins and WordPress itself much easier. Instances of [WP\_Error](wp_error) store error codes and messages representing one or more errors, and whether or not a variable is an instance of [WP\_Error](wp_error) can be determined using the [is\_wp\_error()](../functions/is_wp_error) function. Error codes are slugs that are used to identify each error. They are mostly useful when a piece of code can produce several different errors, and you want to handle each of those errors differently. The error codes used in WordPress are not integers, but strings, with any spaces between words replaced with underscores (example: an\_error\_code). The error codes used in WordPress are usually based on the error message associated with that code. Please refer source code for the complete lists of properties. Below description may cover some of them. $errors Array containing the list of errors. $error\_data Array containing the list of data for error codes. * see [is\_wp\_error()](../functions/is_wp_error) for more information on trapping for errors (particularly useful when faced with the dreaded β€˜Catchable fatal error: Object of class [WP\_Error](wp_error) could not be converted to string’) * [\_\_construct](wp_error/__construct) β€” Initializes the error. * [add](wp_error/add) β€” Adds an error or appends an additional message to an existing error. * [add\_data](wp_error/add_data) β€” Adds data to an error with the given code. * [copy\_errors](wp_error/copy_errors) β€” Copies errors from one WP\_Error instance to another. * [export\_to](wp_error/export_to) β€” Exports the errors in this object into the given one. * [get\_all\_error\_data](wp_error/get_all_error_data) β€” Retrieves all error data for an error code in the order in which the data was added. * [get\_error\_code](wp_error/get_error_code) β€” Retrieves the first error code available. * [get\_error\_codes](wp_error/get_error_codes) β€” Retrieves all error codes. * [get\_error\_data](wp_error/get_error_data) β€” Retrieves the most recently added error data for an error code. * [get\_error\_message](wp_error/get_error_message) β€” Gets a single error message. * [get\_error\_messages](wp_error/get_error_messages) β€” Retrieves all error messages, or the error messages for the given error code. * [has\_errors](wp_error/has_errors) β€” Verifies if the instance contains errors. * [merge\_from](wp_error/merge_from) β€” Merges the errors in the given error object into this one. * [remove](wp_error/remove) β€” Removes the specified error. File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/) ``` class WP_Error { /** * Stores the list of errors. * * @since 2.1.0 * @var array */ public $errors = array(); /** * Stores the most recently added data for each error code. * * @since 2.1.0 * @var array */ public $error_data = array(); /** * Stores previously added data added for error codes, oldest-to-newest by code. * * @since 5.6.0 * @var array[] */ protected $additional_data = array(); /** * Initializes the error. * * If `$code` is empty, the other parameters will be ignored. * When `$code` is not empty, `$message` will be used even if * it is empty. The `$data` parameter will be used only if it * is not empty. * * Though the class is constructed with a single error code and * message, multiple codes can be added using the `add()` method. * * @since 2.1.0 * * @param string|int $code Error code. * @param string $message Error message. * @param mixed $data Optional. Error data. */ public function __construct( $code = '', $message = '', $data = '' ) { if ( empty( $code ) ) { return; } $this->add( $code, $message, $data ); } /** * Retrieves all error codes. * * @since 2.1.0 * * @return array List of error codes, if available. */ public function get_error_codes() { if ( ! $this->has_errors() ) { return array(); } return array_keys( $this->errors ); } /** * Retrieves the first error code available. * * @since 2.1.0 * * @return string|int Empty string, if no error codes. */ public function get_error_code() { $codes = $this->get_error_codes(); if ( empty( $codes ) ) { return ''; } return $codes[0]; } /** * Retrieves all error messages, or the error messages for the given error code. * * @since 2.1.0 * * @param string|int $code Optional. Retrieve messages matching code, if exists. * @return string[] Error strings on success, or empty array if there are none. */ public function get_error_messages( $code = '' ) { // Return all messages if no code specified. if ( empty( $code ) ) { $all_messages = array(); foreach ( (array) $this->errors as $code => $messages ) { $all_messages = array_merge( $all_messages, $messages ); } return $all_messages; } if ( isset( $this->errors[ $code ] ) ) { return $this->errors[ $code ]; } else { return array(); } } /** * Gets a single error message. * * This will get the first message available for the code. If no code is * given then the first code available will be used. * * @since 2.1.0 * * @param string|int $code Optional. Error code to retrieve message. * @return string The error message. */ public function get_error_message( $code = '' ) { if ( empty( $code ) ) { $code = $this->get_error_code(); } $messages = $this->get_error_messages( $code ); if ( empty( $messages ) ) { return ''; } return $messages[0]; } /** * Retrieves the most recently added error data for an error code. * * @since 2.1.0 * * @param string|int $code Optional. Error code. * @return mixed Error data, if it exists. */ public function get_error_data( $code = '' ) { if ( empty( $code ) ) { $code = $this->get_error_code(); } if ( isset( $this->error_data[ $code ] ) ) { return $this->error_data[ $code ]; } } /** * Verifies if the instance contains errors. * * @since 5.1.0 * * @return bool If the instance contains errors. */ public function has_errors() { if ( ! empty( $this->errors ) ) { return true; } return false; } /** * Adds an error or appends an additional message to an existing error. * * @since 2.1.0 * * @param string|int $code Error code. * @param string $message Error message. * @param mixed $data Optional. Error data. */ public function add( $code, $message, $data = '' ) { $this->errors[ $code ][] = $message; if ( ! empty( $data ) ) { $this->add_data( $data, $code ); } /** * Fires when an error is added to a WP_Error object. * * @since 5.6.0 * * @param string|int $code Error code. * @param string $message Error message. * @param mixed $data Error data. Might be empty. * @param WP_Error $wp_error The WP_Error object. */ do_action( 'wp_error_added', $code, $message, $data, $this ); } /** * Adds data to an error with the given code. * * @since 2.1.0 * @since 5.6.0 Errors can now contain more than one item of error data. {@see WP_Error::$additional_data}. * * @param mixed $data Error data. * @param string|int $code Error code. */ public function add_data( $data, $code = '' ) { if ( empty( $code ) ) { $code = $this->get_error_code(); } if ( isset( $this->error_data[ $code ] ) ) { $this->additional_data[ $code ][] = $this->error_data[ $code ]; } $this->error_data[ $code ] = $data; } /** * Retrieves all error data for an error code in the order in which the data was added. * * @since 5.6.0 * * @param string|int $code Error code. * @return mixed[] Array of error data, if it exists. */ public function get_all_error_data( $code = '' ) { if ( empty( $code ) ) { $code = $this->get_error_code(); } $data = array(); if ( isset( $this->additional_data[ $code ] ) ) { $data = $this->additional_data[ $code ]; } if ( isset( $this->error_data[ $code ] ) ) { $data[] = $this->error_data[ $code ]; } return $data; } /** * Removes the specified error. * * This function removes all error messages associated with the specified * error code, along with any error data for that code. * * @since 4.1.0 * * @param string|int $code Error code. */ public function remove( $code ) { unset( $this->errors[ $code ] ); unset( $this->error_data[ $code ] ); unset( $this->additional_data[ $code ] ); } /** * Merges the errors in the given error object into this one. * * @since 5.6.0 * * @param WP_Error $error Error object to merge. */ public function merge_from( WP_Error $error ) { static::copy_errors( $error, $this ); } /** * Exports the errors in this object into the given one. * * @since 5.6.0 * * @param WP_Error $error Error object to export into. */ public function export_to( WP_Error $error ) { static::copy_errors( $this, $error ); } /** * Copies errors from one WP_Error instance to another. * * @since 5.6.0 * * @param WP_Error $from The WP_Error to copy from. * @param WP_Error $to The WP_Error to copy to. */ protected static function copy_errors( WP_Error $from, WP_Error $to ) { foreach ( $from->get_error_codes() as $code ) { foreach ( $from->get_error_messages( $code ) as $error_message ) { $to->add( $code, $error_message ); } foreach ( $from->get_all_error_data( $code ) as $data ) { $to->add_data( $data, $code ); } } } } ``` | Version | Description | | --- | --- | | [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. | wordpress class WP_Customize_Media_Control {} class WP\_Customize\_Media\_Control {} ====================================== Customize Media Control class. * [WP\_Customize\_Control](wp_customize_control) * [\_\_construct](wp_customize_media_control/__construct) β€” Constructor. * [content\_template](wp_customize_media_control/content_template) β€” Render a JS template for the content of the media control. * [enqueue](wp_customize_media_control/enqueue) β€” Enqueue control related scripts/styles. * [get\_default\_button\_labels](wp_customize_media_control/get_default_button_labels) β€” Get default button labels. * [render\_content](wp_customize_media_control/render_content) β€” Don't render any content for this control from PHP. * [to\_json](wp_customize_media_control/to_json) β€” Refresh the parameters passed to the JavaScript via JSON. File: `wp-includes/customize/class-wp-customize-media-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-media-control.php/) ``` class WP_Customize_Media_Control extends WP_Customize_Control { /** * Control type. * * @since 4.2.0 * @var string */ public $type = 'media'; /** * Media control mime type. * * @since 4.2.0 * @var string */ public $mime_type = ''; /** * Button labels. * * @since 4.2.0 * @var array */ public $button_labels = array(); /** * Constructor. * * @since 4.1.0 * @since 4.2.0 Moved from WP_Customize_Upload_Control. * * @see WP_Customize_Control::__construct() * * @param WP_Customize_Manager $manager Customizer bootstrap instance. * @param string $id Control ID. * @param array $args Optional. Arguments to override class property defaults. * See WP_Customize_Control::__construct() for information * on accepted arguments. Default empty array. */ public function __construct( $manager, $id, $args = array() ) { parent::__construct( $manager, $id, $args ); $this->button_labels = wp_parse_args( $this->button_labels, $this->get_default_button_labels() ); } /** * Enqueue control related scripts/styles. * * @since 3.4.0 * @since 4.2.0 Moved from WP_Customize_Upload_Control. */ public function enqueue() { wp_enqueue_media(); } /** * Refresh the parameters passed to the JavaScript via JSON. * * @since 3.4.0 * @since 4.2.0 Moved from WP_Customize_Upload_Control. * * @see WP_Customize_Control::to_json() */ public function to_json() { parent::to_json(); $this->json['label'] = html_entity_decode( $this->label, ENT_QUOTES, get_bloginfo( 'charset' ) ); $this->json['mime_type'] = $this->mime_type; $this->json['button_labels'] = $this->button_labels; $this->json['canUpload'] = current_user_can( 'upload_files' ); $value = $this->value(); if ( is_object( $this->setting ) ) { if ( $this->setting->default ) { // Fake an attachment model - needs all fields used by template. // Note that the default value must be a URL, NOT an attachment ID. $ext = substr( $this->setting->default, -3 ); $type = in_array( $ext, array( 'jpg', 'png', 'gif', 'bmp', 'webp' ), true ) ? 'image' : 'document'; $default_attachment = array( 'id' => 1, 'url' => $this->setting->default, 'type' => $type, 'icon' => wp_mime_type_icon( $type ), 'title' => wp_basename( $this->setting->default ), ); if ( 'image' === $type ) { $default_attachment['sizes'] = array( 'full' => array( 'url' => $this->setting->default ), ); } $this->json['defaultAttachment'] = $default_attachment; } if ( $value && $this->setting->default && $value === $this->setting->default ) { // Set the default as the attachment. $this->json['attachment'] = $this->json['defaultAttachment']; } elseif ( $value ) { $this->json['attachment'] = wp_prepare_attachment_for_js( $value ); } } } /** * Don't render any content for this control from PHP. * * @since 3.4.0 * @since 4.2.0 Moved from WP_Customize_Upload_Control. * * @see WP_Customize_Media_Control::content_template() */ public function render_content() {} /** * Render a JS template for the content of the media control. * * @since 4.1.0 * @since 4.2.0 Moved from WP_Customize_Upload_Control. */ public function content_template() { ?> <# var descriptionId = _.uniqueId( 'customize-media-control-description-' ); var describedByAttr = data.description ? ' aria-describedby="' + descriptionId + '" ' : ''; #> <# if ( data.label ) { #> <span class="customize-control-title">{{ data.label }}</span> <# } #> <div class="customize-control-notifications-container"></div> <# if ( data.description ) { #> <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span> <# } #> <# if ( data.attachment && data.attachment.id ) { #> <div class="attachment-media-view attachment-media-view-{{ data.attachment.type }} {{ data.attachment.orientation }}"> <div class="thumbnail thumbnail-{{ data.attachment.type }}"> <# if ( 'image' === data.attachment.type && data.attachment.sizes && data.attachment.sizes.medium ) { #> <img class="attachment-thumb" src="{{ data.attachment.sizes.medium.url }}" draggable="false" alt="" /> <# } else if ( 'image' === data.attachment.type && data.attachment.sizes && data.attachment.sizes.full ) { #> <img class="attachment-thumb" src="{{ data.attachment.sizes.full.url }}" draggable="false" alt="" /> <# } else if ( 'audio' === data.attachment.type ) { #> <# if ( data.attachment.image && data.attachment.image.src && data.attachment.image.src !== data.attachment.icon ) { #> <img src="{{ data.attachment.image.src }}" class="thumbnail" draggable="false" alt="" /> <# } else { #> <img src="{{ data.attachment.icon }}" class="attachment-thumb type-icon" draggable="false" alt="" /> <# } #> <p class="attachment-meta attachment-meta-title">&#8220;{{ data.attachment.title }}&#8221;</p> <# if ( data.attachment.album || data.attachment.meta.album ) { #> <p class="attachment-meta"><em>{{ data.attachment.album || data.attachment.meta.album }}</em></p> <# } #> <# if ( data.attachment.artist || data.attachment.meta.artist ) { #> <p class="attachment-meta">{{ data.attachment.artist || data.attachment.meta.artist }}</p> <# } #> <audio style="visibility: hidden" controls class="wp-audio-shortcode" width="100%" preload="none"> <source type="{{ data.attachment.mime }}" src="{{ data.attachment.url }}" /> </audio> <# } else if ( 'video' === data.attachment.type ) { #> <div class="wp-media-wrapper wp-video"> <video controls="controls" class="wp-video-shortcode" preload="metadata" <# if ( data.attachment.image && data.attachment.image.src !== data.attachment.icon ) { #>poster="{{ data.attachment.image.src }}"<# } #>> <source type="{{ data.attachment.mime }}" src="{{ data.attachment.url }}" /> </video> </div> <# } else { #> <img class="attachment-thumb type-icon icon" src="{{ data.attachment.icon }}" draggable="false" alt="" /> <p class="attachment-title">{{ data.attachment.title }}</p> <# } #> </div> <div class="actions"> <# if ( data.canUpload ) { #> <button type="button" class="button remove-button">{{ data.button_labels.remove }}</button> <button type="button" class="button upload-button control-focus" {{{ describedByAttr }}}>{{ data.button_labels.change }}</button> <# } #> </div> </div> <# } else { #> <div class="attachment-media-view"> <# if ( data.canUpload ) { #> <button type="button" class="upload-button button-add-media" {{{ describedByAttr }}}>{{ data.button_labels.select }}</button> <# } #> <div class="actions"> <# if ( data.defaultAttachment ) { #> <button type="button" class="button default-button">{{ data.button_labels['default'] }}</button> <# } #> </div> </div> <# } #> <?php } /** * Get default button labels. * * Provides an array of the default button labels based on the mime type of the current control. * * @since 4.9.0 * * @return string[] An associative array of default button labels keyed by the button name. */ public function get_default_button_labels() { // Get just the mime type and strip the mime subtype if present. $mime_type = ! empty( $this->mime_type ) ? strtok( ltrim( $this->mime_type, '/' ), '/' ) : 'default'; switch ( $mime_type ) { case 'video': return array( 'select' => __( 'Select video' ), 'change' => __( 'Change video' ), 'default' => __( 'Default' ), 'remove' => __( 'Remove' ), 'placeholder' => __( 'No video selected' ), 'frame_title' => __( 'Select video' ), 'frame_button' => __( 'Choose video' ), ); case 'audio': return array( 'select' => __( 'Select audio' ), 'change' => __( 'Change audio' ), 'default' => __( 'Default' ), 'remove' => __( 'Remove' ), 'placeholder' => __( 'No audio selected' ), 'frame_title' => __( 'Select audio' ), 'frame_button' => __( 'Choose audio' ), ); case 'image': return array( 'select' => __( 'Select image' ), 'site_icon' => __( 'Select site icon' ), 'change' => __( 'Change image' ), 'default' => __( 'Default' ), 'remove' => __( 'Remove' ), 'placeholder' => __( 'No image selected' ), 'frame_title' => __( 'Select image' ), 'frame_button' => __( 'Choose image' ), ); default: return array( 'select' => __( 'Select file' ), 'change' => __( 'Change file' ), 'default' => __( 'Default' ), 'remove' => __( 'Remove' ), 'placeholder' => __( 'No file selected' ), 'frame_title' => __( 'Select file' ), 'frame_button' => __( 'Choose file' ), ); } // End switch(). } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Control](wp_customize_control) wp-includes/class-wp-customize-control.php | Customize Control class. | | Used By | Description | | --- | --- | | [WP\_Customize\_Upload\_Control](wp_customize_upload_control) wp-includes/customize/class-wp-customize-upload-control.php | Customize Upload Control Class. | | Version | Description | | --- | --- | | [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
programming_docs
wordpress class WP_Embed {} class WP\_Embed {} ================== API for easily embedding rich media such as videos and images into content. * [\_\_construct](wp_embed/__construct) β€” Constructor * [autoembed](wp_embed/autoembed) β€” Passes any unlinked URLs that are on their own line to WP\_Embed::shortcode() for potential embedding. * [autoembed\_callback](wp_embed/autoembed_callback) β€” Callback function for WP\_Embed::autoembed(). * [cache\_oembed](wp_embed/cache_oembed) β€” Triggers a caching of all oEmbed results. * [delete\_oembed\_caches](wp_embed/delete_oembed_caches) β€” Deletes all oEmbed caches. Unused by core as of 4.0.0. * [find\_oembed\_post\_id](wp_embed/find_oembed_post_id) β€” Finds the oEmbed cache post ID for a given cache key. * [get\_embed\_handler\_html](wp_embed/get_embed_handler_html) β€” Returns embed HTML for a given URL from embed handlers. * [maybe\_make\_link](wp_embed/maybe_make_link) β€” Conditionally makes a hyperlink based on an internal class variable. * [maybe\_run\_ajax\_cache](wp_embed/maybe_run_ajax_cache) β€” If a post/page was saved, then output JavaScript to make an Ajax request that will call WP\_Embed::cache\_oembed(). * [register\_handler](wp_embed/register_handler) β€” Registers an embed handler. * [run\_shortcode](wp_embed/run_shortcode) β€” Processes the [embed] shortcode. * [shortcode](wp_embed/shortcode) β€” The do\_shortcode() callback function. * [unregister\_handler](wp_embed/unregister_handler) β€” Unregisters a previously-registered embed handler. File: `wp-includes/class-wp-embed.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-embed.php/) ``` class WP_Embed { public $handlers = array(); public $post_ID; public $usecache = true; public $linkifunknown = true; public $last_attr = array(); public $last_url = ''; /** * When a URL cannot be embedded, return false instead of returning a link * or the URL. * * Bypasses the {@see 'embed_maybe_make_link'} filter. * * @var bool */ public $return_false_on_fail = false; /** * Constructor */ public function __construct() { // Hack to get the [embed] shortcode to run before wpautop(). add_filter( 'the_content', array( $this, 'run_shortcode' ), 8 ); add_filter( 'widget_text_content', array( $this, 'run_shortcode' ), 8 ); add_filter( 'widget_block_content', array( $this, 'run_shortcode' ), 8 ); // Shortcode placeholder for strip_shortcodes(). add_shortcode( 'embed', '__return_false' ); // Attempts to embed all URLs in a post. add_filter( 'the_content', array( $this, 'autoembed' ), 8 ); add_filter( 'widget_text_content', array( $this, 'autoembed' ), 8 ); add_filter( 'widget_block_content', array( $this, 'autoembed' ), 8 ); // After a post is saved, cache oEmbed items via Ajax. add_action( 'edit_form_advanced', array( $this, 'maybe_run_ajax_cache' ) ); add_action( 'edit_page_form', array( $this, 'maybe_run_ajax_cache' ) ); } /** * Processes the [embed] shortcode. * * Since the [embed] shortcode needs to be run earlier than other shortcodes, * this function removes all existing shortcodes, registers the [embed] shortcode, * calls do_shortcode(), and then re-registers the old shortcodes. * * @global array $shortcode_tags * * @param string $content Content to parse. * @return string Content with shortcode parsed. */ public function run_shortcode( $content ) { global $shortcode_tags; // Back up current registered shortcodes and clear them all out. $orig_shortcode_tags = $shortcode_tags; remove_all_shortcodes(); add_shortcode( 'embed', array( $this, 'shortcode' ) ); // Do the shortcode (only the [embed] one is registered). $content = do_shortcode( $content, true ); // Put the original shortcodes back. $shortcode_tags = $orig_shortcode_tags; return $content; } /** * If a post/page was saved, then output JavaScript to make * an Ajax request that will call WP_Embed::cache_oembed(). */ public function maybe_run_ajax_cache() { $post = get_post(); if ( ! $post || empty( $_GET['message'] ) ) { return; } ?> <script type="text/javascript"> jQuery( function($) { $.get("<?php echo esc_url( admin_url( 'admin-ajax.php', 'relative' ) ) . '?action=oembed-cache&post=' . $post->ID; ?>"); } ); </script> <?php } /** * Registers an embed handler. * * Do not use this function directly, use wp_embed_register_handler() instead. * * This function should probably also only be used for sites that do not support oEmbed. * * @param string $id An internal ID/name for the handler. Needs to be unique. * @param string $regex The regex that will be used to see if this handler should be used for a URL. * @param callable $callback The callback function that will be called if the regex is matched. * @param int $priority Optional. Used to specify the order in which the registered handlers will be tested. * Lower numbers correspond with earlier testing, and handlers with the same priority are * tested in the order in which they were added to the action. Default 10. */ public function register_handler( $id, $regex, $callback, $priority = 10 ) { $this->handlers[ $priority ][ $id ] = array( 'regex' => $regex, 'callback' => $callback, ); } /** * Unregisters a previously-registered embed handler. * * Do not use this function directly, use wp_embed_unregister_handler() instead. * * @param string $id The handler ID that should be removed. * @param int $priority Optional. The priority of the handler to be removed (default: 10). */ public function unregister_handler( $id, $priority = 10 ) { unset( $this->handlers[ $priority ][ $id ] ); } /** * Returns embed HTML for a given URL from embed handlers. * * Attempts to convert a URL into embed HTML by checking the URL * against the regex of the registered embed handlers. * * @since 5.5.0 * * @param array $attr { * Shortcode attributes. Optional. * * @type int $width Width of the embed in pixels. * @type int $height Height of the embed in pixels. * } * @param string $url The URL attempting to be embedded. * @return string|false The embed HTML on success, false otherwise. */ public function get_embed_handler_html( $attr, $url ) { $rawattr = $attr; $attr = wp_parse_args( $attr, wp_embed_defaults( $url ) ); ksort( $this->handlers ); foreach ( $this->handlers as $priority => $handlers ) { foreach ( $handlers as $id => $handler ) { if ( preg_match( $handler['regex'], $url, $matches ) && is_callable( $handler['callback'] ) ) { $return = call_user_func( $handler['callback'], $matches, $attr, $url, $rawattr ); if ( false !== $return ) { /** * Filters the returned embed HTML. * * @since 2.9.0 * * @see WP_Embed::shortcode() * * @param string|false $return The HTML result of the shortcode, or false on failure. * @param string $url The embed URL. * @param array $attr An array of shortcode attributes. */ return apply_filters( 'embed_handler_html', $return, $url, $attr ); } } } } return false; } /** * The do_shortcode() callback function. * * Attempts to convert a URL into embed HTML. Starts by checking the URL against the regex of * the registered embed handlers. If none of the regex matches and it's enabled, then the URL * will be given to the WP_oEmbed class. * * @param array $attr { * Shortcode attributes. Optional. * * @type int $width Width of the embed in pixels. * @type int $height Height of the embed in pixels. * } * @param string $url The URL attempting to be embedded. * @return string|false The embed HTML on success, otherwise the original URL. * `->maybe_make_link()` can return false on failure. */ public function shortcode( $attr, $url = '' ) { $post = get_post(); if ( empty( $url ) && ! empty( $attr['src'] ) ) { $url = $attr['src']; } $this->last_url = $url; if ( empty( $url ) ) { $this->last_attr = $attr; return ''; } $rawattr = $attr; $attr = wp_parse_args( $attr, wp_embed_defaults( $url ) ); $this->last_attr = $attr; // KSES converts & into &amp; and we need to undo this. // See https://core.trac.wordpress.org/ticket/11311 $url = str_replace( '&amp;', '&', $url ); // Look for known internal handlers. $embed_handler_html = $this->get_embed_handler_html( $rawattr, $url ); if ( false !== $embed_handler_html ) { return $embed_handler_html; } $post_ID = ( ! empty( $post->ID ) ) ? $post->ID : null; // Potentially set by WP_Embed::cache_oembed(). if ( ! empty( $this->post_ID ) ) { $post_ID = $this->post_ID; } // Check for a cached result (stored as custom post or in the post meta). $key_suffix = md5( $url . serialize( $attr ) ); $cachekey = '_oembed_' . $key_suffix; $cachekey_time = '_oembed_time_' . $key_suffix; /** * Filters the oEmbed TTL value (time to live). * * @since 4.0.0 * * @param int $time Time to live (in seconds). * @param string $url The attempted embed URL. * @param array $attr An array of shortcode attributes. * @param int $post_ID Post ID. */ $ttl = apply_filters( 'oembed_ttl', DAY_IN_SECONDS, $url, $attr, $post_ID ); $cache = ''; $cache_time = 0; $cached_post_id = $this->find_oembed_post_id( $key_suffix ); if ( $post_ID ) { $cache = get_post_meta( $post_ID, $cachekey, true ); $cache_time = get_post_meta( $post_ID, $cachekey_time, true ); if ( ! $cache_time ) { $cache_time = 0; } } elseif ( $cached_post_id ) { $cached_post = get_post( $cached_post_id ); $cache = $cached_post->post_content; $cache_time = strtotime( $cached_post->post_modified_gmt ); } $cached_recently = ( time() - $cache_time ) < $ttl; if ( $this->usecache || $cached_recently ) { // Failures are cached. Serve one if we're using the cache. if ( '{{unknown}}' === $cache ) { return $this->maybe_make_link( $url ); } if ( ! empty( $cache ) ) { /** * Filters the cached oEmbed HTML. * * @since 2.9.0 * * @see WP_Embed::shortcode() * * @param string|false $cache The cached HTML result, stored in post meta. * @param string $url The attempted embed URL. * @param array $attr An array of shortcode attributes. * @param int $post_ID Post ID. */ return apply_filters( 'embed_oembed_html', $cache, $url, $attr, $post_ID ); } } /** * Filters whether to inspect the given URL for discoverable link tags. * * @since 2.9.0 * @since 4.4.0 The default value changed to true. * * @see WP_oEmbed::discover() * * @param bool $enable Whether to enable `<link>` tag discovery. Default true. */ $attr['discover'] = apply_filters( 'embed_oembed_discover', true ); // Use oEmbed to get the HTML. $html = wp_oembed_get( $url, $attr ); if ( $post_ID ) { if ( $html ) { update_post_meta( $post_ID, $cachekey, $html ); update_post_meta( $post_ID, $cachekey_time, time() ); } elseif ( ! $cache ) { update_post_meta( $post_ID, $cachekey, '{{unknown}}' ); } } else { $has_kses = false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' ); if ( $has_kses ) { // Prevent KSES from corrupting JSON in post_content. kses_remove_filters(); } $insert_post_args = array( 'post_name' => $key_suffix, 'post_status' => 'publish', 'post_type' => 'oembed_cache', ); if ( $html ) { if ( $cached_post_id ) { wp_update_post( wp_slash( array( 'ID' => $cached_post_id, 'post_content' => $html, ) ) ); } else { wp_insert_post( wp_slash( array_merge( $insert_post_args, array( 'post_content' => $html, ) ) ) ); } } elseif ( ! $cache ) { wp_insert_post( wp_slash( array_merge( $insert_post_args, array( 'post_content' => '{{unknown}}', ) ) ) ); } if ( $has_kses ) { kses_init_filters(); } } // If there was a result, return it. if ( $html ) { /** This filter is documented in wp-includes/class-wp-embed.php */ return apply_filters( 'embed_oembed_html', $html, $url, $attr, $post_ID ); } // Still unknown. return $this->maybe_make_link( $url ); } /** * Deletes all oEmbed caches. Unused by core as of 4.0.0. * * @param int $post_ID Post ID to delete the caches for. */ public function delete_oembed_caches( $post_ID ) { $post_metas = get_post_custom_keys( $post_ID ); if ( empty( $post_metas ) ) { return; } foreach ( $post_metas as $post_meta_key ) { if ( '_oembed_' === substr( $post_meta_key, 0, 8 ) ) { delete_post_meta( $post_ID, $post_meta_key ); } } } /** * Triggers a caching of all oEmbed results. * * @param int $post_ID Post ID to do the caching for. */ public function cache_oembed( $post_ID ) { $post = get_post( $post_ID ); $post_types = get_post_types( array( 'show_ui' => true ) ); /** * Filters the array of post types to cache oEmbed results for. * * @since 2.9.0 * * @param string[] $post_types Array of post type names to cache oEmbed results for. Defaults to post types with `show_ui` set to true. */ $cache_oembed_types = apply_filters( 'embed_cache_oembed_types', $post_types ); if ( empty( $post->ID ) || ! in_array( $post->post_type, $cache_oembed_types, true ) ) { return; } // Trigger a caching. if ( ! empty( $post->post_content ) ) { $this->post_ID = $post->ID; $this->usecache = false; $content = $this->run_shortcode( $post->post_content ); $this->autoembed( $content ); $this->usecache = true; } } /** * Passes any unlinked URLs that are on their own line to WP_Embed::shortcode() for potential embedding. * * @see WP_Embed::autoembed_callback() * * @param string $content The content to be searched. * @return string Potentially modified $content. */ public function autoembed( $content ) { // Replace line breaks from all HTML elements with placeholders. $content = wp_replace_in_html_tags( $content, array( "\n" => '<!-- wp-line-break -->' ) ); if ( preg_match( '#(^|\s|>)https?://#i', $content ) ) { // Find URLs on their own line. $content = preg_replace_callback( '|^(\s*)(https?://[^\s<>"]+)(\s*)$|im', array( $this, 'autoembed_callback' ), $content ); // Find URLs in their own paragraph. $content = preg_replace_callback( '|(<p(?: [^>]*)?>\s*)(https?://[^\s<>"]+)(\s*<\/p>)|i', array( $this, 'autoembed_callback' ), $content ); } // Put the line breaks back. return str_replace( '<!-- wp-line-break -->', "\n", $content ); } /** * Callback function for WP_Embed::autoembed(). * * @param array $matches A regex match array. * @return string The embed HTML on success, otherwise the original URL. */ public function autoembed_callback( $matches ) { $oldval = $this->linkifunknown; $this->linkifunknown = false; $return = $this->shortcode( array(), $matches[2] ); $this->linkifunknown = $oldval; return $matches[1] . $return . $matches[3]; } /** * Conditionally makes a hyperlink based on an internal class variable. * * @param string $url URL to potentially be linked. * @return string|false Linked URL or the original URL. False if 'return_false_on_fail' is true. */ public function maybe_make_link( $url ) { if ( $this->return_false_on_fail ) { return false; } $output = ( $this->linkifunknown ) ? '<a href="' . esc_url( $url ) . '">' . esc_html( $url ) . '</a>' : $url; /** * Filters the returned, maybe-linked embed URL. * * @since 2.9.0 * * @param string $output The linked or original URL. * @param string $url The original URL. */ return apply_filters( 'embed_maybe_make_link', $output, $url ); } /** * Finds the oEmbed cache post ID for a given cache key. * * @since 4.9.0 * * @param string $cache_key oEmbed cache key. * @return int|null Post ID on success, null on failure. */ public function find_oembed_post_id( $cache_key ) { $cache_group = 'oembed_cache_post'; $oembed_post_id = wp_cache_get( $cache_key, $cache_group ); if ( $oembed_post_id && 'oembed_cache' === get_post_type( $oembed_post_id ) ) { return $oembed_post_id; } $oembed_post_query = new WP_Query( array( 'post_type' => 'oembed_cache', 'post_status' => 'publish', 'name' => $cache_key, 'posts_per_page' => 1, 'no_found_rows' => true, 'cache_results' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, 'lazy_load_term_meta' => false, ) ); if ( ! empty( $oembed_post_query->posts ) ) { // Note: 'fields' => 'ids' is not being used in order to cache the post object as it will be needed. $oembed_post_id = $oembed_post_query->posts[0]->ID; wp_cache_set( $cache_key, $oembed_post_id, $cache_group ); return $oembed_post_id; } return null; } } ``` | Version | Description | | --- | --- | | [2.9.0](https://developer.wordpress.org/reference/since/2.9.0/) | Introduced. | wordpress class WP_Widget_Search {} class WP\_Widget\_Search {} =========================== Core class used to implement a Search widget. * [WP\_Widget](wp_widget) * [\_\_construct](wp_widget_search/__construct) β€” Sets up a new Search widget instance. * [form](wp_widget_search/form) β€” Outputs the settings form for the Search widget. * [update](wp_widget_search/update) β€” Handles updating settings for the current Search widget instance. * [widget](wp_widget_search/widget) β€” Outputs the content for the current Search widget instance. File: `wp-includes/widgets/class-wp-widget-search.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-search.php/) ``` class WP_Widget_Search extends WP_Widget { /** * Sets up a new Search widget instance. * * @since 2.8.0 */ public function __construct() { $widget_ops = array( 'classname' => 'widget_search', 'description' => __( 'A search form for your site.' ), 'customize_selective_refresh' => true, 'show_instance_in_rest' => true, ); parent::__construct( 'search', _x( 'Search', 'Search widget' ), $widget_ops ); } /** * Outputs the content for the current Search widget instance. * * @since 2.8.0 * * @param array $args Display arguments including 'before_title', 'after_title', * 'before_widget', and 'after_widget'. * @param array $instance Settings for the current Search widget instance. */ public function widget( $args, $instance ) { $title = ! empty( $instance['title'] ) ? $instance['title'] : ''; /** 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']; } // Use active theme search form if it exists. get_search_form(); echo $args['after_widget']; } /** * Outputs the settings form for the Search widget. * * @since 2.8.0 * * @param array $instance Current settings. */ public function form( $instance ) { $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) ); $title = $instance['title']; ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /> </p> <?php } /** * Handles updating settings for the current Search widget instance. * * @since 2.8.0 * * @param array $new_instance New settings for this instance as input by the user via * WP_Widget::form(). * @param array $old_instance Old settings for this instance. * @return array Updated settings. */ public function update( $new_instance, $old_instance ) { $instance = $old_instance; $new_instance = wp_parse_args( (array) $new_instance, array( 'title' => '' ) ); $instance['title'] = sanitize_text_field( $new_instance['title'] ); return $instance; } } ``` | Uses | Description | | --- | --- | | [WP\_Widget](wp_widget) wp-includes/class-wp-widget.php | Core base class extended to register widgets. | | Version | Description | | --- | --- | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
programming_docs
wordpress class WP_Customize_Header_Image_Control {} class WP\_Customize\_Header\_Image\_Control {} ============================================== Customize Header Image Control class. * [WP\_Customize\_Image\_Control](wp_customize_image_control) * [\_\_construct](wp_customize_header_image_control/__construct) β€” Constructor. * [enqueue](wp_customize_header_image_control/enqueue) * [get\_current\_image\_src](wp_customize_header_image_control/get_current_image_src) * [prepare\_control](wp_customize_header_image_control/prepare_control) * [print\_header\_image\_template](wp_customize_header_image_control/print_header_image_template) * [render\_content](wp_customize_header_image_control/render_content) File: `wp-includes/customize/class-wp-customize-header-image-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-header-image-control.php/) ``` class WP_Customize_Header_Image_Control extends WP_Customize_Image_Control { /** * Customize control type. * * @since 4.2.0 * @var string */ public $type = 'header'; /** * Uploaded header images. * * @since 3.9.0 * @var string */ public $uploaded_headers; /** * Default header images. * * @since 3.9.0 * @var string */ public $default_headers; /** * Constructor. * * @since 3.4.0 * * @param WP_Customize_Manager $manager Customizer bootstrap instance. */ public function __construct( $manager ) { parent::__construct( $manager, 'header_image', array( 'label' => __( 'Header Image' ), 'settings' => array( 'default' => 'header_image', 'data' => 'header_image_data', ), 'section' => 'header_image', 'removed' => 'remove-header', 'get_url' => 'get_header_image', ) ); } /** */ public function enqueue() { wp_enqueue_media(); wp_enqueue_script( 'customize-views' ); $this->prepare_control(); wp_localize_script( 'customize-views', '_wpCustomizeHeader', array( 'data' => array( 'width' => absint( get_theme_support( 'custom-header', 'width' ) ), 'height' => absint( get_theme_support( 'custom-header', 'height' ) ), 'flex-width' => absint( get_theme_support( 'custom-header', 'flex-width' ) ), 'flex-height' => absint( get_theme_support( 'custom-header', 'flex-height' ) ), 'currentImgSrc' => $this->get_current_image_src(), ), 'nonces' => array( 'add' => wp_create_nonce( 'header-add' ), 'remove' => wp_create_nonce( 'header-remove' ), ), 'uploads' => $this->uploaded_headers, 'defaults' => $this->default_headers, ) ); parent::enqueue(); } /** * @global Custom_Image_Header $custom_image_header */ public function prepare_control() { global $custom_image_header; if ( empty( $custom_image_header ) ) { return; } add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_header_image_template' ) ); // Process default headers and uploaded headers. $custom_image_header->process_default_headers(); $this->default_headers = $custom_image_header->get_default_header_images(); $this->uploaded_headers = $custom_image_header->get_uploaded_header_images(); } /** */ public function print_header_image_template() { ?> <script type="text/template" id="tmpl-header-choice"> <# if (data.random) { #> <button type="button" class="button display-options random"> <span class="dashicons dashicons-randomize dice"></span> <# if ( data.type === 'uploaded' ) { #> <?php _e( 'Randomize uploaded headers' ); ?> <# } else if ( data.type === 'default' ) { #> <?php _e( 'Randomize suggested headers' ); ?> <# } #> </button> <# } else { #> <button type="button" class="choice thumbnail" data-customize-image-value="{{data.header.url}}" data-customize-header-image-data="{{JSON.stringify(data.header)}}"> <span class="screen-reader-text"><?php _e( 'Set image' ); ?></span> <img src="{{data.header.thumbnail_url}}" alt="{{data.header.alt_text || data.header.description}}" /> </button> <# if ( data.type === 'uploaded' ) { #> <button type="button" class="dashicons dashicons-no close"><span class="screen-reader-text"><?php _e( 'Remove image' ); ?></span></button> <# } #> <# } #> </script> <script type="text/template" id="tmpl-header-current"> <# if (data.choice) { #> <# if (data.random) { #> <div class="placeholder"> <span class="dashicons dashicons-randomize dice"></span> <# if ( data.type === 'uploaded' ) { #> <?php _e( 'Randomizing uploaded headers' ); ?> <# } else if ( data.type === 'default' ) { #> <?php _e( 'Randomizing suggested headers' ); ?> <# } #> </div> <# } else { #> <img src="{{data.header.thumbnail_url}}" alt="{{data.header.alt_text || data.header.description}}" /> <# } #> <# } else { #> <div class="placeholder"> <?php _e( 'No image set' ); ?> </div> <# } #> </script> <?php } /** * @return string|void */ public function get_current_image_src() { $src = $this->value(); if ( isset( $this->get_url ) ) { $src = call_user_func( $this->get_url, $src ); return $src; } } /** */ public function render_content() { $visibility = $this->get_current_image_src() ? '' : ' style="display:none" '; $width = absint( get_theme_support( 'custom-header', 'width' ) ); $height = absint( get_theme_support( 'custom-header', 'height' ) ); ?> <div class="customize-control-content"> <?php if ( current_theme_supports( 'custom-header', 'video' ) ) { echo '<span class="customize-control-title">' . $this->label . '</span>'; } ?> <div class="customize-control-notifications-container"></div> <p class="customizer-section-intro customize-control-description"> <?php if ( current_theme_supports( 'custom-header', 'video' ) ) { _e( 'Click &#8220;Add new image&#8221; to upload an image file from your computer. Your theme works best with an image that matches the size of your video &#8212; you&#8217;ll be able to crop your image once you upload it for a perfect fit.' ); } elseif ( $width && $height ) { printf( /* translators: %s: Header size in pixels. */ __( 'Click &#8220;Add new image&#8221; to upload an image file from your computer. Your theme works best with an image with a header size of %s pixels &#8212; you&#8217;ll be able to crop your image once you upload it for a perfect fit.' ), sprintf( '<strong>%s &times; %s</strong>', $width, $height ) ); } elseif ( $width ) { printf( /* translators: %s: Header width in pixels. */ __( 'Click &#8220;Add new image&#8221; to upload an image file from your computer. Your theme works best with an image with a header width of %s pixels &#8212; you&#8217;ll be able to crop your image once you upload it for a perfect fit.' ), sprintf( '<strong>%s</strong>', $width ) ); } else { printf( /* translators: %s: Header height in pixels. */ __( 'Click &#8220;Add new image&#8221; to upload an image file from your computer. Your theme works best with an image with a header height of %s pixels &#8212; you&#8217;ll be able to crop your image once you upload it for a perfect fit.' ), sprintf( '<strong>%s</strong>', $height ) ); } ?> </p> <div class="current"> <label for="header_image-button"> <span class="customize-control-title"> <?php _e( 'Current header' ); ?> </span> </label> <div class="container"> </div> </div> <div class="actions"> <?php if ( current_user_can( 'upload_files' ) ) : ?> <button type="button"<?php echo $visibility; ?> class="button remove" aria-label="<?php esc_attr_e( 'Hide header image' ); ?>"><?php _e( 'Hide image' ); ?></button> <button type="button" class="button new" id="header_image-button" aria-label="<?php esc_attr_e( 'Add new header image' ); ?>"><?php _e( 'Add new image' ); ?></button> <?php endif; ?> </div> <div class="choices"> <span class="customize-control-title header-previously-uploaded"> <?php _ex( 'Previously uploaded', 'custom headers' ); ?> </span> <div class="uploaded"> <div class="list"> </div> </div> <span class="customize-control-title header-default"> <?php _ex( 'Suggested', 'custom headers' ); ?> </span> <div class="default"> <div class="list"> </div> </div> </div> </div> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Image\_Control](wp_customize_image_control) wp-includes/customize/class-wp-customize-image-control.php | Customize Image Control class. | | Version | Description | | --- | --- | | [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. | wordpress class WP_Widget_Links {} class WP\_Widget\_Links {} ========================== Core class used to implement a Links widget. * [WP\_Widget](wp_widget) * [\_\_construct](wp_widget_links/__construct) β€” Sets up a new Links widget instance. * [form](wp_widget_links/form) β€” Outputs the settings form for the Links widget. * [update](wp_widget_links/update) β€” Handles updating settings for the current Links widget instance. * [widget](wp_widget_links/widget) β€” Outputs the content for the current Links widget instance. File: `wp-includes/widgets/class-wp-widget-links.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-links.php/) ``` class WP_Widget_Links extends WP_Widget { /** * Sets up a new Links widget instance. * * @since 2.8.0 */ public function __construct() { $widget_ops = array( 'description' => __( 'Your blogroll' ), 'customize_selective_refresh' => true, ); parent::__construct( 'links', __( 'Links' ), $widget_ops ); } /** * Outputs the content for the current Links widget instance. * * @since 2.8.0 * * @param array $args Display arguments including 'before_title', 'after_title', * 'before_widget', and 'after_widget'. * @param array $instance Settings for the current Links widget instance. */ public function widget( $args, $instance ) { $show_description = isset( $instance['description'] ) ? $instance['description'] : false; $show_name = isset( $instance['name'] ) ? $instance['name'] : false; $show_rating = isset( $instance['rating'] ) ? $instance['rating'] : false; $show_images = isset( $instance['images'] ) ? $instance['images'] : true; $category = isset( $instance['category'] ) ? $instance['category'] : false; $orderby = isset( $instance['orderby'] ) ? $instance['orderby'] : 'name'; $order = 'rating' === $orderby ? 'DESC' : 'ASC'; $limit = isset( $instance['limit'] ) ? $instance['limit'] : -1; $before_widget = preg_replace( '/ id="[^"]*"/', ' id="%id"', $args['before_widget'] ); $widget_links_args = array( 'title_before' => $args['before_title'], 'title_after' => $args['after_title'], 'category_before' => $before_widget, 'category_after' => $args['after_widget'], 'show_images' => $show_images, 'show_description' => $show_description, 'show_name' => $show_name, 'show_rating' => $show_rating, 'category' => $category, 'class' => 'linkcat widget', 'orderby' => $orderby, 'order' => $order, 'limit' => $limit, ); /** * Filters the arguments for the Links widget. * * @since 2.6.0 * @since 4.4.0 Added the `$instance` parameter. * * @see wp_list_bookmarks() * * @param array $widget_links_args An array of arguments to retrieve the links list. * @param array $instance The settings for the particular instance of the widget. */ wp_list_bookmarks( apply_filters( 'widget_links_args', $widget_links_args, $instance ) ); } /** * Handles updating settings for the current Links widget instance. * * @since 2.8.0 * * @param array $new_instance New settings for this instance as input by the user via * WP_Widget::form(). * @param array $old_instance Old settings for this instance. * @return array Updated settings to save. */ public function update( $new_instance, $old_instance ) { $new_instance = (array) $new_instance; $instance = array( 'images' => 0, 'name' => 0, 'description' => 0, 'rating' => 0, ); foreach ( $instance as $field => $val ) { if ( isset( $new_instance[ $field ] ) ) { $instance[ $field ] = 1; } } $instance['orderby'] = 'name'; if ( in_array( $new_instance['orderby'], array( 'name', 'rating', 'id', 'rand' ), true ) ) { $instance['orderby'] = $new_instance['orderby']; } $instance['category'] = (int) $new_instance['category']; $instance['limit'] = ! empty( $new_instance['limit'] ) ? (int) $new_instance['limit'] : -1; return $instance; } /** * Outputs the settings form for the Links widget. * * @since 2.8.0 * * @param array $instance Current settings. */ public function form( $instance ) { // Defaults. $instance = wp_parse_args( (array) $instance, array( 'images' => true, 'name' => true, 'description' => false, 'rating' => false, 'category' => false, 'orderby' => 'name', 'limit' => -1, ) ); $link_cats = get_terms( array( 'taxonomy' => 'link_category' ) ); $limit = (int) $instance['limit']; if ( ! $limit ) { $limit = -1; } ?> <p> <label for="<?php echo $this->get_field_id( 'category' ); ?>"><?php _e( 'Select Link Category:' ); ?></label> <select class="widefat" id="<?php echo $this->get_field_id( 'category' ); ?>" name="<?php echo $this->get_field_name( 'category' ); ?>"> <option value=""><?php _ex( 'All Links', 'links widget' ); ?></option> <?php foreach ( $link_cats as $link_cat ) : ?> <option value="<?php echo (int) $link_cat->term_id; ?>" <?php selected( $instance['category'], $link_cat->term_id ); ?>> <?php echo esc_html( $link_cat->name ); ?> </option> <?php endforeach; ?> </select> <label for="<?php echo $this->get_field_id( 'orderby' ); ?>"><?php _e( 'Sort by:' ); ?></label> <select name="<?php echo $this->get_field_name( 'orderby' ); ?>" id="<?php echo $this->get_field_id( 'orderby' ); ?>" class="widefat"> <option value="name"<?php selected( $instance['orderby'], 'name' ); ?>><?php _e( 'Link title' ); ?></option> <option value="rating"<?php selected( $instance['orderby'], 'rating' ); ?>><?php _e( 'Link rating' ); ?></option> <option value="id"<?php selected( $instance['orderby'], 'id' ); ?>><?php _e( 'Link ID' ); ?></option> <option value="rand"<?php selected( $instance['orderby'], 'rand' ); ?>><?php _ex( 'Random', 'Links widget' ); ?></option> </select> </p> <p> <input class="checkbox" type="checkbox"<?php checked( $instance['images'], true ); ?> id="<?php echo $this->get_field_id( 'images' ); ?>" name="<?php echo $this->get_field_name( 'images' ); ?>" /> <label for="<?php echo $this->get_field_id( 'images' ); ?>"><?php _e( 'Show Link Image' ); ?></label> <br /> <input class="checkbox" type="checkbox"<?php checked( $instance['name'], true ); ?> id="<?php echo $this->get_field_id( 'name' ); ?>" name="<?php echo $this->get_field_name( 'name' ); ?>" /> <label for="<?php echo $this->get_field_id( 'name' ); ?>"><?php _e( 'Show Link Name' ); ?></label> <br /> <input class="checkbox" type="checkbox"<?php checked( $instance['description'], true ); ?> id="<?php echo $this->get_field_id( 'description' ); ?>" name="<?php echo $this->get_field_name( 'description' ); ?>" /> <label for="<?php echo $this->get_field_id( 'description' ); ?>"><?php _e( 'Show Link Description' ); ?></label> <br /> <input class="checkbox" type="checkbox"<?php checked( $instance['rating'], true ); ?> id="<?php echo $this->get_field_id( 'rating' ); ?>" name="<?php echo $this->get_field_name( 'rating' ); ?>" /> <label for="<?php echo $this->get_field_id( 'rating' ); ?>"><?php _e( 'Show Link Rating' ); ?></label> </p> <p> <label for="<?php echo $this->get_field_id( 'limit' ); ?>"><?php _e( 'Number of links to show:' ); ?></label> <input id="<?php echo $this->get_field_id( 'limit' ); ?>" name="<?php echo $this->get_field_name( 'limit' ); ?>" type="text" value="<?php echo ( -1 !== $limit ) ? (int) $limit : ''; ?>" size="3" /> </p> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_Widget](wp_widget) wp-includes/class-wp-widget.php | Core base class extended to register widgets. | | Version | Description | | --- | --- | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. | wordpress class Theme_Upgrader {} class Theme\_Upgrader {} ======================== Core class used for upgrading/installing themes. It is designed to upgrade/install themes from a local zip, remote zip URL, or uploaded zip file. * [WP\_Upgrader](wp_upgrader) * [bulk\_upgrade](theme_upgrader/bulk_upgrade) β€” Upgrade several themes at once. * [check\_package](theme_upgrader/check_package) β€” Checks that the package source contains a valid theme. * [check\_parent\_theme\_filter](theme_upgrader/check_parent_theme_filter) β€” Check if a child theme is being installed and we need to install its parent. * [current\_after](theme_upgrader/current_after) β€” Turn off maintenance mode after upgrading the active theme. * [current\_before](theme_upgrader/current_before) β€” Turn on maintenance mode before attempting to upgrade the active theme. * [delete\_old\_theme](theme_upgrader/delete_old_theme) β€” Delete the old theme during an upgrade. * [hide\_activate\_preview\_actions](theme_upgrader/hide_activate_preview_actions) β€” Don't display the activate and preview actions to the user. * [install](theme_upgrader/install) β€” Install a theme package. * [install\_strings](theme_upgrader/install_strings) β€” Initialize the installation strings. * [theme\_info](theme_upgrader/theme_info) β€” Get the WP\_Theme object for a theme. * [upgrade](theme_upgrader/upgrade) β€” Upgrade a theme. * [upgrade\_strings](theme_upgrader/upgrade_strings) β€” Initialize the upgrade strings. File: `wp-admin/includes/class-theme-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-theme-upgrader.php/) ``` class Theme_Upgrader extends WP_Upgrader { /** * Result of the theme upgrade offer. * * @since 2.8.0 * @var array|WP_Error $result * @see WP_Upgrader::$result */ public $result; /** * Whether multiple themes are being upgraded/installed in bulk. * * @since 2.9.0 * @var bool $bulk */ public $bulk = false; /** * New theme info. * * @since 5.5.0 * @var array $new_theme_data * * @see check_package() */ public $new_theme_data = array(); /** * Initialize the upgrade strings. * * @since 2.8.0 */ public function upgrade_strings() { $this->strings['up_to_date'] = __( 'The theme is at the latest version.' ); $this->strings['no_package'] = __( 'Update package not available.' ); /* translators: %s: Package URL. */ $this->strings['downloading_package'] = sprintf( __( 'Downloading update from %s&#8230;' ), '<span class="code">%s</span>' ); $this->strings['unpack_package'] = __( 'Unpacking the update&#8230;' ); $this->strings['remove_old'] = __( 'Removing the old version of the theme&#8230;' ); $this->strings['remove_old_failed'] = __( 'Could not remove the old theme.' ); $this->strings['process_failed'] = __( 'Theme update failed.' ); $this->strings['process_success'] = __( 'Theme updated successfully.' ); } /** * Initialize the installation strings. * * @since 2.8.0 */ public function install_strings() { $this->strings['no_package'] = __( 'Installation package not available.' ); /* translators: %s: Package URL. */ $this->strings['downloading_package'] = sprintf( __( 'Downloading installation package from %s&#8230;' ), '<span class="code">%s</span>' ); $this->strings['unpack_package'] = __( 'Unpacking the package&#8230;' ); $this->strings['installing_package'] = __( 'Installing the theme&#8230;' ); $this->strings['remove_old'] = __( 'Removing the old version of the theme&#8230;' ); $this->strings['remove_old_failed'] = __( 'Could not remove the old theme.' ); $this->strings['no_files'] = __( 'The theme contains no files.' ); $this->strings['process_failed'] = __( 'Theme installation failed.' ); $this->strings['process_success'] = __( 'Theme installed successfully.' ); /* translators: 1: Theme name, 2: Theme version. */ $this->strings['process_success_specific'] = __( 'Successfully installed the theme <strong>%1$s %2$s</strong>.' ); $this->strings['parent_theme_search'] = __( 'This theme requires a parent theme. Checking if it is installed&#8230;' ); /* translators: 1: Theme name, 2: Theme version. */ $this->strings['parent_theme_prepare_install'] = __( 'Preparing to install <strong>%1$s %2$s</strong>&#8230;' ); /* translators: 1: Theme name, 2: Theme version. */ $this->strings['parent_theme_currently_installed'] = __( 'The parent theme, <strong>%1$s %2$s</strong>, is currently installed.' ); /* translators: 1: Theme name, 2: Theme version. */ $this->strings['parent_theme_install_success'] = __( 'Successfully installed the parent theme, <strong>%1$s %2$s</strong>.' ); /* translators: %s: Theme name. */ $this->strings['parent_theme_not_found'] = sprintf( __( '<strong>The parent theme could not be found.</strong> You will need to install the parent theme, %s, before you can use this child theme.' ), '<strong>%s</strong>' ); /* translators: %s: Theme error. */ $this->strings['current_theme_has_errors'] = __( 'The active theme has the following error: "%s".' ); if ( ! empty( $this->skin->overwrite ) ) { if ( 'update-theme' === $this->skin->overwrite ) { $this->strings['installing_package'] = __( 'Updating the theme&#8230;' ); $this->strings['process_failed'] = __( 'Theme update failed.' ); $this->strings['process_success'] = __( 'Theme updated successfully.' ); } if ( 'downgrade-theme' === $this->skin->overwrite ) { $this->strings['installing_package'] = __( 'Downgrading the theme&#8230;' ); $this->strings['process_failed'] = __( 'Theme downgrade failed.' ); $this->strings['process_success'] = __( 'Theme downgraded successfully.' ); } } } /** * Check if a child theme is being installed and we need to install its parent. * * Hooked to the {@see 'upgrader_post_install'} filter by Theme_Upgrader::install(). * * @since 3.4.0 * * @param bool $install_result * @param array $hook_extra * @param array $child_result * @return bool */ public function check_parent_theme_filter( $install_result, $hook_extra, $child_result ) { // Check to see if we need to install a parent theme. $theme_info = $this->theme_info(); if ( ! $theme_info->parent() ) { return $install_result; } $this->skin->feedback( 'parent_theme_search' ); if ( ! $theme_info->parent()->errors() ) { $this->skin->feedback( 'parent_theme_currently_installed', $theme_info->parent()->display( 'Name' ), $theme_info->parent()->display( 'Version' ) ); // We already have the theme, fall through. return $install_result; } // We don't have the parent theme, let's install it. $api = themes_api( 'theme_information', array( 'slug' => $theme_info->get( 'Template' ), 'fields' => array( 'sections' => false, 'tags' => false, ), ) ); // Save on a bit of bandwidth. if ( ! $api || is_wp_error( $api ) ) { $this->skin->feedback( 'parent_theme_not_found', $theme_info->get( 'Template' ) ); // Don't show activate or preview actions after installation. add_filter( 'install_theme_complete_actions', array( $this, 'hide_activate_preview_actions' ) ); return $install_result; } // Backup required data we're going to override: $child_api = $this->skin->api; $child_success_message = $this->strings['process_success']; // Override them. $this->skin->api = $api; $this->strings['process_success_specific'] = $this->strings['parent_theme_install_success']; $this->skin->feedback( 'parent_theme_prepare_install', $api->name, $api->version ); add_filter( 'install_theme_complete_actions', '__return_false', 999 ); // Don't show any actions after installing the theme. // Install the parent theme. $parent_result = $this->run( array( 'package' => $api->download_link, 'destination' => get_theme_root(), 'clear_destination' => false, // Do not overwrite files. 'clear_working' => true, ) ); if ( is_wp_error( $parent_result ) ) { add_filter( 'install_theme_complete_actions', array( $this, 'hide_activate_preview_actions' ) ); } // Start cleaning up after the parent's installation. remove_filter( 'install_theme_complete_actions', '__return_false', 999 ); // Reset child's result and data. $this->result = $child_result; $this->skin->api = $child_api; $this->strings['process_success'] = $child_success_message; return $install_result; } /** * Don't display the activate and preview actions to the user. * * Hooked to the {@see 'install_theme_complete_actions'} filter by * Theme_Upgrader::check_parent_theme_filter() when installing * a child theme and installing the parent theme fails. * * @since 3.4.0 * * @param array $actions Preview actions. * @return array */ public function hide_activate_preview_actions( $actions ) { unset( $actions['activate'], $actions['preview'] ); return $actions; } /** * Install a theme package. * * @since 2.8.0 * @since 3.7.0 The `$args` parameter was added, making clearing the update cache optional. * * @param string $package The full local path or URI of the package. * @param array $args { * Optional. Other arguments for installing a theme package. Default empty array. * * @type bool $clear_update_cache Whether to clear the updates cache if successful. * Default true. * } * * @return bool|WP_Error True if the installation was successful, false or a WP_Error object otherwise. */ public function install( $package, $args = array() ) { $defaults = array( 'clear_update_cache' => true, 'overwrite_package' => false, // Do not overwrite files. ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->install_strings(); add_filter( 'upgrader_source_selection', array( $this, 'check_package' ) ); add_filter( 'upgrader_post_install', array( $this, 'check_parent_theme_filter' ), 10, 3 ); if ( $parsed_args['clear_update_cache'] ) { // Clear cache so wp_update_themes() knows about the new theme. add_action( 'upgrader_process_complete', 'wp_clean_themes_cache', 9, 0 ); } $this->run( array( 'package' => $package, 'destination' => get_theme_root(), 'clear_destination' => $parsed_args['overwrite_package'], 'clear_working' => true, 'hook_extra' => array( 'type' => 'theme', 'action' => 'install', ), ) ); remove_action( 'upgrader_process_complete', 'wp_clean_themes_cache', 9 ); remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) ); remove_filter( 'upgrader_post_install', array( $this, 'check_parent_theme_filter' ) ); if ( ! $this->result || is_wp_error( $this->result ) ) { return $this->result; } // Refresh the Theme Update information. wp_clean_themes_cache( $parsed_args['clear_update_cache'] ); if ( $parsed_args['overwrite_package'] ) { /** This action is documented in wp-admin/includes/class-plugin-upgrader.php */ do_action( 'upgrader_overwrote_package', $package, $this->new_theme_data, 'theme' ); } return true; } /** * Upgrade a theme. * * @since 2.8.0 * @since 3.7.0 The `$args` parameter was added, making clearing the update cache optional. * * @param string $theme The theme slug. * @param array $args { * Optional. Other arguments for upgrading a theme. Default empty array. * * @type bool $clear_update_cache Whether to clear the update cache if successful. * Default true. * } * @return bool|WP_Error True if the upgrade was successful, false or a WP_Error object otherwise. */ public function upgrade( $theme, $args = array() ) { $defaults = array( 'clear_update_cache' => true, ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->upgrade_strings(); // Is an update available? $current = get_site_transient( 'update_themes' ); if ( ! isset( $current->response[ $theme ] ) ) { $this->skin->before(); $this->skin->set_result( false ); $this->skin->error( 'up_to_date' ); $this->skin->after(); return false; } $r = $current->response[ $theme ]; add_filter( 'upgrader_pre_install', array( $this, 'current_before' ), 10, 2 ); add_filter( 'upgrader_post_install', array( $this, 'current_after' ), 10, 2 ); add_filter( 'upgrader_clear_destination', array( $this, 'delete_old_theme' ), 10, 4 ); if ( $parsed_args['clear_update_cache'] ) { // Clear cache so wp_update_themes() knows about the new theme. add_action( 'upgrader_process_complete', 'wp_clean_themes_cache', 9, 0 ); } $this->run( array( 'package' => $r['package'], 'destination' => get_theme_root( $theme ), 'clear_destination' => true, 'clear_working' => true, 'hook_extra' => array( 'theme' => $theme, 'type' => 'theme', 'action' => 'update', ), ) ); remove_action( 'upgrader_process_complete', 'wp_clean_themes_cache', 9 ); remove_filter( 'upgrader_pre_install', array( $this, 'current_before' ) ); remove_filter( 'upgrader_post_install', array( $this, 'current_after' ) ); remove_filter( 'upgrader_clear_destination', array( $this, 'delete_old_theme' ) ); if ( ! $this->result || is_wp_error( $this->result ) ) { return $this->result; } wp_clean_themes_cache( $parsed_args['clear_update_cache'] ); // Ensure any future auto-update failures trigger a failure email by removing // the last failure notification from the list when themes update successfully. $past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() ); if ( isset( $past_failure_emails[ $theme ] ) ) { unset( $past_failure_emails[ $theme ] ); update_option( 'auto_plugin_theme_update_emails', $past_failure_emails ); } return true; } /** * Upgrade several themes at once. * * @since 3.0.0 * @since 3.7.0 The `$args` parameter was added, making clearing the update cache optional. * * @param string[] $themes Array of the theme slugs. * @param array $args { * Optional. Other arguments for upgrading several themes at once. Default empty array. * * @type bool $clear_update_cache Whether to clear the update cache if successful. * Default true. * } * @return array[]|false An array of results, or false if unable to connect to the filesystem. */ public function bulk_upgrade( $themes, $args = array() ) { $defaults = array( 'clear_update_cache' => true, ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->bulk = true; $this->upgrade_strings(); $current = get_site_transient( 'update_themes' ); add_filter( 'upgrader_pre_install', array( $this, 'current_before' ), 10, 2 ); add_filter( 'upgrader_post_install', array( $this, 'current_after' ), 10, 2 ); add_filter( 'upgrader_clear_destination', array( $this, 'delete_old_theme' ), 10, 4 ); $this->skin->header(); // Connect to the filesystem first. $res = $this->fs_connect( array( WP_CONTENT_DIR ) ); if ( ! $res ) { $this->skin->footer(); return false; } $this->skin->bulk_header(); /* * Only start maintenance mode if: * - running Multisite and there are one or more themes specified, OR * - a theme with an update available is currently in use. * @todo For multisite, maintenance mode should only kick in for individual sites if at all possible. */ $maintenance = ( is_multisite() && ! empty( $themes ) ); foreach ( $themes as $theme ) { $maintenance = $maintenance || get_stylesheet() === $theme || get_template() === $theme; } if ( $maintenance ) { $this->maintenance_mode( true ); } $results = array(); $this->update_count = count( $themes ); $this->update_current = 0; foreach ( $themes as $theme ) { $this->update_current++; $this->skin->theme_info = $this->theme_info( $theme ); if ( ! isset( $current->response[ $theme ] ) ) { $this->skin->set_result( true ); $this->skin->before(); $this->skin->feedback( 'up_to_date' ); $this->skin->after(); $results[ $theme ] = true; continue; } // Get the URL to the zip file. $r = $current->response[ $theme ]; $result = $this->run( array( 'package' => $r['package'], 'destination' => get_theme_root( $theme ), 'clear_destination' => true, 'clear_working' => true, 'is_multi' => true, 'hook_extra' => array( 'theme' => $theme, ), ) ); $results[ $theme ] = $result; // Prevent credentials auth screen from displaying multiple times. if ( false === $result ) { break; } } // End foreach $themes. $this->maintenance_mode( false ); // Refresh the Theme Update information. wp_clean_themes_cache( $parsed_args['clear_update_cache'] ); /** This action is documented in wp-admin/includes/class-wp-upgrader.php */ do_action( 'upgrader_process_complete', $this, array( 'action' => 'update', 'type' => 'theme', 'bulk' => true, 'themes' => $themes, ) ); $this->skin->bulk_footer(); $this->skin->footer(); // Cleanup our hooks, in case something else does a upgrade on this connection. remove_filter( 'upgrader_pre_install', array( $this, 'current_before' ) ); remove_filter( 'upgrader_post_install', array( $this, 'current_after' ) ); remove_filter( 'upgrader_clear_destination', array( $this, 'delete_old_theme' ) ); // Ensure any future auto-update failures trigger a failure email by removing // the last failure notification from the list when themes update successfully. $past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() ); foreach ( $results as $theme => $result ) { // Maintain last failure notification when themes failed to update manually. if ( ! $result || is_wp_error( $result ) || ! isset( $past_failure_emails[ $theme ] ) ) { continue; } unset( $past_failure_emails[ $theme ] ); } update_option( 'auto_plugin_theme_update_emails', $past_failure_emails ); return $results; } /** * Checks that the package source contains a valid theme. * * Hooked to the {@see 'upgrader_source_selection'} filter by Theme_Upgrader::install(). * * @since 3.3.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * @global string $wp_version The WordPress version string. * * @param string $source The path to the downloaded package source. * @return string|WP_Error The source as passed, or a WP_Error object on failure. */ public function check_package( $source ) { global $wp_filesystem, $wp_version; $this->new_theme_data = array(); if ( is_wp_error( $source ) ) { return $source; } // Check that the folder contains a valid theme. $working_directory = str_replace( $wp_filesystem->wp_content_dir(), trailingslashit( WP_CONTENT_DIR ), $source ); if ( ! is_dir( $working_directory ) ) { // Sanity check, if the above fails, let's not prevent installation. return $source; } // A proper archive should have a style.css file in the single subdirectory. if ( ! file_exists( $working_directory . 'style.css' ) ) { return new WP_Error( 'incompatible_archive_theme_no_style', $this->strings['incompatible_archive'], sprintf( /* translators: %s: style.css */ __( 'The theme is missing the %s stylesheet.' ), '<code>style.css</code>' ) ); } // All these headers are needed on Theme_Installer_Skin::do_overwrite(). $info = get_file_data( $working_directory . 'style.css', array( 'Name' => 'Theme Name', 'Version' => 'Version', 'Author' => 'Author', 'Template' => 'Template', 'RequiresWP' => 'Requires at least', 'RequiresPHP' => 'Requires PHP', ) ); if ( empty( $info['Name'] ) ) { return new WP_Error( 'incompatible_archive_theme_no_name', $this->strings['incompatible_archive'], sprintf( /* translators: %s: style.css */ __( 'The %s stylesheet does not contain a valid theme header.' ), '<code>style.css</code>' ) ); } /* * Parent themes must contain an index file: * - classic themes require /index.php * - block themes require /templates/index.html or block-templates/index.html (deprecated 5.9.0). */ if ( empty( $info['Template'] ) && ! file_exists( $working_directory . 'index.php' ) && ! file_exists( $working_directory . 'templates/index.html' ) && ! file_exists( $working_directory . 'block-templates/index.html' ) ) { return new WP_Error( 'incompatible_archive_theme_no_index', $this->strings['incompatible_archive'], 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>' ) ); } $requires_php = isset( $info['RequiresPHP'] ) ? $info['RequiresPHP'] : null; $requires_wp = isset( $info['RequiresWP'] ) ? $info['RequiresWP'] : null; if ( ! is_php_version_compatible( $requires_php ) ) { $error = sprintf( /* translators: 1: Current PHP version, 2: Version required by the uploaded theme. */ __( 'The PHP version on your server is %1$s, however the uploaded theme requires %2$s.' ), PHP_VERSION, $requires_php ); return new WP_Error( 'incompatible_php_required_version', $this->strings['incompatible_archive'], $error ); } if ( ! is_wp_version_compatible( $requires_wp ) ) { $error = sprintf( /* translators: 1: Current WordPress version, 2: Version required by the uploaded theme. */ __( 'Your WordPress version is %1$s, however the uploaded theme requires %2$s.' ), $wp_version, $requires_wp ); return new WP_Error( 'incompatible_wp_required_version', $this->strings['incompatible_archive'], $error ); } $this->new_theme_data = $info; return $source; } /** * Turn on maintenance mode before attempting to upgrade the active theme. * * Hooked to the {@see 'upgrader_pre_install'} filter by Theme_Upgrader::upgrade() and * Theme_Upgrader::bulk_upgrade(). * * @since 2.8.0 * * @param bool|WP_Error $response The installation response before the installation has started. * @param array $theme Theme arguments. * @return bool|WP_Error The original `$response` parameter or WP_Error. */ public function current_before( $response, $theme ) { if ( is_wp_error( $response ) ) { return $response; } $theme = isset( $theme['theme'] ) ? $theme['theme'] : ''; // Only run if active theme. if ( get_stylesheet() !== $theme ) { return $response; } // Change to maintenance mode. Bulk edit handles this separately. if ( ! $this->bulk ) { $this->maintenance_mode( true ); } return $response; } /** * Turn off maintenance mode after upgrading the active theme. * * Hooked to the {@see 'upgrader_post_install'} filter by Theme_Upgrader::upgrade() * and Theme_Upgrader::bulk_upgrade(). * * @since 2.8.0 * * @param bool|WP_Error $response The installation response after the installation has finished. * @param array $theme Theme arguments. * @return bool|WP_Error The original `$response` parameter or WP_Error. */ public function current_after( $response, $theme ) { if ( is_wp_error( $response ) ) { return $response; } $theme = isset( $theme['theme'] ) ? $theme['theme'] : ''; // Only run if active theme. if ( get_stylesheet() !== $theme ) { return $response; } // Ensure stylesheet name hasn't changed after the upgrade: if ( get_stylesheet() === $theme && $theme !== $this->result['destination_name'] ) { wp_clean_themes_cache(); $stylesheet = $this->result['destination_name']; switch_theme( $stylesheet ); } // Time to remove maintenance mode. Bulk edit handles this separately. if ( ! $this->bulk ) { $this->maintenance_mode( false ); } return $response; } /** * Delete the old theme during an upgrade. * * Hooked to the {@see 'upgrader_clear_destination'} filter by Theme_Upgrader::upgrade() * and Theme_Upgrader::bulk_upgrade(). * * @since 2.8.0 * * @global WP_Filesystem_Base $wp_filesystem Subclass * * @param bool $removed * @param string $local_destination * @param string $remote_destination * @param array $theme * @return bool */ public function delete_old_theme( $removed, $local_destination, $remote_destination, $theme ) { global $wp_filesystem; if ( is_wp_error( $removed ) ) { return $removed; // Pass errors through. } if ( ! isset( $theme['theme'] ) ) { return $removed; } $theme = $theme['theme']; $themes_dir = trailingslashit( $wp_filesystem->wp_themes_dir( $theme ) ); if ( $wp_filesystem->exists( $themes_dir . $theme ) ) { if ( ! $wp_filesystem->delete( $themes_dir . $theme, true ) ) { return false; } } return true; } /** * Get the WP_Theme object for a theme. * * @since 2.8.0 * @since 3.0.0 The `$theme` argument was added. * * @param string $theme The directory name of the theme. This is optional, and if not supplied, * the directory name from the last result will be used. * @return WP_Theme|false The theme's info object, or false `$theme` is not supplied * and the last result isn't set. */ public function theme_info( $theme = null ) { if ( empty( $theme ) ) { if ( ! empty( $this->result['destination_name'] ) ) { $theme = $this->result['destination_name']; } else { return false; } } $theme = wp_get_theme( $theme ); $theme->cache_delete(); return $theme; } } ``` | Uses | Description | | --- | --- | | [WP\_Upgrader](wp_upgrader) wp-admin/includes/class-wp-upgrader.php | | | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Moved to its own file from wp-admin/includes/class-wp-upgrader.php. | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
programming_docs
wordpress class WP_Sitemaps_Users {} class WP\_Sitemaps\_Users {} ============================ Users XML sitemap provider. * [\_\_construct](wp_sitemaps_users/__construct) β€” WP\_Sitemaps\_Users constructor. * [get\_max\_num\_pages](wp_sitemaps_users/get_max_num_pages) β€” Gets the max number of pages available for the object type. * [get\_url\_list](wp_sitemaps_users/get_url_list) β€” Gets a URL list for a user sitemap. * [get\_users\_query\_args](wp_sitemaps_users/get_users_query_args) β€” Returns the query args for retrieving users to list in the sitemap. File: `wp-includes/sitemaps/providers/class-wp-sitemaps-users.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/providers/class-wp-sitemaps-users.php/) ``` class WP_Sitemaps_Users extends WP_Sitemaps_Provider { /** * WP_Sitemaps_Users constructor. * * @since 5.5.0 */ public function __construct() { $this->name = 'users'; $this->object_type = 'user'; } /** * Gets a URL list for a user sitemap. * * @since 5.5.0 * * @param int $page_num Page of results. * @param string $object_subtype Optional. Not applicable for Users but * required for compatibility with the parent * provider class. Default empty. * @return array[] Array of URL information for a sitemap. */ public function get_url_list( $page_num, $object_subtype = '' ) { /** * Filters the users 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 int $page_num Page of results. */ $url_list = apply_filters( 'wp_sitemaps_users_pre_url_list', null, $page_num ); if ( null !== $url_list ) { return $url_list; } $args = $this->get_users_query_args(); $args['paged'] = $page_num; $query = new WP_User_Query( $args ); $users = $query->get_results(); $url_list = array(); foreach ( $users as $user ) { $sitemap_entry = array( 'loc' => get_author_posts_url( $user->ID ), ); /** * Filters the sitemap entry for an individual user. * * @since 5.5.0 * * @param array $sitemap_entry Sitemap entry for the user. * @param WP_User $user User object. */ $sitemap_entry = apply_filters( 'wp_sitemaps_users_entry', $sitemap_entry, $user ); $url_list[] = $sitemap_entry; } return $url_list; } /** * Gets the max number of pages available for the object type. * * @since 5.5.0 * * @see WP_Sitemaps_Provider::max_num_pages * * @param string $object_subtype Optional. Not applicable for Users but * required for compatibility with the parent * provider class. Default empty. * @return int Total page count. */ public function get_max_num_pages( $object_subtype = '' ) { /** * Filters the max number of pages for a user sitemap before it is generated. * * Returning a non-null value will effectively 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. */ $max_num_pages = apply_filters( 'wp_sitemaps_users_pre_max_num_pages', null ); if ( null !== $max_num_pages ) { return $max_num_pages; } $args = $this->get_users_query_args(); $query = new WP_User_Query( $args ); $total_users = $query->get_total(); return (int) ceil( $total_users / wp_sitemaps_get_max_urls( $this->object_type ) ); } /** * Returns the query args for retrieving users to list in the sitemap. * * @since 5.5.0 * * @return array Array of WP_User_Query arguments. */ protected function get_users_query_args() { $public_post_types = get_post_types( array( 'public' => true, ) ); // We're not supporting sitemaps for author pages for attachments. unset( $public_post_types['attachment'] ); /** * Filters the query arguments for authors with public posts. * * Allows modification of the authors query arguments before querying. * * @see WP_User_Query for a full list of arguments * * @since 5.5.0 * * @param array $args Array of WP_User_Query arguments. */ $args = apply_filters( 'wp_sitemaps_users_query_args', array( 'has_published_posts' => array_keys( $public_post_types ), 'number' => wp_sitemaps_get_max_urls( $this->object_type ), ) ); return $args; } } ``` | Uses | Description | | --- | --- | | [WP\_Sitemaps\_Provider](wp_sitemaps_provider) wp-includes/sitemaps/class-wp-sitemaps-provider.php | Class [WP\_Sitemaps\_Provider](wp_sitemaps_provider). | | Version | Description | | --- | --- | | [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. | wordpress class Requests_Exception_HTTP_408 {} class Requests\_Exception\_HTTP\_408 {} ======================================= Exception for 408 Request Timeout responses File: `wp-includes/Requests/Exception/HTTP/408.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/408.php/) ``` class Requests_Exception_HTTP_408 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 408; /** * Reason phrase * * @var string */ protected $reason = 'Request Timeout'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_Block_Type_Registry {} class WP\_Block\_Type\_Registry {} ================================== Core class used for interacting with block types. * [get\_all\_registered](wp_block_type_registry/get_all_registered) β€” Retrieves all registered block types. * [get\_instance](wp_block_type_registry/get_instance) β€” Utility method to retrieve the main instance of the class. * [get\_registered](wp_block_type_registry/get_registered) β€” Retrieves a registered block type. * [is\_registered](wp_block_type_registry/is_registered) β€” Checks if a block type is registered. * [register](wp_block_type_registry/register) β€” Registers a block type. * [unregister](wp_block_type_registry/unregister) β€” Unregisters a block type. File: `wp-includes/class-wp-block-type-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type-registry.php/) ``` final class WP_Block_Type_Registry { /** * Registered block types, as `$name => $instance` pairs. * * @since 5.0.0 * @var WP_Block_Type[] */ private $registered_block_types = array(); /** * Container for the main instance of the class. * * @since 5.0.0 * @var WP_Block_Type_Registry|null */ private static $instance = null; /** * Registers a block type. * * @since 5.0.0 * * @see WP_Block_Type::__construct() * * @param string|WP_Block_Type $name Block type name including namespace, or alternatively * a complete WP_Block_Type instance. In case a WP_Block_Type * is provided, the $args parameter will be ignored. * @param array $args Optional. Array of block type arguments. Accepts any public property * of `WP_Block_Type`. See WP_Block_Type::__construct() for information * on accepted arguments. Default empty array. * @return WP_Block_Type|false The registered block type on success, or false on failure. */ public function register( $name, $args = array() ) { $block_type = null; if ( $name instanceof WP_Block_Type ) { $block_type = $name; $name = $block_type->name; } if ( ! is_string( $name ) ) { _doing_it_wrong( __METHOD__, __( 'Block type names must be strings.' ), '5.0.0' ); return false; } if ( preg_match( '/[A-Z]+/', $name ) ) { _doing_it_wrong( __METHOD__, __( 'Block type names must not contain uppercase characters.' ), '5.0.0' ); return false; } $name_matcher = '/^[a-z0-9-]+\/[a-z0-9-]+$/'; if ( ! preg_match( $name_matcher, $name ) ) { _doing_it_wrong( __METHOD__, __( 'Block type names must contain a namespace prefix. Example: my-plugin/my-custom-block-type' ), '5.0.0' ); return false; } if ( $this->is_registered( $name ) ) { _doing_it_wrong( __METHOD__, /* translators: %s: Block name. */ sprintf( __( 'Block type "%s" is already registered.' ), $name ), '5.0.0' ); return false; } if ( ! $block_type ) { $block_type = new WP_Block_Type( $name, $args ); } $this->registered_block_types[ $name ] = $block_type; return $block_type; } /** * Unregisters a block type. * * @since 5.0.0 * * @param string|WP_Block_Type $name Block type name including namespace, or alternatively * a complete WP_Block_Type instance. * @return WP_Block_Type|false The unregistered block type on success, or false on failure. */ public function unregister( $name ) { if ( $name instanceof WP_Block_Type ) { $name = $name->name; } if ( ! $this->is_registered( $name ) ) { _doing_it_wrong( __METHOD__, /* translators: %s: Block name. */ sprintf( __( 'Block type "%s" is not registered.' ), $name ), '5.0.0' ); return false; } $unregistered_block_type = $this->registered_block_types[ $name ]; unset( $this->registered_block_types[ $name ] ); return $unregistered_block_type; } /** * Retrieves a registered block type. * * @since 5.0.0 * * @param string $name Block type name including namespace. * @return WP_Block_Type|null The registered block type, or null if it is not registered. */ public function get_registered( $name ) { if ( ! $this->is_registered( $name ) ) { return null; } return $this->registered_block_types[ $name ]; } /** * Retrieves all registered block types. * * @since 5.0.0 * * @return WP_Block_Type[] Associative array of `$block_type_name => $block_type` pairs. */ public function get_all_registered() { return $this->registered_block_types; } /** * Checks if a block type is registered. * * @since 5.0.0 * * @param string $name Block type name including namespace. * @return bool True if the block type is registered, false otherwise. */ public function is_registered( $name ) { return isset( $this->registered_block_types[ $name ] ); } /** * Utility method to retrieve the main instance of the class. * * The instance will be created if it does not exist yet. * * @since 5.0.0 * * @return WP_Block_Type_Registry The main instance. */ public static function get_instance() { if ( null === self::$instance ) { self::$instance = new self(); } return self::$instance; } } ``` | Version | Description | | --- | --- | | [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. | wordpress class WP_REST_Response {} class WP\_REST\_Response {} =========================== Core class used to implement a REST response object. * [WP\_HTTP\_Response](wp_http_response) * [add\_link](wp_rest_response/add_link) β€” Adds a link to the response. * [add\_links](wp_rest_response/add_links) β€” Adds multiple links to the response. * [as\_error](wp_rest_response/as_error) β€” Retrieves a WP\_Error object from the response. * [get\_curies](wp_rest_response/get_curies) β€” Retrieves the CURIEs (compact URIs) used for relations. * [get\_links](wp_rest_response/get_links) β€” Retrieves links for the response. * [get\_matched\_handler](wp_rest_response/get_matched_handler) β€” Retrieves the handler that was used to generate the response. * [get\_matched\_route](wp_rest_response/get_matched_route) β€” Retrieves the route that was used. * [is\_error](wp_rest_response/is_error) β€” Checks if the response is an error, i.e. >= 400 response code. * [link\_header](wp_rest_response/link_header) β€” Sets a single link header. * [remove\_link](wp_rest_response/remove_link) β€” Removes a link from the response. * [set\_matched\_handler](wp_rest_response/set_matched_handler) β€” Sets the handler that was responsible for generating the response. * [set\_matched\_route](wp_rest_response/set_matched_route) β€” Sets the route (regex for path) that caused the response. File: `wp-includes/rest-api/class-wp-rest-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-response.php/) ``` class WP_REST_Response extends WP_HTTP_Response { /** * Links related to the response. * * @since 4.4.0 * @var array */ protected $links = array(); /** * The route that was to create the response. * * @since 4.4.0 * @var string */ protected $matched_route = ''; /** * The handler that was used to create the response. * * @since 4.4.0 * @var null|array */ protected $matched_handler = null; /** * Adds a link to the response. * * @internal The $rel parameter is first, as this looks nicer when sending multiple. * * @since 4.4.0 * * @link https://tools.ietf.org/html/rfc5988 * @link https://www.iana.org/assignments/link-relations/link-relations.xml * * @param string $rel Link relation. Either an IANA registered type, * or an absolute URL. * @param string $href Target URI for the link. * @param array $attributes Optional. Link parameters to send along with the URL. Default empty array. */ public function add_link( $rel, $href, $attributes = array() ) { if ( empty( $this->links[ $rel ] ) ) { $this->links[ $rel ] = array(); } if ( isset( $attributes['href'] ) ) { // Remove the href attribute, as it's used for the main URL. unset( $attributes['href'] ); } $this->links[ $rel ][] = array( 'href' => $href, 'attributes' => $attributes, ); } /** * Removes a link from the response. * * @since 4.4.0 * * @param string $rel Link relation. Either an IANA registered type, or an absolute URL. * @param string $href Optional. Only remove links for the relation matching the given href. * Default null. */ public function remove_link( $rel, $href = null ) { if ( ! isset( $this->links[ $rel ] ) ) { return; } if ( $href ) { $this->links[ $rel ] = wp_list_filter( $this->links[ $rel ], array( 'href' => $href ), 'NOT' ); } else { $this->links[ $rel ] = array(); } if ( ! $this->links[ $rel ] ) { unset( $this->links[ $rel ] ); } } /** * Adds multiple links to the response. * * Link data should be an associative array with link relation as the key. * The value can either be an associative array of link attributes * (including `href` with the URL for the response), or a list of these * associative arrays. * * @since 4.4.0 * * @param array $links Map of link relation to list of links. */ public function add_links( $links ) { foreach ( $links as $rel => $set ) { // If it's a single link, wrap with an array for consistent handling. if ( isset( $set['href'] ) ) { $set = array( $set ); } foreach ( $set as $attributes ) { $this->add_link( $rel, $attributes['href'], $attributes ); } } } /** * Retrieves links for the response. * * @since 4.4.0 * * @return array List of links. */ public function get_links() { return $this->links; } /** * Sets a single link header. * * @internal The $rel parameter is first, as this looks nicer when sending multiple. * * @since 4.4.0 * * @link https://tools.ietf.org/html/rfc5988 * @link https://www.iana.org/assignments/link-relations/link-relations.xml * * @param string $rel Link relation. Either an IANA registered type, or an absolute URL. * @param string $link Target IRI for the link. * @param array $other Optional. Other parameters to send, as an associative array. * Default empty array. */ public function link_header( $rel, $link, $other = array() ) { $header = '<' . $link . '>; rel="' . $rel . '"'; foreach ( $other as $key => $value ) { if ( 'title' === $key ) { $value = '"' . $value . '"'; } $header .= '; ' . $key . '=' . $value; } $this->header( 'Link', $header, false ); } /** * Retrieves the route that was used. * * @since 4.4.0 * * @return string The matched route. */ public function get_matched_route() { return $this->matched_route; } /** * Sets the route (regex for path) that caused the response. * * @since 4.4.0 * * @param string $route Route name. */ public function set_matched_route( $route ) { $this->matched_route = $route; } /** * Retrieves the handler that was used to generate the response. * * @since 4.4.0 * * @return null|array The handler that was used to create the response. */ public function get_matched_handler() { return $this->matched_handler; } /** * Sets the handler that was responsible for generating the response. * * @since 4.4.0 * * @param array $handler The matched handler. */ public function set_matched_handler( $handler ) { $this->matched_handler = $handler; } /** * Checks if the response is an error, i.e. >= 400 response code. * * @since 4.4.0 * * @return bool Whether the response is an error. */ public function is_error() { return $this->get_status() >= 400; } /** * Retrieves a WP_Error object from the response. * * @since 4.4.0 * * @return WP_Error|null WP_Error or null on not an errored response. */ public function as_error() { if ( ! $this->is_error() ) { return null; } $error = new WP_Error; if ( is_array( $this->get_data() ) ) { $data = $this->get_data(); $error->add( $data['code'], $data['message'], $data['data'] ); if ( ! empty( $data['additional_errors'] ) ) { foreach ( $data['additional_errors'] as $err ) { $error->add( $err['code'], $err['message'], $err['data'] ); } } } else { $error->add( $this->get_status(), '', array( 'status' => $this->get_status() ) ); } return $error; } /** * Retrieves the CURIEs (compact URIs) used for relations. * * @since 4.5.0 * * @return array Compact URIs. */ public function get_curies() { $curies = array( array( 'name' => 'wp', 'href' => 'https://api.w.org/{rel}', 'templated' => true, ), ); /** * Filters extra CURIEs available on REST API responses. * * CURIEs allow a shortened version of URI relations. This allows a more * usable form for custom relations than using the full URI. These work * similarly to how XML namespaces work. * * Registered CURIES need to specify a name and URI template. This will * automatically transform URI relations into their shortened version. * The shortened relation follows the format `{name}:{rel}`. `{rel}` in * the URI template will be replaced with the `{rel}` part of the * shortened relation. * * For example, a CURIE with name `example` and URI template * `http://w.org/{rel}` would transform a `http://w.org/term` relation * into `example:term`. * * Well-behaved clients should expand and normalize these back to their * full URI relation, however some naive clients may not resolve these * correctly, so adding new CURIEs may break backward compatibility. * * @since 4.5.0 * * @param array $additional Additional CURIEs to register with the REST API. */ $additional = apply_filters( 'rest_response_link_curies', array() ); return array_merge( $curies, $additional ); } } ``` | Uses | Description | | --- | --- | | [WP\_HTTP\_Response](wp_http_response) wp-includes/class-wp-http-response.php | Core class used to prepare HTTP responses. | | Version | Description | | --- | --- | | [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
programming_docs
wordpress class IXR_ClientMulticall {} class IXR\_ClientMulticall {} ============================= [IXR\_ClientMulticall](ixr_clientmulticall) * [\_\_construct](ixr_clientmulticall/__construct) β€” PHP5 constructor. * [addCall](ixr_clientmulticall/addcall) * [IXR\_ClientMulticall](ixr_clientmulticall/ixr_clientmulticall) β€” PHP4 constructor. * [query](ixr_clientmulticall/query) File: `wp-includes/IXR/class-IXR-clientmulticall.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-clientmulticall.php/) ``` class IXR_ClientMulticall extends IXR_Client { var $calls = array(); /** * PHP5 constructor. */ function __construct( $server, $path = false, $port = 80 ) { parent::IXR_Client($server, $path, $port); $this->useragent = 'The Incutio XML-RPC PHP Library (multicall client)'; } /** * PHP4 constructor. */ public function IXR_ClientMulticall( $server, $path = false, $port = 80 ) { self::__construct( $server, $path, $port ); } /** * @since 1.5.0 * @since 5.5.0 Formalized the existing `...$args` parameter by adding it * to the function signature. */ function addCall( ...$args ) { $methodName = array_shift($args); $struct = array( 'methodName' => $methodName, 'params' => $args ); $this->calls[] = $struct; } /** * @since 1.5.0 * @since 5.5.0 Formalized the existing `...$args` parameter by adding it * to the function signature. * * @return bool */ function query( ...$args ) { // Prepare multicall, then call the parent::query() method return parent::query('system.multicall', $this->calls); } } ``` | Uses | Description | | --- | --- | | [IXR\_Client](ixr_client) wp-includes/IXR/class-IXR-client.php | [IXR\_Client](ixr_client) | | Version | Description | | --- | --- | | [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. | wordpress class WP_Http_Encoding {} class WP\_Http\_Encoding {} =========================== Core class used to implement deflate and gzip transfer encoding support for HTTP requests. Includes RFC 1950, RFC 1951, and RFC 1952. * [accept\_encoding](wp_http_encoding/accept_encoding) β€” What encoding types to accept and their priority values. * [compatible\_gzinflate](wp_http_encoding/compatible_gzinflate) β€” Decompression of deflated string while staying compatible with the majority of servers. * [compress](wp_http_encoding/compress) β€” Compress raw string using the deflate format. * [content\_encoding](wp_http_encoding/content_encoding) β€” What encoding the content used when it was compressed to send in the headers. * [decompress](wp_http_encoding/decompress) β€” Decompression of deflated string. * [is\_available](wp_http_encoding/is_available) β€” Whether decompression and compression are supported by the PHP version. * [should\_decode](wp_http_encoding/should_decode) β€” Whether the content be decoded based on the headers. File: `wp-includes/class-wp-http-encoding.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-encoding.php/) ``` class WP_Http_Encoding { /** * Compress raw string using the deflate format. * * Supports the RFC 1951 standard. * * @since 2.8.0 * * @param string $raw String to compress. * @param int $level Optional. Compression level, 9 is highest. Default 9. * @param string $supports Optional, not used. When implemented it will choose * the right compression based on what the server supports. * @return string|false Compressed string on success, false on failure. */ public static function compress( $raw, $level = 9, $supports = null ) { return gzdeflate( $raw, $level ); } /** * 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. * * @since 2.8.0 * * @param string $compressed String to decompress. * @param int $length The optional length of the compressed data. * @return string|false Decompressed string on success, false on failure. */ 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; } /** * 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 * * @since 2.8.1 * * @link https://core.trac.wordpress.org/ticket/18273 * @link https://www.php.net/manual/en/function.gzinflate.php#70875 * @link https://www.php.net/manual/en/function.gzinflate.php#77336 * * @param string $gz_data String to decompress. * @return string|false Decompressed string on success, false on failure. */ 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; } /** * What encoding types to accept and their priority values. * * @since 2.8.0 * * @param string $url * @param array $args * @return string Types of encoding to accept. */ 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 ); } /** * What encoding the content used when it was compressed to send in the headers. * * @since 2.8.0 * * @return string Content-Encoding string to send in the header. */ public static function content_encoding() { return 'deflate'; } /** * Whether the content be decoded based on the headers. * * @since 2.8.0 * * @param array|string $headers All of the available headers. * @return bool */ 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; } /** * 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. * * @since 2.8.0 * * @return bool */ public static function is_available() { return ( function_exists( 'gzuncompress' ) || function_exists( 'gzdeflate' ) || function_exists( 'gzinflate' ) ); } } ``` | Version | Description | | --- | --- | | [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. | wordpress class Automatic_Upgrader_Skin {} class Automatic\_Upgrader\_Skin {} ================================== Upgrader Skin for Automatic WordPress Upgrades. This skin is designed to be used when no output is intended, all output is captured and stored for the caller to process and log/email/discard. * [Bulk\_Upgrader\_Skin](bulk_upgrader_skin) * [feedback](automatic_upgrader_skin/feedback) β€” Stores a message about the upgrade. * [footer](automatic_upgrader_skin/footer) β€” Retrieves the buffered content, deletes the buffer, and processes the output. * [get\_upgrade\_messages](automatic_upgrader_skin/get_upgrade_messages) β€” Retrieves the upgrade messages. * [header](automatic_upgrader_skin/header) β€” Creates a new output buffer. * [request\_filesystem\_credentials](automatic_upgrader_skin/request_filesystem_credentials) β€” Determines whether the upgrader needs FTP/SSH details in order to connect to the filesystem. File: `wp-admin/includes/class-automatic-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-automatic-upgrader-skin.php/) ``` class Automatic_Upgrader_Skin extends WP_Upgrader_Skin { protected $messages = array(); /** * Determines whether the upgrader needs FTP/SSH details in order to connect * to the filesystem. * * @since 3.7.0 * @since 4.6.0 The `$context` parameter default changed from `false` to an empty string. * * @see request_filesystem_credentials() * * @param bool|WP_Error $error Optional. Whether the current request has failed to connect, * or an error object. Default false. * @param string $context Optional. Full path to the directory that is tested * for being writable. Default empty. * @param bool $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable. Default false. * @return bool True on success, false on failure. */ public function request_filesystem_credentials( $error = false, $context = '', $allow_relaxed_file_ownership = false ) { if ( $context ) { $this->options['context'] = $context; } /* * TODO: Fix up request_filesystem_credentials(), or split it, to allow us to request a no-output version. * This will output a credentials form in event of failure. We don't want that, so just hide with a buffer. */ ob_start(); $result = parent::request_filesystem_credentials( $error, $context, $allow_relaxed_file_ownership ); ob_end_clean(); return $result; } /** * Retrieves the upgrade messages. * * @since 3.7.0 * * @return string[] Messages during an upgrade. */ public function get_upgrade_messages() { return $this->messages; } /** * Stores a message about the upgrade. * * @since 3.7.0 * @since 5.9.0 Renamed `$data` to `$feedback` for PHP 8 named parameter support. * * @param string|array|WP_Error $feedback Message data. * @param mixed ...$args Optional text replacements. */ public function feedback( $feedback, ...$args ) { if ( is_wp_error( $feedback ) ) { $string = $feedback->get_error_message(); } elseif ( is_array( $feedback ) ) { return; } else { $string = $feedback; } if ( ! empty( $this->upgrader->strings[ $string ] ) ) { $string = $this->upgrader->strings[ $string ]; } if ( strpos( $string, '%' ) !== false ) { if ( ! empty( $args ) ) { $string = vsprintf( $string, $args ); } } $string = trim( $string ); // Only allow basic HTML in the messages, as it'll be used in emails/logs rather than direct browser output. $string = wp_kses( $string, array( 'a' => array( 'href' => true, ), 'br' => true, 'em' => true, 'strong' => true, ) ); if ( empty( $string ) ) { return; } $this->messages[] = $string; } /** * Creates a new output buffer. * * @since 3.7.0 */ public function header() { ob_start(); } /** * Retrieves the buffered content, deletes the buffer, and processes the output. * * @since 3.7.0 */ public function footer() { $output = ob_get_clean(); if ( ! empty( $output ) ) { $this->feedback( $output ); } } } ``` | Uses | Description | | --- | --- | | [WP\_Upgrader\_Skin](wp_upgrader_skin) wp-admin/includes/class-wp-upgrader-skin.php | Generic Skin for the WordPress Upgrader classes. This skin is designed to be extended for specific purposes. | | Used By | Description | | --- | --- | | [WP\_Ajax\_Upgrader\_Skin](wp_ajax_upgrader_skin) wp-admin/includes/class-wp-ajax-upgrader-skin.php | Upgrader Skin for Ajax WordPress upgrades. | | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php. | | [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. | wordpress class WP_Session_Tokens {} class WP\_Session\_Tokens {} ============================ Abstract class for managing user session tokens. * [\_\_construct](wp_session_tokens/__construct) β€” Protected constructor. Use the `get\_instance()` method to get the instance. * [create](wp_session_tokens/create) β€” Generates a session token and attaches session information to it. * [destroy](wp_session_tokens/destroy) β€” Destroys the session with the given token. * [destroy\_all](wp_session_tokens/destroy_all) β€” Destroys all sessions for a user. * [destroy\_all\_for\_all\_users](wp_session_tokens/destroy_all_for_all_users) β€” Destroys all sessions for all users. * [destroy\_all\_sessions](wp_session_tokens/destroy_all_sessions) β€” Destroys all sessions for the user. * [destroy\_other\_sessions](wp_session_tokens/destroy_other_sessions) β€” Destroys all sessions for this user, except the single session with the given verifier. * [destroy\_others](wp_session_tokens/destroy_others) β€” Destroys all sessions for this user except the one with the given token (presumably the one in use). * [drop\_sessions](wp_session_tokens/drop_sessions) β€” Destroys all sessions for all users. * [get](wp_session_tokens/get) β€” Retrieves a user's session for the given token. * [get\_all](wp_session_tokens/get_all) β€” Retrieves all sessions for a user. * [get\_instance](wp_session_tokens/get_instance) β€” Retrieves a session manager instance for a user. * [get\_session](wp_session_tokens/get_session) β€” Retrieves a session based on its verifier (token hash). * [get\_sessions](wp_session_tokens/get_sessions) β€” Retrieves all sessions of the user. * [hash\_token](wp_session_tokens/hash_token) β€” Hashes the given session token for storage. * [is\_still\_valid](wp_session_tokens/is_still_valid) β€” Determines whether a session is still valid, based on its expiration timestamp. * [update](wp_session_tokens/update) β€” Updates the data for the session with the given token. * [update\_session](wp_session_tokens/update_session) β€” Updates a session based on its verifier (token hash). * [verify](wp_session_tokens/verify) β€” Validates the given session token for authenticity and validity. File: `wp-includes/class-wp-session-tokens.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-session-tokens.php/) ``` abstract class WP_Session_Tokens { /** * User ID. * * @since 4.0.0 * @var int User ID. */ protected $user_id; /** * Protected constructor. Use the `get_instance()` method to get the instance. * * @since 4.0.0 * * @param int $user_id User whose session to manage. */ protected function __construct( $user_id ) { $this->user_id = $user_id; } /** * Retrieves a session manager instance for a user. * * This method contains a {@see 'session_token_manager'} filter, allowing a plugin to swap out * the session manager for a subclass of `WP_Session_Tokens`. * * @since 4.0.0 * * @param int $user_id User whose session to manage. * @return WP_Session_Tokens The session object, which is by default an instance of * the `WP_User_Meta_Session_Tokens` class. */ final public static function get_instance( $user_id ) { /** * Filters the class name for the session token manager. * * @since 4.0.0 * * @param string $session Name of class to use as the manager. * Default 'WP_User_Meta_Session_Tokens'. */ $manager = apply_filters( 'session_token_manager', 'WP_User_Meta_Session_Tokens' ); return new $manager( $user_id ); } /** * Hashes the given session token for storage. * * @since 4.0.0 * * @param string $token Session token to hash. * @return string A hash of the session token (a verifier). */ private function hash_token( $token ) { // If ext/hash is not present, use sha1() instead. if ( function_exists( 'hash' ) ) { return hash( 'sha256', $token ); } else { return sha1( $token ); } } /** * Retrieves a user's session for the given token. * * @since 4.0.0 * * @param string $token Session token. * @return array|null The session, or null if it does not exist. */ final public function get( $token ) { $verifier = $this->hash_token( $token ); return $this->get_session( $verifier ); } /** * Validates the given session token for authenticity and validity. * * Checks that the given token is present and hasn't expired. * * @since 4.0.0 * * @param string $token Token to verify. * @return bool Whether the token is valid for the user. */ final public function verify( $token ) { $verifier = $this->hash_token( $token ); return (bool) $this->get_session( $verifier ); } /** * Generates a session token and attaches session information to it. * * A session token is a long, random string. It is used in a cookie * to link that cookie to an expiration time and to ensure the cookie * becomes invalidated when the user logs out. * * This function generates a token and stores it with the associated * expiration time (and potentially other session information via the * {@see 'attach_session_information'} filter). * * @since 4.0.0 * * @param int $expiration Session expiration timestamp. * @return string Session token. */ final public function create( $expiration ) { /** * Filters the information attached to the newly created session. * * Can be used to attach further information to a session. * * @since 4.0.0 * * @param array $session Array of extra data. * @param int $user_id User ID. */ $session = apply_filters( 'attach_session_information', array(), $this->user_id ); $session['expiration'] = $expiration; // IP address. if ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) { $session['ip'] = $_SERVER['REMOTE_ADDR']; } // User-agent. if ( ! empty( $_SERVER['HTTP_USER_AGENT'] ) ) { $session['ua'] = wp_unslash( $_SERVER['HTTP_USER_AGENT'] ); } // Timestamp. $session['login'] = time(); $token = wp_generate_password( 43, false, false ); $this->update( $token, $session ); return $token; } /** * Updates the data for the session with the given token. * * @since 4.0.0 * * @param string $token Session token to update. * @param array $session Session information. */ final public function update( $token, $session ) { $verifier = $this->hash_token( $token ); $this->update_session( $verifier, $session ); } /** * Destroys the session with the given token. * * @since 4.0.0 * * @param string $token Session token to destroy. */ final public function destroy( $token ) { $verifier = $this->hash_token( $token ); $this->update_session( $verifier, null ); } /** * Destroys all sessions for this user except the one with the given token (presumably the one in use). * * @since 4.0.0 * * @param string $token_to_keep Session token to keep. */ final public function destroy_others( $token_to_keep ) { $verifier = $this->hash_token( $token_to_keep ); $session = $this->get_session( $verifier ); if ( $session ) { $this->destroy_other_sessions( $verifier ); } else { $this->destroy_all_sessions(); } } /** * Determines whether a session is still valid, based on its expiration timestamp. * * @since 4.0.0 * * @param array $session Session to check. * @return bool Whether session is valid. */ final protected function is_still_valid( $session ) { return $session['expiration'] >= time(); } /** * Destroys all sessions for a user. * * @since 4.0.0 */ final public function destroy_all() { $this->destroy_all_sessions(); } /** * Destroys all sessions for all users. * * @since 4.0.0 */ final public static function destroy_all_for_all_users() { /** This filter is documented in wp-includes/class-wp-session-tokens.php */ $manager = apply_filters( 'session_token_manager', 'WP_User_Meta_Session_Tokens' ); call_user_func( array( $manager, 'drop_sessions' ) ); } /** * Retrieves all sessions for a user. * * @since 4.0.0 * * @return array Sessions for a user. */ final public function get_all() { return array_values( $this->get_sessions() ); } /** * Retrieves all sessions of the user. * * @since 4.0.0 * * @return array Sessions of the user. */ abstract protected function get_sessions(); /** * Retrieves a session based on its verifier (token hash). * * @since 4.0.0 * * @param string $verifier Verifier for the session to retrieve. * @return array|null The session, or null if it does not exist. */ abstract protected function get_session( $verifier ); /** * Updates a session based on its verifier (token hash). * * Omitting the second argument destroys the session. * * @since 4.0.0 * * @param string $verifier Verifier for the session to update. * @param array $session Optional. Session. Omitting this argument destroys the session. */ abstract protected function update_session( $verifier, $session = null ); /** * Destroys all sessions for this user, except the single session with the given verifier. * * @since 4.0.0 * * @param string $verifier Verifier of the session to keep. */ abstract protected function destroy_other_sessions( $verifier ); /** * Destroys all sessions for the user. * * @since 4.0.0 */ abstract protected function destroy_all_sessions(); /** * Destroys all sessions for all users. * * @since 4.0.0 */ public static function drop_sessions() {} } ``` | Used By | Description | | --- | --- | | [WP\_User\_Meta\_Session\_Tokens](wp_user_meta_session_tokens) wp-includes/class-wp-user-meta-session-tokens.php | Meta-based user sessions token manager. | | Version | Description | | --- | --- | | [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
programming_docs
wordpress class WP_Http_Streams {} class WP\_Http\_Streams {} ========================== Core class used to integrate PHP Streams as an HTTP transport. * [request](wp_http_streams/request) β€” Send a HTTP request to a URI using PHP Streams. * [test](wp_http_streams/test) β€” Determines whether this class can be used for retrieving a URL. * [verify\_ssl\_certificate](wp_http_streams/verify_ssl_certificate) β€” Verifies the received SSL certificate against its Common Names and subjectAltName fields. File: `wp-includes/class-wp-http-streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-streams.php/) ``` class WP_Http_Streams { /** * Send a HTTP request to a URI using PHP Streams. * * @see WP_Http::request() For default options descriptions. * * @since 2.7.0 * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client(). * * @param string $url The request URL. * @param string|array $args Optional. Override the defaults. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error */ 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; } /** * 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. * * @since 3.7.0 * * @param resource $stream The PHP Stream which the SSL request is being made over * @param string $host The hostname being requested * @return bool If the certificate presented in $stream is valid for $host */ 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 ); } /** * Determines whether this class can be used for retrieving a URL. * * @since 2.7.0 * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client(). * * @param array $args Optional. Array of request arguments. Default empty array. * @return bool False means this class can not be used, true means it can. */ 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 ); } } ``` | Used By | Description | | --- | --- | | [WP\_HTTP\_Fsockopen](wp_http_fsockopen) wp-includes/class-wp-http-streams.php | Deprecated HTTP Transport method which used fsockopen. | | 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 class WP_Style_Engine {} class WP\_Style\_Engine {} ========================== Class [WP\_Style\_Engine](wp_style_engine). The Style Engine aims to provide a consistent API for rendering styling for blocks across both client-side and server-side applications. This class is final and should not be extended. This class is for internal Core usage and is not supposed to be used by extenders (plugins and/or themes). This is a low-level API that may need to do breaking changes. Please, use wp\_style\_engine\_get\_styles instead. * [compile\_css](wp_style_engine/compile_css) β€” Returns compiled CSS from css\_declarations. * [compile\_stylesheet\_from\_css\_rules](wp_style_engine/compile_stylesheet_from_css_rules) β€” Returns a compiled stylesheet from stored CSS rules. * [get\_classnames](wp_style_engine/get_classnames) β€” Returns classnames, and generates classname(s) from a CSS preset property pattern, e.g., '`var:preset||`'. * [get\_css\_declarations](wp_style_engine/get_css_declarations) β€” Returns an array of CSS declarations based on valid block style values. * [get\_css\_var\_value](wp_style_engine/get_css_var_value) β€” Util: Generates a CSS var string, e.g., var(--wp--preset--color--background) from a preset string such as `var:preset|space|50`. * [get\_individual\_property\_css\_declarations](wp_style_engine/get_individual_property_css_declarations) β€” Style value parser that returns a CSS definition array comprising style properties that have keys representing individual style properties, otherwise known as longhand CSS properties. * [get\_slug\_from\_preset\_value](wp_style_engine/get_slug_from_preset_value) β€” Util: Extracts the slug in kebab case from a preset string, e.g., "heavenly-blue" from 'var:preset|color|heavenlyBlue'. * [get\_store](wp_style_engine/get_store) β€” Returns a store by store key. * [is\_valid\_style\_value](wp_style_engine/is_valid_style_value) β€” Util: Checks whether an incoming block style value is valid. * [parse\_block\_styles](wp_style_engine/parse_block_styles) β€” Returns classnames and CSS based on the values in a styles object. * [store\_css\_rule](wp_style_engine/store_css_rule) β€” Stores a CSS rule using the provided CSS selector and CSS declarations. File: `wp-includes/style-engine/class-wp-style-engine.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine.php/) ``` final class WP_Style_Engine { /** * Style definitions that contain the instructions to * parse/output valid Gutenberg styles from a block's attributes. * For every style definition, the follow properties are valid: * - classnames => (array) an array of classnames to be returned for block styles. The key is a classname or pattern. * A value of `true` means the classname should be applied always. Otherwise, a valid CSS property (string) * to match the incoming value, e.g., "color" to match var:preset|color|somePresetSlug. * - css_vars => (array) an array of key value pairs used to generate CSS var values. The key is a CSS var pattern, whose `$slug` fragment will be replaced with a preset slug. * The value should be a valid CSS property (string) to match the incoming value, e.g., "color" to match var:preset|color|somePresetSlug. * - property_keys => (array) array of keys whose values represent a valid CSS property, e.g., "margin" or "border". * - path => (array) a path that accesses the corresponding style value in the block style object. * - value_func => (string) the name of a function to generate a CSS definition array for a particular style object. The output of this function should be `array( "$property" => "$value", ... )`. * * @since 6.1.0 * @var array */ const BLOCK_STYLE_DEFINITIONS_METADATA = array( 'color' => array( 'text' => array( 'property_keys' => array( 'default' => 'color', ), 'path' => array( 'color', 'text' ), 'css_vars' => array( 'color' => '--wp--preset--color--$slug', ), 'classnames' => array( 'has-text-color' => true, 'has-$slug-color' => 'color', ), ), 'background' => array( 'property_keys' => array( 'default' => 'background-color', ), 'path' => array( 'color', 'background' ), 'classnames' => array( 'has-background' => true, 'has-$slug-background-color' => 'color', ), ), 'gradient' => array( 'property_keys' => array( 'default' => 'background', ), 'path' => array( 'color', 'gradient' ), 'classnames' => array( 'has-background' => true, 'has-$slug-gradient-background' => 'gradient', ), ), ), 'border' => array( 'color' => array( 'property_keys' => array( 'default' => 'border-color', 'individual' => 'border-%s-color', ), 'path' => array( 'border', 'color' ), 'classnames' => array( 'has-border-color' => true, 'has-$slug-border-color' => 'color', ), ), 'radius' => array( 'property_keys' => array( 'default' => 'border-radius', 'individual' => 'border-%s-radius', ), 'path' => array( 'border', 'radius' ), ), 'style' => array( 'property_keys' => array( 'default' => 'border-style', 'individual' => 'border-%s-style', ), 'path' => array( 'border', 'style' ), ), 'width' => array( 'property_keys' => array( 'default' => 'border-width', 'individual' => 'border-%s-width', ), 'path' => array( 'border', 'width' ), ), 'top' => array( 'value_func' => array( self::class, 'get_individual_property_css_declarations' ), 'path' => array( 'border', 'top' ), 'css_vars' => array( 'color' => '--wp--preset--color--$slug', ), ), 'right' => array( 'value_func' => array( self::class, 'get_individual_property_css_declarations' ), 'path' => array( 'border', 'right' ), 'css_vars' => array( 'color' => '--wp--preset--color--$slug', ), ), 'bottom' => array( 'value_func' => array( self::class, 'get_individual_property_css_declarations' ), 'path' => array( 'border', 'bottom' ), 'css_vars' => array( 'color' => '--wp--preset--color--$slug', ), ), 'left' => array( 'value_func' => array( self::class, 'get_individual_property_css_declarations' ), 'path' => array( 'border', 'left' ), 'css_vars' => array( 'color' => '--wp--preset--color--$slug', ), ), ), 'spacing' => array( 'padding' => array( 'property_keys' => array( 'default' => 'padding', 'individual' => 'padding-%s', ), 'path' => array( 'spacing', 'padding' ), 'css_vars' => array( 'spacing' => '--wp--preset--spacing--$slug', ), ), 'margin' => array( 'property_keys' => array( 'default' => 'margin', 'individual' => 'margin-%s', ), 'path' => array( 'spacing', 'margin' ), 'css_vars' => array( 'spacing' => '--wp--preset--spacing--$slug', ), ), ), 'typography' => array( 'fontSize' => array( 'property_keys' => array( 'default' => 'font-size', ), 'path' => array( 'typography', 'fontSize' ), 'classnames' => array( 'has-$slug-font-size' => 'font-size', ), ), 'fontFamily' => array( 'property_keys' => array( 'default' => 'font-family', ), 'path' => array( 'typography', 'fontFamily' ), 'classnames' => array( 'has-$slug-font-family' => 'font-family', ), ), 'fontStyle' => array( 'property_keys' => array( 'default' => 'font-style', ), 'path' => array( 'typography', 'fontStyle' ), ), 'fontWeight' => array( 'property_keys' => array( 'default' => 'font-weight', ), 'path' => array( 'typography', 'fontWeight' ), ), 'lineHeight' => array( 'property_keys' => array( 'default' => 'line-height', ), 'path' => array( 'typography', 'lineHeight' ), ), 'textDecoration' => array( 'property_keys' => array( 'default' => 'text-decoration', ), 'path' => array( 'typography', 'textDecoration' ), ), 'textTransform' => array( 'property_keys' => array( 'default' => 'text-transform', ), 'path' => array( 'typography', 'textTransform' ), ), 'letterSpacing' => array( 'property_keys' => array( 'default' => 'letter-spacing', ), 'path' => array( 'typography', 'letterSpacing' ), ), ), ); /** * Util: Extracts the slug in kebab case from a preset string, e.g., "heavenly-blue" from 'var:preset|color|heavenlyBlue'. * * @since 6.1.0 * * @param string $style_value A single CSS preset value. * @param string $property_key The CSS property that is the second element of the preset string. Used for matching. * * @return string The slug, or empty string if not found. */ protected static function get_slug_from_preset_value( $style_value, $property_key ) { if ( is_string( $style_value ) && is_string( $property_key ) && str_contains( $style_value, "var:preset|{$property_key}|" ) ) { $index_to_splice = strrpos( $style_value, '|' ) + 1; return _wp_to_kebab_case( substr( $style_value, $index_to_splice ) ); } return ''; } /** * Util: Generates a CSS var string, e.g., var(--wp--preset--color--background) from a preset string such as `var:preset|space|50`. * * @since 6.1.0 * * @param string $style_value A single css preset value. * @param string[] $css_vars An associate array of css var patterns used to generate the var string. * * @return string The css var, or an empty string if no match for slug found. */ protected static function get_css_var_value( $style_value, $css_vars ) { foreach ( $css_vars as $property_key => $css_var_pattern ) { $slug = static::get_slug_from_preset_value( $style_value, $property_key ); if ( static::is_valid_style_value( $slug ) ) { $var = strtr( $css_var_pattern, array( '$slug' => $slug ) ); return "var($var)"; } } return ''; } /** * Util: Checks whether an incoming block style value is valid. * * @since 6.1.0 * * @param string $style_value A single CSS preset value. * * @return bool */ protected static function is_valid_style_value( $style_value ) { return '0' === $style_value || ! empty( $style_value ); } /** * Stores a CSS rule using the provided CSS selector and CSS declarations. * * @since 6.1.0 * * @param string $store_name A valid store key. * @param string $css_selector When a selector is passed, the function will return a full CSS rule `$selector { ...rules }`, otherwise a concatenated string of properties and values. * @param string[] $css_declarations An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ). * * @return void. */ public static function store_css_rule( $store_name, $css_selector, $css_declarations ) { if ( empty( $store_name ) || empty( $css_selector ) || empty( $css_declarations ) ) { return; } static::get_store( $store_name )->add_rule( $css_selector )->add_declarations( $css_declarations ); } /** * Returns a store by store key. * * @since 6.1.0 * * @param string $store_name A store key. * * @return WP_Style_Engine_CSS_Rules_Store */ public static function get_store( $store_name ) { return WP_Style_Engine_CSS_Rules_Store::get_store( $store_name ); } /** * Returns classnames and CSS based on the values in a styles object. * Return values are parsed based on the instructions in BLOCK_STYLE_DEFINITIONS_METADATA. * * @since 6.1.0 * * @param array $block_styles The style object. * @param array $options { * Optional. An array of options. Default empty array. * * @type bool $convert_vars_to_classnames Whether to skip converting incoming CSS var patterns, e.g., `var:preset|<PRESET_TYPE>|<PRESET_SLUG>`, to var( --wp--preset--* ) values. Default `false`. * @type string $selector Optional. When a selector is passed, the value of `$css` in the return value will comprise a full CSS rule `$selector { ...$css_declarations }`, * otherwise, the value will be a concatenated string of CSS declarations. * } * * @return array { * @type string $classnames Classnames separated by a space. * @type string[] $declarations An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ). * } */ public static function parse_block_styles( $block_styles, $options ) { $parsed_styles = array( 'classnames' => array(), 'declarations' => array(), ); if ( empty( $block_styles ) || ! is_array( $block_styles ) ) { return $parsed_styles; } // Collect CSS and classnames. foreach ( static::BLOCK_STYLE_DEFINITIONS_METADATA as $definition_group_key => $definition_group_style ) { if ( empty( $block_styles[ $definition_group_key ] ) ) { continue; } foreach ( $definition_group_style as $style_definition ) { $style_value = _wp_array_get( $block_styles, $style_definition['path'], null ); if ( ! static::is_valid_style_value( $style_value ) ) { continue; } $parsed_styles['classnames'] = array_merge( $parsed_styles['classnames'], static::get_classnames( $style_value, $style_definition ) ); $parsed_styles['declarations'] = array_merge( $parsed_styles['declarations'], static::get_css_declarations( $style_value, $style_definition, $options ) ); } } return $parsed_styles; } /** * Returns classnames, and generates classname(s) from a CSS preset property pattern, e.g., '`var:preset|<PRESET_TYPE>|<PRESET_SLUG>`'. * * @since 6.1.0 * * @param array $style_value A single raw style value or css preset property from the $block_styles array. * @param array $style_definition A single style definition from BLOCK_STYLE_DEFINITIONS_METADATA. * * @return array|string[] An array of CSS classnames, or empty array. */ protected static function get_classnames( $style_value, $style_definition ) { if ( empty( $style_value ) ) { return array(); } $classnames = array(); if ( ! empty( $style_definition['classnames'] ) ) { foreach ( $style_definition['classnames'] as $classname => $property_key ) { if ( true === $property_key ) { $classnames[] = $classname; } $slug = static::get_slug_from_preset_value( $style_value, $property_key ); if ( $slug ) { /* * Right now we expect a classname pattern to be stored in BLOCK_STYLE_DEFINITIONS_METADATA. * One day, if there are no stored schemata, we could allow custom patterns or * generate classnames based on other properties * such as a path or a value or a prefix passed in options. */ $classnames[] = strtr( $classname, array( '$slug' => $slug ) ); } } } return $classnames; } /** * Returns an array of CSS declarations based on valid block style values. * * @since 6.1.0 * * @param array $style_value A single raw style value from $block_styles array. * @param array $style_definition A single style definition from BLOCK_STYLE_DEFINITIONS_METADATA. * @param array $options { * Optional. An array of options. Default empty array. * * @type bool $convert_vars_to_classnames Whether to skip converting incoming CSS var patterns, e.g., `var:preset|<PRESET_TYPE>|<PRESET_SLUG>`, to var( --wp--preset--* ) values. Default `false`. * } * * @return string[] An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ). */ protected static function get_css_declarations( $style_value, $style_definition, $options = array() ) { if ( isset( $style_definition['value_func'] ) && is_callable( $style_definition['value_func'] ) ) { return call_user_func( $style_definition['value_func'], $style_value, $style_definition, $options ); } $css_declarations = array(); $style_property_keys = $style_definition['property_keys']; $should_skip_css_vars = isset( $options['convert_vars_to_classnames'] ) && true === $options['convert_vars_to_classnames']; /* * Build CSS var values from `var:preset|<PRESET_TYPE>|<PRESET_SLUG>` values, e.g, `var(--wp--css--rule-slug )`. * Check if the value is a CSS preset and there's a corresponding css_var pattern in the style definition. */ if ( is_string( $style_value ) && str_contains( $style_value, 'var:' ) ) { if ( ! $should_skip_css_vars && ! empty( $style_definition['css_vars'] ) ) { $css_var = static::get_css_var_value( $style_value, $style_definition['css_vars'] ); if ( static::is_valid_style_value( $css_var ) ) { $css_declarations[ $style_property_keys['default'] ] = $css_var; } } return $css_declarations; } /* * Default rule builder. * If the input contains an array, assume box model-like properties * for styles such as margins and padding. */ if ( is_array( $style_value ) ) { // Bail out early if the `'individual'` property is not defined. if ( ! isset( $style_property_keys['individual'] ) ) { return $css_declarations; } foreach ( $style_value as $key => $value ) { if ( is_string( $value ) && str_contains( $value, 'var:' ) && ! $should_skip_css_vars && ! empty( $style_definition['css_vars'] ) ) { $value = static::get_css_var_value( $value, $style_definition['css_vars'] ); } $individual_property = sprintf( $style_property_keys['individual'], _wp_to_kebab_case( $key ) ); if ( $individual_property && static::is_valid_style_value( $value ) ) { $css_declarations[ $individual_property ] = $value; } } return $css_declarations; } $css_declarations[ $style_property_keys['default'] ] = $style_value; return $css_declarations; } /** * Style value parser that returns a CSS definition array comprising style properties * that have keys representing individual style properties, otherwise known as longhand CSS properties. * e.g., "$style_property-$individual_feature: $value;", which could represent the following: * "border-{top|right|bottom|left}-{color|width|style}: {value};" or, * "border-image-{outset|source|width|repeat|slice}: {value};" * * @since 6.1.0 * * @param array $style_value A single raw style value from $block_styles array. * @param array $individual_property_definition A single style definition from BLOCK_STYLE_DEFINITIONS_METADATA representing an individual property of a CSS property, e.g., 'top' in 'border-top'. * @param array $options { * Optional. An array of options. Default empty array. * * @type bool $convert_vars_to_classnames Whether to skip converting incoming CSS var patterns, e.g., `var:preset|<PRESET_TYPE>|<PRESET_SLUG>`, to var( --wp--preset--* ) values. Default `false`. * } * * @return string[] An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ). */ protected static function get_individual_property_css_declarations( $style_value, $individual_property_definition, $options = array() ) { if ( ! is_array( $style_value ) || empty( $style_value ) || empty( $individual_property_definition['path'] ) ) { return array(); } /* * The first item in $individual_property_definition['path'] array tells us the style property, e.g., "border". * We use this to get a corresponding CSS style definition such as "color" or "width" from the same group. * The second item in $individual_property_definition['path'] array refers to the individual property marker, e.g., "top". */ $definition_group_key = $individual_property_definition['path'][0]; $individual_property_key = $individual_property_definition['path'][1]; $should_skip_css_vars = isset( $options['convert_vars_to_classnames'] ) && true === $options['convert_vars_to_classnames']; $css_declarations = array(); foreach ( $style_value as $css_property => $value ) { if ( empty( $value ) ) { continue; } // Build a path to the individual rules in definitions. $style_definition_path = array( $definition_group_key, $css_property ); $style_definition = _wp_array_get( static::BLOCK_STYLE_DEFINITIONS_METADATA, $style_definition_path, null ); if ( $style_definition && isset( $style_definition['property_keys']['individual'] ) ) { // Set a CSS var if there is a valid preset value. if ( is_string( $value ) && str_contains( $value, 'var:' ) && ! $should_skip_css_vars && ! empty( $individual_property_definition['css_vars'] ) ) { $value = static::get_css_var_value( $value, $individual_property_definition['css_vars'] ); } $individual_css_property = sprintf( $style_definition['property_keys']['individual'], $individual_property_key ); $css_declarations[ $individual_css_property ] = $value; } } return $css_declarations; } /** * Returns compiled CSS from css_declarations. * * @since 6.1.0 * * @param string[] $css_declarations An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ). * @param string $css_selector When a selector is passed, the function will return a full CSS rule `$selector { ...rules }`, otherwise a concatenated string of properties and values. * * @return string A compiled CSS string. */ public static function compile_css( $css_declarations, $css_selector ) { if ( empty( $css_declarations ) || ! is_array( $css_declarations ) ) { return ''; } // Return an entire rule if there is a selector. if ( $css_selector ) { $css_rule = new WP_Style_Engine_CSS_Rule( $css_selector, $css_declarations ); return $css_rule->get_css(); } $css_declarations = new WP_Style_Engine_CSS_Declarations( $css_declarations ); return $css_declarations->get_declarations_string(); } /** * Returns a compiled stylesheet from stored CSS rules. * * @since 6.1.0 * * @param WP_Style_Engine_CSS_Rule[] $css_rules An array of WP_Style_Engine_CSS_Rule objects from a store or otherwise. * @param array $options { * Optional. An array of options. Default empty array. * * @type bool $optimize Whether to optimize the CSS output, e.g., combine rules. Default is `false`. * @type bool $prettify Whether to add new lines and indents to output. Default is the test of whether the global constant `SCRIPT_DEBUG` is defined. * } * * @return string A compiled stylesheet from stored CSS rules. */ public static function compile_stylesheet_from_css_rules( $css_rules, $options = array() ) { $processor = new WP_Style_Engine_Processor(); $processor->add_rules( $css_rules ); return $processor->get_css( $options ); } } ``` | Version | Description | | --- | --- | | [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
programming_docs
wordpress class WP_Feed_Cache {} class WP\_Feed\_Cache {} ======================== * [create](wp_feed_cache/create) β€” Creates a new SimplePie\_Cache object. File: `wp-includes/class-wp-feed-cache.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-feed-cache.php/) ``` class WP_Feed_Cache extends SimplePie_Cache { /** * Creates a new SimplePie_Cache object. * * @since 2.8.0 * * @param string $location URL location (scheme is used to determine handler). * @param string $filename Unique identifier for cache object. * @param string $extension 'spi' or 'spc'. * @return WP_Feed_Cache_Transient Feed cache handler object that uses transients. */ public function create( $location, $filename, $extension ) { return new WP_Feed_Cache_Transient( $location, $filename, $extension ); } } ``` wordpress class WP_Roles {} class WP\_Roles {} ================== Core class used to implement a user roles API. The role option is simple, the structure is organized by role name that store the name in value of the β€˜name’ key. The capabilities are stored as an array in the value of the β€˜capability’ key. ``` array ( 'rolename' => array ( 'name' => 'rolename', 'capabilities' => array() ) ) ``` * [\_\_call](wp_roles/__call) β€” Makes private/protected methods readable for backward compatibility. * [\_\_construct](wp_roles/__construct) β€” Constructor. * [\_init](wp_roles/_init) β€” Sets up the object properties. β€” deprecated * [add\_cap](wp_roles/add_cap) β€” Adds a capability to role. * [add\_role](wp_roles/add_role) β€” Adds a role name with capabilities to the list. * [for\_site](wp_roles/for_site) β€” Sets the site to operate on. Defaults to the current site. * [get\_names](wp_roles/get_names) β€” Retrieves a list of role names. * [get\_role](wp_roles/get_role) β€” Retrieves a role object by name. * [get\_roles\_data](wp_roles/get_roles_data) β€” Gets the available roles data. * [get\_site\_id](wp_roles/get_site_id) β€” Gets the ID of the site for which roles are currently initialized. * [init\_roles](wp_roles/init_roles) β€” Initializes all of the available roles. * [is\_role](wp_roles/is_role) β€” Determines whether a role name is currently in the list of available roles. * [reinit](wp_roles/reinit) β€” Reinitializes the object. β€” deprecated * [remove\_cap](wp_roles/remove_cap) β€” Removes a capability from role. * [remove\_role](wp_roles/remove_role) β€” Removes a role by name. File: `wp-includes/class-wp-roles.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-roles.php/) ``` class WP_Roles { /** * List of roles and capabilities. * * @since 2.0.0 * @var array[] */ public $roles; /** * List of the role objects. * * @since 2.0.0 * @var WP_Role[] */ public $role_objects = array(); /** * List of role names. * * @since 2.0.0 * @var string[] */ public $role_names = array(); /** * Option name for storing role list. * * @since 2.0.0 * @var string */ public $role_key; /** * Whether to use the database for retrieval and storage. * * @since 2.1.0 * @var bool */ public $use_db = true; /** * The site ID the roles are initialized for. * * @since 4.9.0 * @var int */ protected $site_id = 0; /** * Constructor. * * @since 2.0.0 * @since 4.9.0 The `$site_id` argument was added. * * @global array $wp_user_roles Used to set the 'roles' property value. * * @param int $site_id Site ID to initialize roles for. Default is the current site. */ public function __construct( $site_id = null ) { global $wp_user_roles; $this->use_db = empty( $wp_user_roles ); $this->for_site( $site_id ); } /** * Makes private/protected methods readable for backward compatibility. * * @since 4.0.0 * * @param string $name Method to call. * @param array $arguments Arguments to pass when calling. * @return mixed|false Return value of the callback, false otherwise. */ public function __call( $name, $arguments ) { if ( '_init' === $name ) { return $this->_init( ...$arguments ); } return false; } /** * Sets up the object properties. * * The role key is set to the current prefix for the $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. * * @since 2.1.0 * @deprecated 4.9.0 Use WP_Roles::for_site() */ protected function _init() { _deprecated_function( __METHOD__, '4.9.0', 'WP_Roles::for_site()' ); $this->for_site(); } /** * Reinitializes the object. * * Recreates the role objects. This is typically called only by switch_to_blog() * after switching wpdb to a new site ID. * * @since 3.5.0 * @deprecated 4.7.0 Use WP_Roles::for_site() */ public function reinit() { _deprecated_function( __METHOD__, '4.7.0', 'WP_Roles::for_site()' ); $this->for_site(); } /** * 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. * * @since 2.0.0 * * @param string $role Role name. * @param string $display_name Role display name. * @param bool[] $capabilities Optional. List of capabilities keyed by the capability name, * e.g. `array( 'edit_posts' => true, 'delete_posts' => false )`. * Default empty array. * @return WP_Role|void WP_Role object, if the role is added. */ 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 ]; } /** * Removes a role by name. * * @since 2.0.0 * * @param string $role Role name. */ 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' ); } } /** * Adds a capability to role. * * @since 2.0.0 * * @param string $role Role name. * @param string $cap Capability name. * @param bool $grant Optional. Whether role is capable of performing capability. * Default true. */ 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 ); } } /** * Removes a capability from role. * * @since 2.0.0 * * @param string $role Role name. * @param string $cap Capability name. */ 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 ); } } /** * Retrieves a role object by name. * * @since 2.0.0 * * @param string $role Role name. * @return WP_Role|null WP_Role object if found, null if the role does not exist. */ public function get_role( $role ) { if ( isset( $this->role_objects[ $role ] ) ) { return $this->role_objects[ $role ]; } else { return null; } } /** * Retrieves a list of role names. * * @since 2.0.0 * * @return string[] List of role names. */ public function get_names() { return $this->role_names; } /** * Determines whether a role name is currently in the list of available roles. * * @since 2.0.0 * * @param string $role Role name to look up. * @return bool */ public function is_role( $role ) { return isset( $this->role_names[ $role ] ); } /** * Initializes all of the available roles. * * @since 4.9.0 */ 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 ); } /** * Sets the site to operate on. Defaults to the current site. * * @since 4.9.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $site_id Site ID to initialize roles for. Default is the current site. */ 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(); } /** * Gets the ID of the site for which roles are currently initialized. * * @since 4.9.0 * * @return int Site ID. */ public function get_site_id() { return $this->site_id; } /** * Gets the available roles data. * * @since 4.9.0 * * @global array $wp_user_roles Used to set the 'roles' property value. * * @return array Roles array. */ 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() ); } } ``` | Version | Description | | --- | --- | | [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. | wordpress class Requests_Cookie_Jar {} class Requests\_Cookie\_Jar {} ============================== Cookie holder object * [\_\_construct](requests_cookie_jar/__construct) β€” Create a new jar * [before\_redirect\_check](requests_cookie_jar/before_redirect_check) β€” Parse all cookies from a response and attach them to the response * [before\_request](requests_cookie_jar/before_request) β€” Add Cookie header to a request if we have any * [getIterator](requests_cookie_jar/getiterator) β€” Get an iterator for the data * [normalize\_cookie](requests_cookie_jar/normalize_cookie) β€” Normalise cookie data into a Requests\_Cookie * [normalizeCookie](requests_cookie_jar/normalizecookie) β€” Normalise cookie data into a Requests\_Cookie β€” deprecated * [offsetExists](requests_cookie_jar/offsetexists) β€” Check if the given item exists * [offsetGet](requests_cookie_jar/offsetget) β€” Get the value for the item * [offsetSet](requests_cookie_jar/offsetset) β€” Set the given item * [offsetUnset](requests_cookie_jar/offsetunset) β€” Unset the given header * [register](requests_cookie_jar/register) β€” Register the cookie handler with the request's hooking system File: `wp-includes/Requests/Cookie/Jar.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/cookie/jar.php/) ``` class Requests_Cookie_Jar implements ArrayAccess, IteratorAggregate { /** * Actual item data * * @var array */ protected $cookies = array(); /** * Create a new jar * * @param array $cookies Existing cookie values */ public function __construct($cookies = array()) { $this->cookies = $cookies; } /** * Normalise cookie data into a Requests_Cookie * * @param string|Requests_Cookie $cookie * @return Requests_Cookie */ public function normalize_cookie($cookie, $key = null) { if ($cookie instanceof Requests_Cookie) { return $cookie; } return Requests_Cookie::parse($cookie, $key); } /** * Normalise cookie data into a Requests_Cookie * * @codeCoverageIgnore * @deprecated Use {@see Requests_Cookie_Jar::normalize_cookie} * @return Requests_Cookie */ public function normalizeCookie($cookie, $key = null) { return $this->normalize_cookie($cookie, $key); } /** * Check if the given item exists * * @param string $key Item key * @return boolean Does the item exist? */ public function offsetExists($key) { return isset($this->cookies[$key]); } /** * Get the value for the item * * @param string $key Item key * @return string|null Item value (null if offsetExists is false) */ public function offsetGet($key) { if (!isset($this->cookies[$key])) { return null; } return $this->cookies[$key]; } /** * Set the given item * * @throws Requests_Exception On attempting to use dictionary as list (`invalidset`) * * @param string $key Item name * @param string $value Item value */ public function offsetSet($key, $value) { if ($key === null) { throw new Requests_Exception('Object is a dictionary, not a list', 'invalidset'); } $this->cookies[$key] = $value; } /** * Unset the given header * * @param string $key */ public function offsetUnset($key) { unset($this->cookies[$key]); } /** * Get an iterator for the data * * @return ArrayIterator */ public function getIterator() { return new ArrayIterator($this->cookies); } /** * Register the cookie handler with the request's hooking system * * @param Requests_Hooker $hooks Hooking system */ public function register(Requests_Hooker $hooks) { $hooks->register('requests.before_request', array($this, 'before_request')); $hooks->register('requests.before_redirect_check', array($this, 'before_redirect_check')); } /** * Add Cookie header to a request if we have any * * As per RFC 6265, cookies are separated by '; ' * * @param string $url * @param array $headers * @param array $data * @param string $type * @param array $options */ public function before_request($url, &$headers, &$data, &$type, &$options) { if (!$url instanceof Requests_IRI) { $url = new Requests_IRI($url); } if (!empty($this->cookies)) { $cookies = array(); foreach ($this->cookies as $key => $cookie) { $cookie = $this->normalize_cookie($cookie, $key); // Skip expired cookies if ($cookie->is_expired()) { continue; } if ($cookie->domain_matches($url->host)) { $cookies[] = $cookie->format_for_header(); } } $headers['Cookie'] = implode('; ', $cookies); } } /** * Parse all cookies from a response and attach them to the response * * @var Requests_Response $response */ public function before_redirect_check(Requests_Response $return) { $url = $return->url; if (!$url instanceof Requests_IRI) { $url = new Requests_IRI($url); } $cookies = Requests_Cookie::parse_from_headers($return->headers, $url); $this->cookies = array_merge($this->cookies, $cookies); $return->cookies = $this; } } ``` wordpress class WP_Block {} class WP\_Block {} ================== Class representing a parsed instance of a block. * [\_\_construct](wp_block/__construct) β€” Constructor. * [\_\_get](wp_block/__get) β€” Returns a value from an inaccessible property. * [render](wp_block/render) β€” Generates the render output for the block. File: `wp-includes/class-wp-block.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block.php/) ``` class WP_Block { /** * Original parsed array representation of block. * * @since 5.5.0 * @var array */ public $parsed_block; /** * Name of block. * * @example "core/paragraph" * * @since 5.5.0 * @var string */ public $name; /** * Block type associated with the instance. * * @since 5.5.0 * @var WP_Block_Type */ public $block_type; /** * Block context values. * * @since 5.5.0 * @var array */ public $context = array(); /** * All available context of the current hierarchy. * * @since 5.5.0 * @var array * @access protected */ protected $available_context; /** * Block type registry. * * @since 5.9.0 * @var WP_Block_Type_Registry * @access protected */ protected $registry; /** * List of inner blocks (of this same class) * * @since 5.5.0 * @var WP_Block_List */ public $inner_blocks = array(); /** * Resultant HTML from inside block comment delimiters after removing inner * blocks. * * @example "...Just <!-- wp:test /--> testing..." -> "Just testing..." * * @since 5.5.0 * @var string */ public $inner_html = ''; /** * List of string fragments and null markers where inner blocks were found * * @example array( * 'inner_html' => 'BeforeInnerAfter', * 'inner_blocks' => array( block, block ), * 'inner_content' => array( 'Before', null, 'Inner', null, 'After' ), * ) * * @since 5.5.0 * @var array */ public $inner_content = array(); /** * Constructor. * * Populates object properties from the provided block instance argument. * * The given array of context values will not necessarily be available on * the instance itself, but is treated as the full set of values provided by * the block's ancestry. This is assigned to the private `available_context` * property. Only values which are configured to consumed by the block via * its registered type will be assigned to the block's `context` property. * * @since 5.5.0 * * @param array $block Array of parsed block properties. * @param array $available_context Optional array of ancestry context values. * @param WP_Block_Type_Registry $registry Optional block type registry. */ public function __construct( $block, $available_context = array(), $registry = null ) { $this->parsed_block = $block; $this->name = $block['blockName']; if ( is_null( $registry ) ) { $registry = WP_Block_Type_Registry::get_instance(); } $this->registry = $registry; $this->block_type = $registry->get_registered( $this->name ); $this->available_context = $available_context; if ( ! empty( $this->block_type->uses_context ) ) { foreach ( $this->block_type->uses_context as $context_name ) { if ( array_key_exists( $context_name, $this->available_context ) ) { $this->context[ $context_name ] = $this->available_context[ $context_name ]; } } } if ( ! empty( $block['innerBlocks'] ) ) { $child_context = $this->available_context; if ( ! empty( $this->block_type->provides_context ) ) { foreach ( $this->block_type->provides_context as $context_name => $attribute_name ) { if ( array_key_exists( $attribute_name, $this->attributes ) ) { $child_context[ $context_name ] = $this->attributes[ $attribute_name ]; } } } $this->inner_blocks = new WP_Block_List( $block['innerBlocks'], $child_context, $registry ); } if ( ! empty( $block['innerHTML'] ) ) { $this->inner_html = $block['innerHTML']; } if ( ! empty( $block['innerContent'] ) ) { $this->inner_content = $block['innerContent']; } } /** * Returns a value from an inaccessible property. * * This is used to lazily initialize the `attributes` property of a block, * such that it is only prepared with default attributes at the time that * the property is accessed. For all other inaccessible properties, a `null` * value is returned. * * @since 5.5.0 * * @param string $name Property name. * @return array|null Prepared attributes, or null. */ public function __get( $name ) { if ( 'attributes' === $name ) { $this->attributes = isset( $this->parsed_block['attrs'] ) ? $this->parsed_block['attrs'] : array(); if ( ! is_null( $this->block_type ) ) { $this->attributes = $this->block_type->prepare_attributes_for_render( $this->attributes ); } return $this->attributes; } return null; } /** * Generates the render output for the block. * * @since 5.5.0 * * @param array $options { * Optional options object. * * @type bool $dynamic Defaults to 'true'. Optionally set to false to avoid using the block's render_callback. * } * @return string Rendered block output. */ public function render( $options = array() ) { global $post; $options = wp_parse_args( $options, array( 'dynamic' => true, ) ); $is_dynamic = $options['dynamic'] && $this->name && null !== $this->block_type && $this->block_type->is_dynamic(); $block_content = ''; if ( ! $options['dynamic'] || empty( $this->block_type->skip_inner_blocks ) ) { $index = 0; foreach ( $this->inner_content as $chunk ) { if ( is_string( $chunk ) ) { $block_content .= $chunk; } else { $inner_block = $this->inner_blocks[ $index ]; $parent_block = $this; /** This filter is documented in wp-includes/blocks.php */ $pre_render = apply_filters( 'pre_render_block', null, $inner_block->parsed_block, $parent_block ); if ( ! is_null( $pre_render ) ) { $block_content .= $pre_render; } else { $source_block = $inner_block->parsed_block; /** This filter is documented in wp-includes/blocks.php */ $inner_block->parsed_block = apply_filters( 'render_block_data', $inner_block->parsed_block, $source_block, $parent_block ); /** This filter is documented in wp-includes/blocks.php */ $inner_block->context = apply_filters( 'render_block_context', $inner_block->context, $inner_block->parsed_block, $parent_block ); $block_content .= $inner_block->render(); } $index++; } } } if ( $is_dynamic ) { $global_post = $post; $parent = WP_Block_Supports::$block_to_render; WP_Block_Supports::$block_to_render = $this->parsed_block; $block_content = (string) call_user_func( $this->block_type->render_callback, $this->attributes, $block_content, $this ); WP_Block_Supports::$block_to_render = $parent; $post = $global_post; } if ( ( ! empty( $this->block_type->script_handles ) ) ) { foreach ( $this->block_type->script_handles as $script_handle ) { wp_enqueue_script( $script_handle ); } } if ( ! empty( $this->block_type->view_script_handles ) ) { foreach ( $this->block_type->view_script_handles as $view_script_handle ) { wp_enqueue_script( $view_script_handle ); } } if ( ( ! empty( $this->block_type->style_handles ) ) ) { foreach ( $this->block_type->style_handles as $style_handle ) { wp_enqueue_style( $style_handle ); } } /** * Filters the content of a single block. * * @since 5.0.0 * @since 5.9.0 The `$instance` parameter was added. * * @param string $block_content The block content. * @param array $block The full block, including name and attributes. * @param WP_Block $instance The block instance. */ $block_content = apply_filters( 'render_block', $block_content, $this->parsed_block, $this ); /** * Filters the content of a single block. * * The dynamic portion of the hook name, `$name`, refers to * the block name, e.g. "core/paragraph". * * @since 5.7.0 * @since 5.9.0 The `$instance` parameter was added. * * @param string $block_content The block content. * @param array $block The full block, including name and attributes. * @param WP_Block $instance The block instance. */ $block_content = apply_filters( "render_block_{$this->name}", $block_content, $this->parsed_block, $this ); return $block_content; } } ``` | Version | Description | | --- | --- | | [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
programming_docs
wordpress class WP_Customize_Background_Image_Control {} class WP\_Customize\_Background\_Image\_Control {} ================================================== Customize Background Image Control class. * [WP\_Customize\_Image\_Control](wp_customize_image_control) * [\_\_construct](wp_customize_background_image_control/__construct) β€” Constructor. * [enqueue](wp_customize_background_image_control/enqueue) β€” Enqueue control related scripts/styles. File: `wp-includes/customize/class-wp-customize-background-image-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-background-image-control.php/) ``` class WP_Customize_Background_Image_Control extends WP_Customize_Image_Control { /** * Customize control type. * * @since 4.1.0 * @var string */ public $type = 'background'; /** * Constructor. * * @since 3.4.0 * @uses WP_Customize_Image_Control::__construct() * * @param WP_Customize_Manager $manager Customizer bootstrap instance. */ public function __construct( $manager ) { parent::__construct( $manager, 'background_image', array( 'label' => __( 'Background Image' ), 'section' => 'background_image', ) ); } /** * Enqueue control related scripts/styles. * * @since 4.1.0 */ public function enqueue() { parent::enqueue(); $custom_background = get_theme_support( 'custom-background' ); wp_localize_script( 'customize-controls', '_wpCustomizeBackground', array( 'defaults' => ! empty( $custom_background[0] ) ? $custom_background[0] : array(), 'nonces' => array( 'add' => wp_create_nonce( 'background-add' ), ), ) ); } } ``` | Uses | Description | | --- | --- | | [WP\_Customize\_Image\_Control](wp_customize_image_control) wp-includes/customize/class-wp-customize-image-control.php | Customize Image Control class. | | Version | Description | | --- | --- | | [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. | wordpress class WP_Customize_Selective_Refresh {} class WP\_Customize\_Selective\_Refresh {} ========================================== Core Customizer class for implementing selective refresh. * [\_\_construct](wp_customize_selective_refresh/__construct) β€” Plugin bootstrap for Partial Refresh functionality. * [add\_dynamic\_partials](wp_customize_selective_refresh/add_dynamic_partials) β€” Registers dynamically-created partials. * [add\_partial](wp_customize_selective_refresh/add_partial) β€” Adds a partial. * [enqueue\_preview\_scripts](wp_customize_selective_refresh/enqueue_preview_scripts) β€” Enqueues preview scripts. * [export\_preview\_data](wp_customize_selective_refresh/export_preview_data) β€” Exports data in preview after it has finished rendering so that partials can be added at runtime. * [get\_partial](wp_customize_selective_refresh/get_partial) β€” Retrieves a partial. * [handle\_error](wp_customize_selective_refresh/handle_error) β€” Handles PHP errors triggered during rendering the partials. * [handle\_render\_partials\_request](wp_customize_selective_refresh/handle_render_partials_request) β€” Handles the Ajax request to return the rendered partials for the requested placements. * [init\_preview](wp_customize_selective_refresh/init_preview) β€” Initializes the Customizer preview. * [is\_render\_partials\_request](wp_customize_selective_refresh/is_render_partials_request) β€” Checks whether the request is for rendering partials. * [partials](wp_customize_selective_refresh/partials) β€” Retrieves the registered partials. * [remove\_partial](wp_customize_selective_refresh/remove_partial) β€” Removes a partial. File: `wp-includes/customize/class-wp-customize-selective-refresh.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-selective-refresh.php/) ``` final class WP_Customize_Selective_Refresh { /** * Query var used in requests to render partials. * * @since 4.5.0 */ const RENDER_QUERY_VAR = 'wp_customize_render_partials'; /** * Customize manager. * * @since 4.5.0 * @var WP_Customize_Manager */ public $manager; /** * Registered instances of WP_Customize_Partial. * * @since 4.5.0 * @var WP_Customize_Partial[] */ protected $partials = array(); /** * Log of errors triggered when partials are rendered. * * @since 4.5.0 * @var array */ protected $triggered_errors = array(); /** * Keep track of the current partial being rendered. * * @since 4.5.0 * @var string|null */ protected $current_partial_id; /** * Plugin bootstrap for Partial Refresh functionality. * * @since 4.5.0 * * @param WP_Customize_Manager $manager Customizer bootstrap instance. */ public function __construct( WP_Customize_Manager $manager ) { $this->manager = $manager; require_once ABSPATH . WPINC . '/customize/class-wp-customize-partial.php'; add_action( 'customize_preview_init', array( $this, 'init_preview' ) ); } /** * Retrieves the registered partials. * * @since 4.5.0 * * @return array Partials. */ public function partials() { return $this->partials; } /** * Adds a partial. * * @since 4.5.0 * * @see WP_Customize_Partial::__construct() * * @param WP_Customize_Partial|string $id Customize Partial object, or Partial ID. * @param array $args Optional. Array of properties for the new Partials object. * See WP_Customize_Partial::__construct() for information * on accepted arguments. Default empty array. * @return WP_Customize_Partial The instance of the partial that was added. */ public function add_partial( $id, $args = array() ) { if ( $id instanceof WP_Customize_Partial ) { $partial = $id; } else { $class = 'WP_Customize_Partial'; /** This filter is documented in wp-includes/customize/class-wp-customize-selective-refresh.php */ $args = apply_filters( 'customize_dynamic_partial_args', $args, $id ); /** This filter is documented in wp-includes/customize/class-wp-customize-selective-refresh.php */ $class = apply_filters( 'customize_dynamic_partial_class', $class, $id, $args ); $partial = new $class( $this, $id, $args ); } $this->partials[ $partial->id ] = $partial; return $partial; } /** * Retrieves a partial. * * @since 4.5.0 * * @param string $id Customize Partial ID. * @return WP_Customize_Partial|null The partial, if set. Otherwise null. */ public function get_partial( $id ) { if ( isset( $this->partials[ $id ] ) ) { return $this->partials[ $id ]; } else { return null; } } /** * Removes a partial. * * @since 4.5.0 * * @param string $id Customize Partial ID. */ public function remove_partial( $id ) { unset( $this->partials[ $id ] ); } /** * Initializes the Customizer preview. * * @since 4.5.0 */ public function init_preview() { add_action( 'template_redirect', array( $this, 'handle_render_partials_request' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_preview_scripts' ) ); } /** * Enqueues preview scripts. * * @since 4.5.0 */ public function enqueue_preview_scripts() { wp_enqueue_script( 'customize-selective-refresh' ); add_action( 'wp_footer', array( $this, 'export_preview_data' ), 1000 ); } /** * Exports data in preview after it has finished rendering so that partials can be added at runtime. * * @since 4.5.0 */ public function export_preview_data() { $partials = array(); foreach ( $this->partials() as $partial ) { if ( $partial->check_capabilities() ) { $partials[ $partial->id ] = $partial->json(); } } $switched_locale = switch_to_locale( get_user_locale() ); $l10n = array( 'shiftClickToEdit' => __( 'Shift-click to edit this element.' ), 'clickEditMenu' => __( 'Click to edit this menu.' ), 'clickEditWidget' => __( 'Click to edit this widget.' ), 'clickEditTitle' => __( 'Click to edit the site title.' ), 'clickEditMisc' => __( 'Click to edit this element.' ), /* translators: %s: document.write() */ 'badDocumentWrite' => sprintf( __( '%s is forbidden' ), 'document.write()' ), ); if ( $switched_locale ) { restore_previous_locale(); } $exports = array( 'partials' => $partials, 'renderQueryVar' => self::RENDER_QUERY_VAR, 'l10n' => $l10n, ); // Export data to JS. printf( '<script>var _customizePartialRefreshExports = %s;</script>', wp_json_encode( $exports ) ); } /** * Registers dynamically-created partials. * * @since 4.5.0 * * @see WP_Customize_Manager::add_dynamic_settings() * * @param string[] $partial_ids Array of the partial IDs to add. * @return WP_Customize_Partial[] Array of added WP_Customize_Partial instances. */ public function add_dynamic_partials( $partial_ids ) { $new_partials = array(); foreach ( $partial_ids as $partial_id ) { // Skip partials already created. $partial = $this->get_partial( $partial_id ); if ( $partial ) { continue; } $partial_args = false; $partial_class = 'WP_Customize_Partial'; /** * Filters a dynamic partial's constructor arguments. * * For a dynamic partial to be registered, this filter must be employed * to override the default false value with an array of args to pass to * the WP_Customize_Partial constructor. * * @since 4.5.0 * * @param false|array $partial_args The arguments to the WP_Customize_Partial constructor. * @param string $partial_id ID for dynamic partial. */ $partial_args = apply_filters( 'customize_dynamic_partial_args', $partial_args, $partial_id ); if ( false === $partial_args ) { continue; } /** * Filters the class used to construct partials. * * Allow non-statically created partials to be constructed with custom WP_Customize_Partial subclass. * * @since 4.5.0 * * @param string $partial_class WP_Customize_Partial or a subclass. * @param string $partial_id ID for dynamic partial. * @param array $partial_args The arguments to the WP_Customize_Partial constructor. */ $partial_class = apply_filters( 'customize_dynamic_partial_class', $partial_class, $partial_id, $partial_args ); $partial = new $partial_class( $this, $partial_id, $partial_args ); $this->add_partial( $partial ); $new_partials[] = $partial; } return $new_partials; } /** * Checks whether the request is for rendering partials. * * Note that this will not consider whether the request is authorized or valid, * just that essentially the route is a match. * * @since 4.5.0 * * @return bool Whether the request is for rendering partials. */ public function is_render_partials_request() { return ! empty( $_POST[ self::RENDER_QUERY_VAR ] ); } /** * Handles PHP errors triggered during rendering the partials. * * These errors will be relayed back to the client in the Ajax response. * * @since 4.5.0 * * @param int $errno Error number. * @param string $errstr Error string. * @param string $errfile Error file. * @param int $errline Error line. * @return true Always true. */ public function handle_error( $errno, $errstr, $errfile = null, $errline = null ) { $this->triggered_errors[] = array( 'partial' => $this->current_partial_id, 'error_number' => $errno, 'error_string' => $errstr, 'error_file' => $errfile, 'error_line' => $errline, ); return true; } /** * Handles the Ajax request to return the rendered partials for the requested placements. * * @since 4.5.0 */ public function handle_render_partials_request() { if ( ! $this->is_render_partials_request() ) { return; } /* * Note that is_customize_preview() returning true will entail that the * user passed the 'customize' capability check and the nonce check, since * WP_Customize_Manager::setup_theme() is where the previewing flag is set. */ if ( ! is_customize_preview() ) { wp_send_json_error( 'expected_customize_preview', 403 ); } elseif ( ! isset( $_POST['partials'] ) ) { wp_send_json_error( 'missing_partials', 400 ); } // Ensure that doing selective refresh on 404 template doesn't result in fallback rendering behavior (full refreshes). status_header( 200 ); $partials = json_decode( wp_unslash( $_POST['partials'] ), true ); if ( ! is_array( $partials ) ) { wp_send_json_error( 'malformed_partials' ); } $this->add_dynamic_partials( array_keys( $partials ) ); /** * Fires immediately before partials are rendered. * * Plugins may do things like call wp_enqueue_scripts() and gather a list of the scripts * and styles which may get enqueued in the response. * * @since 4.5.0 * * @param WP_Customize_Selective_Refresh $refresh Selective refresh component. * @param array $partials Placements' context data for the partials rendered in the request. * The array is keyed by partial ID, with each item being an array of * the placements' context data. */ do_action( 'customize_render_partials_before', $this, $partials ); set_error_handler( array( $this, 'handle_error' ), error_reporting() ); $contents = array(); foreach ( $partials as $partial_id => $container_contexts ) { $this->current_partial_id = $partial_id; if ( ! is_array( $container_contexts ) ) { wp_send_json_error( 'malformed_container_contexts' ); } $partial = $this->get_partial( $partial_id ); if ( ! $partial || ! $partial->check_capabilities() ) { $contents[ $partial_id ] = null; continue; } $contents[ $partial_id ] = array(); // @todo The array should include not only the contents, but also whether the container is included? if ( empty( $container_contexts ) ) { // Since there are no container contexts, render just once. $contents[ $partial_id ][] = $partial->render( null ); } else { foreach ( $container_contexts as $container_context ) { $contents[ $partial_id ][] = $partial->render( $container_context ); } } } $this->current_partial_id = null; restore_error_handler(); /** * Fires immediately after partials are rendered. * * Plugins may do things like call wp_footer() to scrape scripts output and return them * via the {@see 'customize_render_partials_response'} filter. * * @since 4.5.0 * * @param WP_Customize_Selective_Refresh $refresh Selective refresh component. * @param array $partials Placements' context data for the partials rendered in the request. * The array is keyed by partial ID, with each item being an array of * the placements' context data. */ do_action( 'customize_render_partials_after', $this, $partials ); $response = array( 'contents' => $contents, ); if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) { $response['errors'] = $this->triggered_errors; } $setting_validities = $this->manager->validate_setting_values( $this->manager->unsanitized_post_values() ); $exported_setting_validities = array_map( array( $this->manager, 'prepare_setting_validity_for_js' ), $setting_validities ); $response['setting_validities'] = $exported_setting_validities; /** * Filters the response from rendering the partials. * * Plugins may use this filter to inject `$scripts` and `$styles`, which are dependencies * for the partials being rendered. The response data will be available to the client via * the `render-partials-response` JS event, so the client can then inject the scripts and * styles into the DOM if they have not already been enqueued there. * * If plugins do this, they'll need to take care for any scripts that do `document.write()` * and make sure that these are not injected, or else to override the function to no-op, * or else the page will be destroyed. * * Plugins should be aware that `$scripts` and `$styles` may eventually be included by * default in the response. * * @since 4.5.0 * * @param array $response { * Response. * * @type array $contents Associative array mapping a partial ID its corresponding array of contents * for the containers requested. * @type array $errors List of errors triggered during rendering of partials, if `WP_DEBUG_DISPLAY` * is enabled. * } * @param WP_Customize_Selective_Refresh $refresh Selective refresh component. * @param array $partials Placements' context data for the partials rendered in the request. * The array is keyed by partial ID, with each item being an array of * the placements' context data. */ $response = apply_filters( 'customize_render_partials_response', $response, $this, $partials ); wp_send_json_success( $response ); } } ``` | Version | Description | | --- | --- | | [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. | wordpress class IXR_Server {} class IXR\_Server {} ==================== [IXR\_Server](ixr_server) * [\_\_construct](ixr_server/__construct) β€” PHP5 constructor. * [call](ixr_server/call) * [error](ixr_server/error) * [getCapabilities](ixr_server/getcapabilities) * [hasMethod](ixr_server/hasmethod) * [IXR\_Server](ixr_server/ixr_server) β€” PHP4 constructor. * [listMethods](ixr_server/listmethods) * [multiCall](ixr_server/multicall) * [output](ixr_server/output) * [serve](ixr_server/serve) * [setCallbacks](ixr_server/setcallbacks) * [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/) ``` class IXR_Server { var $data; var $callbacks = array(); var $message; var $capabilities; /** * PHP5 constructor. */ function __construct( $callbacks = false, $data = false, $wait = false ) { $this->setCapabilities(); if ($callbacks) { $this->callbacks = $callbacks; } $this->setCallbacks(); if (!$wait) { $this->serve($data); } } /** * PHP4 constructor. */ public function IXR_Server( $callbacks = false, $data = false, $wait = false ) { self::__construct( $callbacks, $data, $wait ); } 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); } 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; } 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()); } 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; } function hasMethod($method) { return in_array($method, array_keys($this->callbacks)); } 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 ), ); } function getCapabilities($args) { return $this->capabilities; } function setCallbacks() { $this->callbacks['system.getCapabilities'] = 'this:getCapabilities'; $this->callbacks['system.listMethods'] = 'this:listMethods'; $this->callbacks['system.multicall'] = 'this:multiCall'; } 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)); } 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; } } ``` | Used By | Description | | --- | --- | | [IXR\_IntrospectionServer](ixr_introspectionserver) wp-includes/IXR/class-IXR-introspectionserver.php | [IXR\_IntrospectionServer](ixr_introspectionserver) | | <wp_xmlrpc_server> wp-includes/class-wp-xmlrpc-server.php | WordPress XMLRPC server implementation. | | Version | Description | | --- | --- | | [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
programming_docs
wordpress class WP_Locale_Switcher {} class WP\_Locale\_Switcher {} ============================= Core class used for switching locales. * [\_\_construct](wp_locale_switcher/__construct) β€” Constructor. * [change\_locale](wp_locale_switcher/change_locale) β€” Changes the site's locale to the given one. * [filter\_locale](wp_locale_switcher/filter_locale) β€” Filters the locale of the WordPress installation. * [init](wp_locale_switcher/init) β€” Initializes the locale switcher. * [is\_switched](wp_locale_switcher/is_switched) β€” Whether switch\_to\_locale() is in effect. * [load\_translations](wp_locale_switcher/load_translations) β€” Load translations for a given locale. * [restore\_current\_locale](wp_locale_switcher/restore_current_locale) β€” Restores the translations according to the original locale. * [restore\_previous\_locale](wp_locale_switcher/restore_previous_locale) β€” Restores the translations according to the previous locale. * [switch\_to\_locale](wp_locale_switcher/switch_to_locale) β€” Switches the translations according to the given locale. File: `wp-includes/class-wp-locale-switcher.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-locale-switcher.php/) ``` class WP_Locale_Switcher { /** * Locale stack. * * @since 4.7.0 * @var string[] */ private $locales = array(); /** * Original locale. * * @since 4.7.0 * @var string */ private $original_locale; /** * Holds all available languages. * * @since 4.7.0 * @var string[] An array of language codes (file names without the .mo extension). */ private $available_languages = array(); /** * Constructor. * * Stores the original locale as well as a list of all available languages. * * @since 4.7.0 */ public function __construct() { $this->original_locale = determine_locale(); $this->available_languages = array_merge( array( 'en_US' ), get_available_languages() ); } /** * Initializes the locale switcher. * * Hooks into the {@see 'locale'} filter to change the locale on the fly. * * @since 4.7.0 */ public function init() { add_filter( 'locale', array( $this, 'filter_locale' ) ); } /** * Switches the translations according to the given locale. * * @since 4.7.0 * * @param string $locale The locale to switch to. * @return bool True on success, false on failure. */ 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; } /** * Restores the translations according to the previous locale. * * @since 4.7.0 * * @return string|false Locale on success, false on failure. */ 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; } /** * Restores the translations according to the original locale. * * @since 4.7.0 * * @return string|false Locale on success, false on failure. */ public function restore_current_locale() { if ( empty( $this->locales ) ) { return false; } $this->locales = array( $this->original_locale ); return $this->restore_previous_locale(); } /** * Whether switch_to_locale() is in effect. * * @since 4.7.0 * * @return bool True if the locale has been switched, false otherwise. */ public function is_switched() { return ! empty( $this->locales ); } /** * Filters the locale of the WordPress installation. * * @since 4.7.0 * * @param string $locale The locale of the WordPress installation. * @return string The locale currently being switched to. */ public function filter_locale( $locale ) { $switched_locale = end( $this->locales ); if ( $switched_locale ) { return $switched_locale; } return $locale; } /** * Load translations for a given locale. * * When switching to a locale, translations for this locale must be loaded from scratch. * * @since 4.7.0 * * @global Mo[] $l10n An array of all currently loaded text domains. * * @param string $locale The locale to load translations for. */ 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 ); } } /** * Changes the site's locale to the given one. * * Loads the translations, changes the global `$wp_locale` object and updates * all post type labels. * * @since 4.7.0 * * @global WP_Locale $wp_locale WordPress date and time locale object. * * @param string $locale The locale to change to. */ 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 ); } } ``` | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. | wordpress class WP_HTTP_Requests_Response {} class WP\_HTTP\_Requests\_Response {} ===================================== Core wrapper object for a [Requests\_Response](requests_response) for standardisation. * [WP\_HTTP\_Response](wp_http_response) * [\_\_construct](wp_http_requests_response/__construct) β€” Constructor. * [get\_cookies](wp_http_requests_response/get_cookies) β€” Retrieves cookies from the response. * [get\_data](wp_http_requests_response/get_data) β€” Retrieves the response data. * [get\_headers](wp_http_requests_response/get_headers) β€” Retrieves headers associated with the response. * [get\_response\_object](wp_http_requests_response/get_response_object) β€” Retrieves the response object for the request. * [get\_status](wp_http_requests_response/get_status) β€” Retrieves the HTTP return code for the response. * [header](wp_http_requests_response/header) β€” Sets a single HTTP header. * [set\_data](wp_http_requests_response/set_data) β€” Sets the response data. * [set\_headers](wp_http_requests_response/set_headers) β€” Sets all header values. * [set\_status](wp_http_requests_response/set_status) β€” Sets the 3-digit HTTP status code. * [to\_array](wp_http_requests_response/to_array) β€” Converts the object to a WP\_Http response array. File: `wp-includes/class-wp-http-requests-response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-requests-response.php/) ``` class WP_HTTP_Requests_Response extends WP_HTTP_Response { /** * Requests Response object. * * @since 4.6.0 * @var Requests_Response */ protected $response; /** * Filename the response was saved to. * * @since 4.6.0 * @var string|null */ protected $filename; /** * Constructor. * * @since 4.6.0 * * @param Requests_Response $response HTTP response. * @param string $filename Optional. File name. Default empty. */ public function __construct( Requests_Response $response, $filename = '' ) { $this->response = $response; $this->filename = $filename; } /** * Retrieves the response object for the request. * * @since 4.6.0 * * @return Requests_Response HTTP response. */ public function get_response_object() { return $this->response; } /** * Retrieves headers associated with the response. * * @since 4.6.0 * * @return \Requests_Utility_CaseInsensitiveDictionary Map of header name to header value. */ public function get_headers() { // Ensure headers remain case-insensitive. $converted = new Requests_Utility_CaseInsensitiveDictionary(); foreach ( $this->response->headers->getAll() as $key => $value ) { if ( count( $value ) === 1 ) { $converted[ $key ] = $value[0]; } else { $converted[ $key ] = $value; } } return $converted; } /** * Sets all header values. * * @since 4.6.0 * * @param array $headers Map of header name to header value. */ public function set_headers( $headers ) { $this->response->headers = new Requests_Response_Headers( $headers ); } /** * Sets a single HTTP header. * * @since 4.6.0 * * @param string $key Header name. * @param string $value Header value. * @param bool $replace Optional. Whether to replace an existing header of the same name. * Default true. */ public function header( $key, $value, $replace = true ) { if ( $replace ) { unset( $this->response->headers[ $key ] ); } $this->response->headers[ $key ] = $value; } /** * Retrieves the HTTP return code for the response. * * @since 4.6.0 * * @return int The 3-digit HTTP status code. */ public function get_status() { return $this->response->status_code; } /** * Sets the 3-digit HTTP status code. * * @since 4.6.0 * * @param int $code HTTP status. */ public function set_status( $code ) { $this->response->status_code = absint( $code ); } /** * Retrieves the response data. * * @since 4.6.0 * * @return string Response data. */ public function get_data() { return $this->response->body; } /** * Sets the response data. * * @since 4.6.0 * * @param string $data Response data. */ public function set_data( $data ) { $this->response->body = $data; } /** * Retrieves cookies from the response. * * @since 4.6.0 * * @return WP_HTTP_Cookie[] List of cookie objects. */ public function get_cookies() { $cookies = array(); foreach ( $this->response->cookies as $cookie ) { $cookies[] = new WP_Http_Cookie( array( 'name' => $cookie->name, 'value' => urldecode( $cookie->value ), 'expires' => isset( $cookie->attributes['expires'] ) ? $cookie->attributes['expires'] : null, 'path' => isset( $cookie->attributes['path'] ) ? $cookie->attributes['path'] : null, 'domain' => isset( $cookie->attributes['domain'] ) ? $cookie->attributes['domain'] : null, 'host_only' => isset( $cookie->flags['host-only'] ) ? $cookie->flags['host-only'] : null, ) ); } return $cookies; } /** * Converts the object to a WP_Http response array. * * @since 4.6.0 * * @return array WP_Http response array, per WP_Http::request(). */ public function to_array() { return array( 'headers' => $this->get_headers(), 'body' => $this->get_data(), 'response' => array( 'code' => $this->get_status(), 'message' => get_status_header_desc( $this->get_status() ), ), 'cookies' => $this->get_cookies(), 'filename' => $this->filename, ); } } ``` | Uses | Description | | --- | --- | | [WP\_HTTP\_Response](wp_http_response) wp-includes/class-wp-http-response.php | Core class used to prepare HTTP responses. | | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. | wordpress class Walker_Category_Checklist {} class Walker\_Category\_Checklist {} ==================================== Core walker class to output an unordered list of category checkbox input elements. * [Walker](walker) * [wp\_category\_checklist()](../functions/wp_category_checklist) * [wp\_terms\_checklist()](../functions/wp_terms_checklist) * [end\_el](walker_category_checklist/end_el) β€” Ends the element output, if needed. * [end\_lvl](walker_category_checklist/end_lvl) β€” Ends the list of after the elements are added. * [start\_el](walker_category_checklist/start_el) β€” Start the element output. * [start\_lvl](walker_category_checklist/start_lvl) β€” Starts the list before the elements are added. File: `wp-admin/includes/class-walker-category-checklist.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-walker-category-checklist.php/) ``` class Walker_Category_Checklist extends Walker { public $tree_type = 'category'; public $db_fields = array( 'parent' => 'parent', 'id' => 'term_id', ); // TODO: Decouple this. /** * Starts the list before the elements are added. * * @see Walker:start_lvl() * * @since 2.5.1 * * @param string $output Used to append additional content (passed by reference). * @param int $depth Depth of category. Used for tab indentation. * @param array $args An array of arguments. @see wp_terms_checklist() */ public function start_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat( "\t", $depth ); $output .= "$indent<ul class='children'>\n"; } /** * Ends the list of after the elements are added. * * @see Walker::end_lvl() * * @since 2.5.1 * * @param string $output Used to append additional content (passed by reference). * @param int $depth Depth of category. Used for tab indentation. * @param array $args An array of arguments. @see wp_terms_checklist() */ public function end_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat( "\t", $depth ); $output .= "$indent</ul>\n"; } /** * Start the element output. * * @see Walker::start_el() * * @since 2.5.1 * @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. * * @param string $output Used to append additional content (passed by reference). * @param WP_Term $data_object The current term object. * @param int $depth Depth of the term in reference to parents. Default 0. * @param array $args An array of arguments. @see wp_terms_checklist() * @param int $current_object_id Optional. ID of the current term. Default 0. */ 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; if ( empty( $args['taxonomy'] ) ) { $taxonomy = 'category'; } else { $taxonomy = $args['taxonomy']; } if ( 'category' === $taxonomy ) { $name = 'post_category'; } else { $name = 'tax_input[' . $taxonomy . ']'; } $args['popular_cats'] = ! empty( $args['popular_cats'] ) ? array_map( 'intval', $args['popular_cats'] ) : array(); $class = in_array( $category->term_id, $args['popular_cats'], true ) ? ' class="popular-category"' : ''; $args['selected_cats'] = ! empty( $args['selected_cats'] ) ? array_map( 'intval', $args['selected_cats'] ) : array(); if ( ! empty( $args['list_only'] ) ) { $aria_checked = 'false'; $inner_class = 'category'; if ( in_array( $category->term_id, $args['selected_cats'], true ) ) { $inner_class .= ' selected'; $aria_checked = 'true'; } $output .= "\n" . '<li' . $class . '>' . '<div class="' . $inner_class . '" data-term-id=' . $category->term_id . ' tabindex="0" role="checkbox" aria-checked="' . $aria_checked . '">' . /** This filter is documented in wp-includes/category-template.php */ esc_html( apply_filters( 'the_category', $category->name, '', '' ) ) . '</div>'; } else { $is_selected = in_array( $category->term_id, $args['selected_cats'], true ); $is_disabled = ! empty( $args['disabled'] ); $output .= "\n<li id='{$taxonomy}-{$category->term_id}'$class>" . '<label class="selectit"><input value="' . $category->term_id . '" type="checkbox" name="' . $name . '[]" id="in-' . $taxonomy . '-' . $category->term_id . '"' . checked( $is_selected, true, false ) . disabled( $is_disabled, true, false ) . ' /> ' . /** This filter is documented in wp-includes/category-template.php */ esc_html( apply_filters( 'the_category', $category->name, '', '' ) ) . '</label>'; } } /** * Ends the element output, if needed. * * @see Walker::end_el() * * @since 2.5.1 * @since 5.9.0 Renamed `$category` to `$data_object` to match parent class for PHP 8 named parameter support. * * @param string $output Used to append additional content (passed by reference). * @param WP_Term $data_object The current term object. * @param int $depth Depth of the term in reference to parents. Default 0. * @param array $args An array of arguments. @see wp_terms_checklist() */ public function end_el( &$output, $data_object, $depth = 0, $args = array() ) { $output .= "</li>\n"; } } ``` | Uses | Description | | --- | --- | | [Walker](walker) wp-includes/class-wp-walker.php | A class for displaying various tree-like structures. | | Version | Description | | --- | --- | | [2.5.1](https://developer.wordpress.org/reference/since/2.5.1/) | Introduced. | wordpress class POMO_Reader {} class POMO\_Reader {} ===================== * [\_\_construct](pomo_reader/__construct) β€” PHP5 constructor. * [close](pomo_reader/close) * [is\_resource](pomo_reader/is_resource) * [POMO\_Reader](pomo_reader/pomo_reader) β€” PHP4 constructor. β€” deprecated * [pos](pomo_reader/pos) * [readint32](pomo_reader/readint32) β€” Reads a 32bit Integer from the Stream * [readint32array](pomo_reader/readint32array) β€” Reads an array of 32-bit Integers from the Stream * [setEndian](pomo_reader/setendian) β€” Sets the endianness of the file. * [str\_split](pomo_reader/str_split) * [strlen](pomo_reader/strlen) * [substr](pomo_reader/substr) File: `wp-includes/pomo/streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/streams.php/) ``` class POMO_Reader { public $endian = 'little'; public $_pos; public $is_overloaded; /** * PHP5 constructor. */ public function __construct() { if ( function_exists( 'mb_substr' ) && ( (int) ini_get( 'mbstring.func_overload' ) & 2 ) // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.mbstring_func_overloadDeprecated ) { $this->is_overloaded = true; } else { $this->is_overloaded = false; } $this->_pos = 0; } /** * PHP4 constructor. * * @deprecated 5.4.0 Use __construct() instead. * * @see POMO_Reader::__construct() */ public function POMO_Reader() { _deprecated_constructor( self::class, '5.4.0', static::class ); self::__construct(); } /** * Sets the endianness of the file. * * @param string $endian Set the endianness of the file. Accepts 'big', or 'little'. */ public function setEndian( $endian ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid $this->endian = $endian; } /** * Reads a 32bit Integer from the Stream * * @return mixed The integer, corresponding to the next 32 bits from * the stream of false if there are not enough bytes or on error */ public function readint32() { $bytes = $this->read( 4 ); if ( 4 != $this->strlen( $bytes ) ) { return false; } $endian_letter = ( 'big' === $this->endian ) ? 'N' : 'V'; $int = unpack( $endian_letter, $bytes ); return reset( $int ); } /** * Reads an array of 32-bit Integers from the Stream * * @param int $count How many elements should be read * @return mixed Array of integers or false if there isn't * enough data or on error */ public function readint32array( $count ) { $bytes = $this->read( 4 * $count ); if ( 4 * $count != $this->strlen( $bytes ) ) { return false; } $endian_letter = ( 'big' === $this->endian ) ? 'N' : 'V'; return unpack( $endian_letter . $count, $bytes ); } /** * @param string $string * @param int $start * @param int $length * @return string */ public function substr( $string, $start, $length ) { if ( $this->is_overloaded ) { return mb_substr( $string, $start, $length, 'ascii' ); } else { return substr( $string, $start, $length ); } } /** * @param string $string * @return int */ public function strlen( $string ) { if ( $this->is_overloaded ) { return mb_strlen( $string, 'ascii' ); } else { return strlen( $string ); } } /** * @param string $string * @param int $chunk_size * @return array */ public function str_split( $string, $chunk_size ) { if ( ! function_exists( 'str_split' ) ) { $length = $this->strlen( $string ); $out = array(); for ( $i = 0; $i < $length; $i += $chunk_size ) { $out[] = $this->substr( $string, $i, $chunk_size ); } return $out; } else { return str_split( $string, $chunk_size ); } } /** * @return int */ public function pos() { return $this->_pos; } /** * @return true */ public function is_resource() { return true; } /** * @return true */ public function close() { return true; } } ``` | Used By | Description | | --- | --- | | [POMO\_StringReader](pomo_stringreader) wp-includes/pomo/streams.php | Provides file-like methods for manipulating a string instead of a physical file. | | [POMO\_FileReader](pomo_filereader) wp-includes/pomo/streams.php | |
programming_docs
wordpress class WP_REST_Comment_Meta_Fields {} class WP\_REST\_Comment\_Meta\_Fields {} ======================================== Core class to manage comment meta via the REST API. * [WP\_REST\_Meta\_Fields](wp_rest_meta_fields) * [get\_meta\_subtype](wp_rest_comment_meta_fields/get_meta_subtype) β€” Retrieves the comment meta subtype. * [get\_meta\_type](wp_rest_comment_meta_fields/get_meta_type) β€” Retrieves the comment type for comment meta. * [get\_rest\_field\_type](wp_rest_comment_meta_fields/get_rest_field_type) β€” Retrieves the type for register\_rest\_field() in the context of comments. File: `wp-includes/rest-api/fields/class-wp-rest-comment-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-comment-meta-fields.php/) ``` class WP_REST_Comment_Meta_Fields extends WP_REST_Meta_Fields { /** * Retrieves the comment type for comment meta. * * @since 4.7.0 * * @return string The meta type. */ protected function get_meta_type() { return 'comment'; } /** * Retrieves the comment meta subtype. * * @since 4.9.8 * * @return string 'comment' There are no subtypes. */ protected function get_meta_subtype() { return 'comment'; } /** * Retrieves the type for register_rest_field() in the context of comments. * * @since 4.7.0 * * @return string The REST field type. */ public function get_rest_field_type() { return 'comment'; } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Meta\_Fields](wp_rest_meta_fields) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Core class to manage meta values for an object via the REST API. | | Version | Description | | --- | --- | | [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. | wordpress class WP_Customize_Setting {} class WP\_Customize\_Setting {} =============================== Customize Setting class. Handles saving and sanitizing of settings. * [WP\_Customize\_Manager](wp_customize_manager) * [\_\_construct](wp_customize_setting/__construct) β€” Constructor. * [\_clear\_aggregated\_multidimensional\_preview\_applied\_flag](wp_customize_setting/_clear_aggregated_multidimensional_preview_applied_flag) β€” Clear out the previewed-applied flag for a multidimensional-aggregated value whenever its post value is updated. * [\_multidimensional\_preview\_filter](wp_customize_setting/_multidimensional_preview_filter) β€” Callback function to filter multidimensional theme mods and options. * [\_preview\_filter](wp_customize_setting/_preview_filter) β€” Callback function to filter non-multidimensional theme mods and options. * [\_update\_option](wp_customize_setting/_update_option) β€” Deprecated method. β€” deprecated * [\_update\_theme\_mod](wp_customize_setting/_update_theme_mod) β€” Deprecated method. β€” deprecated * [aggregate\_multidimensional](wp_customize_setting/aggregate_multidimensional) β€” Set up the setting for aggregated multidimensional values. * [check\_capabilities](wp_customize_setting/check_capabilities) β€” Validate user capabilities whether the theme supports the setting. * [get\_root\_value](wp_customize_setting/get_root_value) β€” Get the root value for a setting, especially for multidimensional ones. * [id\_data](wp_customize_setting/id_data) β€” Get parsed ID data for multidimensional setting. * [is\_current\_blog\_previewed](wp_customize_setting/is_current_blog_previewed) β€” Return true if the current site is not the same as the previewed site. * [js\_value](wp_customize_setting/js_value) β€” Sanitize the setting's value for use in JavaScript. * [json](wp_customize_setting/json) β€” Retrieves the data to export to the client via JSON. * [multidimensional](wp_customize_setting/multidimensional) β€” Multidimensional helper function. * [multidimensional\_get](wp_customize_setting/multidimensional_get) β€” Will attempt to fetch a specific value from a multidimensional array. * [multidimensional\_isset](wp_customize_setting/multidimensional_isset) β€” Will attempt to check if a specific value in a multidimensional array is set. * [multidimensional\_replace](wp_customize_setting/multidimensional_replace) β€” Will attempt to replace a specific value in a multidimensional array. * [post\_value](wp_customize_setting/post_value) β€” Fetch and sanitize the $\_POST value for the setting. * [preview](wp_customize_setting/preview) β€” Add filters to supply the setting's value when accessed. * [sanitize](wp_customize_setting/sanitize) β€” Sanitize an input. * [save](wp_customize_setting/save) β€” Checks user capabilities and theme supports, and then saves the value of the setting. * [set\_root\_value](wp_customize_setting/set_root_value) β€” Set the root value for a setting, especially for multidimensional ones. * [update](wp_customize_setting/update) β€” Save the value of the setting, using the related API. * [validate](wp_customize_setting/validate) β€” Validates an input. * [value](wp_customize_setting/value) β€” Fetch the value of the setting. File: `wp-includes/class-wp-customize-setting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-setting.php/) ``` class WP_Customize_Setting { /** * Customizer bootstrap instance. * * @since 3.4.0 * @var WP_Customize_Manager */ public $manager; /** * Unique string identifier for the setting. * * @since 3.4.0 * @var string */ public $id; /** * Type of customize settings. * * @since 3.4.0 * @var string */ public $type = 'theme_mod'; /** * Capability required to edit this setting. * * @since 3.4.0 * @var string|array */ public $capability = 'edit_theme_options'; /** * Theme features required to support the setting. * * @since 3.4.0 * @var string|string[] */ public $theme_supports = ''; /** * The default value for the setting. * * @since 3.4.0 * @var string */ public $default = ''; /** * Options for rendering the live preview of changes in Customizer. * * Set this value to 'postMessage' to enable a custom JavaScript handler to render changes to this setting * as opposed to reloading the whole page. * * @since 3.4.0 * @var string */ public $transport = 'refresh'; /** * Server-side validation callback for the setting's value. * * @since 4.6.0 * @var callable */ public $validate_callback = ''; /** * Callback to filter a Customize setting value in un-slashed form. * * @since 3.4.0 * @var callable */ public $sanitize_callback = ''; /** * Callback to convert a Customize PHP setting value to a value that is JSON serializable. * * @since 3.4.0 * @var callable */ public $sanitize_js_callback = ''; /** * Whether or not the setting is initially dirty when created. * * This is used to ensure that a setting will be sent from the pane to the * preview when loading the Customizer. Normally a setting only is synced to * the preview if it has been changed. This allows the setting to be sent * from the start. * * @since 4.2.0 * @var bool */ public $dirty = false; /** * ID Data. * * @since 3.4.0 * @var array */ protected $id_data = array(); /** * Whether or not preview() was called. * * @since 4.4.0 * @var bool */ protected $is_previewed = false; /** * Cache of multidimensional values to improve performance. * * @since 4.4.0 * @var array */ protected static $aggregated_multidimensionals = array(); /** * Whether the multidimensional setting is aggregated. * * @since 4.4.0 * @var bool */ protected $is_multidimensional_aggregated = false; /** * Constructor. * * Any supplied $args override class property defaults. * * @since 3.4.0 * * @param WP_Customize_Manager $manager Customizer bootstrap instance. * @param string $id A specific ID of the setting. * Can be a theme mod or option name. * @param array $args { * Optional. Array of properties for the new Setting object. Default empty array. * * @type string $type Type of the setting. Default 'theme_mod'. * @type string $capability Capability required for the setting. Default 'edit_theme_options' * @type string|string[] $theme_supports Theme features required to support the panel. Default is none. * @type string $default Default value for the setting. Default is empty string. * @type string $transport Options for rendering the live preview of changes in Customizer. * Using 'refresh' makes the change visible by reloading the whole preview. * Using 'postMessage' allows a custom JavaScript to handle live changes. * Default is 'refresh'. * @type callable $validate_callback Server-side validation callback for the setting's value. * @type callable $sanitize_callback Callback to filter a Customize setting value in un-slashed form. * @type callable $sanitize_js_callback Callback to convert a Customize PHP setting value to a value that is * JSON serializable. * @type bool $dirty Whether or not the setting is initially dirty when created. * } */ 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; // Parse the ID for array keys. $this->id_data['keys'] = preg_split( '/\[/', str_replace( ']', '', $this->id ) ); $this->id_data['base'] = array_shift( $this->id_data['keys'] ); // Rebuild the ID. $this->id = $this->id_data['base']; if ( ! empty( $this->id_data['keys'] ) ) { $this->id .= '[' . implode( '][', $this->id_data['keys'] ) . ']'; } if ( $this->validate_callback ) { add_filter( "customize_validate_{$this->id}", $this->validate_callback, 10, 3 ); } if ( $this->sanitize_callback ) { add_filter( "customize_sanitize_{$this->id}", $this->sanitize_callback, 10, 2 ); } if ( $this->sanitize_js_callback ) { add_filter( "customize_sanitize_js_{$this->id}", $this->sanitize_js_callback, 10, 2 ); } if ( 'option' === $this->type || 'theme_mod' === $this->type ) { // Other setting types can opt-in to aggregate multidimensional explicitly. $this->aggregate_multidimensional(); // Allow option settings to indicate whether they should be autoloaded. if ( 'option' === $this->type && isset( $args['autoload'] ) ) { self::$aggregated_multidimensionals[ $this->type ][ $this->id_data['base'] ]['autoload'] = $args['autoload']; } } } /** * Get parsed ID data for multidimensional setting. * * @since 4.4.0 * * @return array { * ID data for multidimensional setting. * * @type string $base ID base * @type array $keys Keys for multidimensional array. * } */ final public function id_data() { return $this->id_data; } /** * Set up the setting for aggregated multidimensional values. * * When a multidimensional setting gets aggregated, all of its preview and update * calls get combined into one call, greatly improving performance. * * @since 4.4.0 */ protected function aggregate_multidimensional() { $id_base = $this->id_data['base']; if ( ! isset( self::$aggregated_multidimensionals[ $this->type ] ) ) { self::$aggregated_multidimensionals[ $this->type ] = array(); } if ( ! isset( self::$aggregated_multidimensionals[ $this->type ][ $id_base ] ) ) { self::$aggregated_multidimensionals[ $this->type ][ $id_base ] = array( 'previewed_instances' => array(), // Calling preview() will add the $setting to the array. 'preview_applied_instances' => array(), // Flags for which settings have had their values applied. 'root_value' => $this->get_root_value( array() ), // Root value for initial state, manipulated by preview and update calls. ); } if ( ! empty( $this->id_data['keys'] ) ) { // Note the preview-applied flag is cleared at priority 9 to ensure it is cleared before a deferred-preview runs. add_action( "customize_post_value_set_{$this->id}", array( $this, '_clear_aggregated_multidimensional_preview_applied_flag' ), 9 ); $this->is_multidimensional_aggregated = true; } } /** * Reset `$aggregated_multidimensionals` static variable. * * This is intended only for use by unit tests. * * @since 4.5.0 * @ignore */ public static function reset_aggregated_multidimensionals() { self::$aggregated_multidimensionals = array(); } /** * The ID for the current site when the preview() method was called. * * @since 4.2.0 * @var int */ protected $_previewed_blog_id; /** * Return true if the current site is not the same as the previewed site. * * @since 4.2.0 * * @return bool If preview() has been called. */ public function is_current_blog_previewed() { if ( ! isset( $this->_previewed_blog_id ) ) { return false; } return ( get_current_blog_id() === $this->_previewed_blog_id ); } /** * Original non-previewed value stored by the preview method. * * @see WP_Customize_Setting::preview() * @since 4.1.1 * @var mixed */ protected $_original_value; /** * Add filters to supply the setting's value when accessed. * * If the setting already has a pre-existing value and there is no incoming * post value for the setting, then this method will short-circuit since * there is no change to preview. * * @since 3.4.0 * @since 4.4.0 Added boolean return value. * * @return bool False when preview short-circuits due no change needing to be previewed. */ public function preview() { if ( ! isset( $this->_previewed_blog_id ) ) { $this->_previewed_blog_id = get_current_blog_id(); } // Prevent re-previewing an already-previewed setting. if ( $this->is_previewed ) { return true; } $id_base = $this->id_data['base']; $is_multidimensional = ! empty( $this->id_data['keys'] ); $multidimensional_filter = array( $this, '_multidimensional_preview_filter' ); /* * Check if the setting has a pre-existing value (an isset check), * and if doesn't have any incoming post value. If both checks are true, * then the preview short-circuits because there is nothing that needs * to be previewed. */ $undefined = new stdClass(); $needs_preview = ( $undefined !== $this->post_value( $undefined ) ); $value = null; // Since no post value was defined, check if we have an initial value set. if ( ! $needs_preview ) { if ( $this->is_multidimensional_aggregated ) { $root = self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value']; $value = $this->multidimensional_get( $root, $this->id_data['keys'], $undefined ); } else { $default = $this->default; $this->default = $undefined; // Temporarily set default to undefined so we can detect if existing value is set. $value = $this->value(); $this->default = $default; } $needs_preview = ( $undefined === $value ); // Because the default needs to be supplied. } // If the setting does not need previewing now, defer to when it has a value to preview. if ( ! $needs_preview ) { if ( ! has_action( "customize_post_value_set_{$this->id}", array( $this, 'preview' ) ) ) { add_action( "customize_post_value_set_{$this->id}", array( $this, 'preview' ) ); } return false; } switch ( $this->type ) { case 'theme_mod': if ( ! $is_multidimensional ) { add_filter( "theme_mod_{$id_base}", array( $this, '_preview_filter' ) ); } else { if ( empty( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'] ) ) { // Only add this filter once for this ID base. add_filter( "theme_mod_{$id_base}", $multidimensional_filter ); } self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'][ $this->id ] = $this; } break; case 'option': if ( ! $is_multidimensional ) { add_filter( "pre_option_{$id_base}", array( $this, '_preview_filter' ) ); } else { if ( empty( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'] ) ) { // Only add these filters once for this ID base. add_filter( "option_{$id_base}", $multidimensional_filter ); add_filter( "default_option_{$id_base}", $multidimensional_filter ); } self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'][ $this->id ] = $this; } break; default: /** * Fires when the WP_Customize_Setting::preview() method is called for settings * not handled as theme_mods or options. * * The dynamic portion of the hook name, `$this->id`, refers to the setting ID. * * @since 3.4.0 * * @param WP_Customize_Setting $setting WP_Customize_Setting instance. */ do_action( "customize_preview_{$this->id}", $this ); /** * Fires when the WP_Customize_Setting::preview() method is called for settings * not handled as theme_mods or options. * * The dynamic portion of the hook name, `$this->type`, refers to the setting type. * * @since 4.1.0 * * @param WP_Customize_Setting $setting WP_Customize_Setting instance. */ do_action( "customize_preview_{$this->type}", $this ); } $this->is_previewed = true; return true; } /** * Clear out the previewed-applied flag for a multidimensional-aggregated value whenever its post value is updated. * * This ensures that the new value will get sanitized and used the next time * that `WP_Customize_Setting::_multidimensional_preview_filter()` * is called for this setting. * * @since 4.4.0 * * @see WP_Customize_Manager::set_post_value() * @see WP_Customize_Setting::_multidimensional_preview_filter() */ final public function _clear_aggregated_multidimensional_preview_applied_flag() { unset( self::$aggregated_multidimensionals[ $this->type ][ $this->id_data['base'] ]['preview_applied_instances'][ $this->id ] ); } /** * Callback function to filter non-multidimensional theme mods and options. * * If switch_to_blog() was called after the preview() method, and the current * site is now not the same site, then this method does a no-op and returns * the original value. * * @since 3.4.0 * * @param mixed $original Old value. * @return mixed New or old value. */ public function _preview_filter( $original ) { if ( ! $this->is_current_blog_previewed() ) { return $original; } $undefined = new stdClass(); // Symbol hack. $post_value = $this->post_value( $undefined ); if ( $undefined !== $post_value ) { $value = $post_value; } else { /* * Note that we don't use $original here because preview() will * not add the filter in the first place if it has an initial value * and there is no post value. */ $value = $this->default; } return $value; } /** * Callback function to filter multidimensional theme mods and options. * * For all multidimensional settings of a given type, the preview filter for * the first setting previewed will be used to apply the values for the others. * * @since 4.4.0 * * @see WP_Customize_Setting::$aggregated_multidimensionals * @param mixed $original Original root value. * @return mixed New or old value. */ final public function _multidimensional_preview_filter( $original ) { if ( ! $this->is_current_blog_previewed() ) { return $original; } $id_base = $this->id_data['base']; // If no settings have been previewed yet (which should not be the case, since $this is), just pass through the original value. if ( empty( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'] ) ) { return $original; } foreach ( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['previewed_instances'] as $previewed_setting ) { // Skip applying previewed value for any settings that have already been applied. if ( ! empty( self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['preview_applied_instances'][ $previewed_setting->id ] ) ) { continue; } // Do the replacements of the posted/default sub value into the root value. $value = $previewed_setting->post_value( $previewed_setting->default ); $root = self::$aggregated_multidimensionals[ $previewed_setting->type ][ $id_base ]['root_value']; $root = $previewed_setting->multidimensional_replace( $root, $previewed_setting->id_data['keys'], $value ); self::$aggregated_multidimensionals[ $previewed_setting->type ][ $id_base ]['root_value'] = $root; // Mark this setting having been applied so that it will be skipped when the filter is called again. self::$aggregated_multidimensionals[ $previewed_setting->type ][ $id_base ]['preview_applied_instances'][ $previewed_setting->id ] = true; } return self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value']; } /** * Checks user capabilities and theme supports, and then saves * the value of the setting. * * @since 3.4.0 * * @return void|false Void on success, false if cap check fails * or value isn't set or is invalid. */ final public function save() { $value = $this->post_value(); if ( ! $this->check_capabilities() || ! isset( $value ) ) { return false; } $id_base = $this->id_data['base']; /** * Fires when the WP_Customize_Setting::save() method is called. * * The dynamic portion of the hook name, `$id_base` refers to * the base slug of the setting name. * * @since 3.4.0 * * @param WP_Customize_Setting $setting WP_Customize_Setting instance. */ do_action( "customize_save_{$id_base}", $this ); $this->update( $value ); } /** * Fetch and sanitize the $_POST value for the setting. * * During a save request prior to save, post_value() provides the new value while value() does not. * * @since 3.4.0 * * @param mixed $default_value A default value which is used as a fallback. Default null. * @return mixed The default value on failure, otherwise the sanitized and validated value. */ final public function post_value( $default_value = null ) { return $this->manager->post_value( $this, $default_value ); } /** * Sanitize an input. * * @since 3.4.0 * * @param string|array $value The value to sanitize. * @return string|array|null|WP_Error Sanitized value, or `null`/`WP_Error` if invalid. */ public function sanitize( $value ) { /** * Filters a Customize setting value in un-slashed form. * * @since 3.4.0 * * @param mixed $value Value of the setting. * @param WP_Customize_Setting $setting WP_Customize_Setting instance. */ return apply_filters( "customize_sanitize_{$this->id}", $value, $this ); } /** * Validates an input. * * @since 4.6.0 * * @see WP_REST_Request::has_valid_params() * * @param mixed $value Value to validate. * @return true|WP_Error True if the input was validated, otherwise WP_Error. */ public function validate( $value ) { if ( is_wp_error( $value ) ) { return $value; } if ( is_null( $value ) ) { return new WP_Error( 'invalid_value', __( 'Invalid value.' ) ); } $validity = new WP_Error(); /** * Validates a Customize setting value. * * Plugins should amend the `$validity` object via its `WP_Error::add()` method. * * The dynamic portion of the hook name, `$this->ID`, refers to the setting ID. * * @since 4.6.0 * * @param WP_Error $validity Filtered from `true` to `WP_Error` when invalid. * @param mixed $value Value of the setting. * @param WP_Customize_Setting $setting WP_Customize_Setting instance. */ $validity = apply_filters( "customize_validate_{$this->id}", $validity, $value, $this ); if ( is_wp_error( $validity ) && ! $validity->has_errors() ) { $validity = true; } return $validity; } /** * Get the root value for a setting, especially for multidimensional ones. * * @since 4.4.0 * * @param mixed $default_value Value to return if root does not exist. * @return mixed */ protected function get_root_value( $default_value = null ) { $id_base = $this->id_data['base']; if ( 'option' === $this->type ) { return get_option( $id_base, $default_value ); } elseif ( 'theme_mod' === $this->type ) { return get_theme_mod( $id_base, $default_value ); } else { /* * Any WP_Customize_Setting subclass implementing aggregate multidimensional * will need to override this method to obtain the data from the appropriate * location. */ return $default_value; } } /** * Set the root value for a setting, especially for multidimensional ones. * * @since 4.4.0 * * @param mixed $value Value to set as root of multidimensional setting. * @return bool Whether the multidimensional root was updated successfully. */ protected function set_root_value( $value ) { $id_base = $this->id_data['base']; if ( 'option' === $this->type ) { $autoload = true; if ( isset( self::$aggregated_multidimensionals[ $this->type ][ $this->id_data['base'] ]['autoload'] ) ) { $autoload = self::$aggregated_multidimensionals[ $this->type ][ $this->id_data['base'] ]['autoload']; } return update_option( $id_base, $value, $autoload ); } elseif ( 'theme_mod' === $this->type ) { set_theme_mod( $id_base, $value ); return true; } else { /* * Any WP_Customize_Setting subclass implementing aggregate multidimensional * will need to override this method to obtain the data from the appropriate * location. */ return false; } } /** * Save the value of the setting, using the related API. * * @since 3.4.0 * * @param mixed $value The value to update. * @return bool The result of saving the value. */ protected function update( $value ) { $id_base = $this->id_data['base']; if ( 'option' === $this->type || 'theme_mod' === $this->type ) { if ( ! $this->is_multidimensional_aggregated ) { return $this->set_root_value( $value ); } else { $root = self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value']; $root = $this->multidimensional_replace( $root, $this->id_data['keys'], $value ); self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value'] = $root; return $this->set_root_value( $root ); } } else { /** * Fires when the WP_Customize_Setting::update() method is called for settings * not handled as theme_mods or options. * * The dynamic portion of the hook name, `$this->type`, refers to the type of setting. * * @since 3.4.0 * * @param mixed $value Value of the setting. * @param WP_Customize_Setting $setting WP_Customize_Setting instance. */ do_action( "customize_update_{$this->type}", $value, $this ); return has_action( "customize_update_{$this->type}" ); } } /** * Deprecated method. * * @since 3.4.0 * @deprecated 4.4.0 Deprecated in favor of update() method. */ protected function _update_theme_mod() { _deprecated_function( __METHOD__, '4.4.0', __CLASS__ . '::update()' ); } /** * Deprecated method. * * @since 3.4.0 * @deprecated 4.4.0 Deprecated in favor of update() method. */ protected function _update_option() { _deprecated_function( __METHOD__, '4.4.0', __CLASS__ . '::update()' ); } /** * Fetch the value of the setting. * * @since 3.4.0 * * @return mixed The value. */ public function value() { $id_base = $this->id_data['base']; $is_core_type = ( 'option' === $this->type || 'theme_mod' === $this->type ); if ( ! $is_core_type && ! $this->is_multidimensional_aggregated ) { // Use post value if previewed and a post value is present. if ( $this->is_previewed ) { $value = $this->post_value( null ); if ( null !== $value ) { return $value; } } $value = $this->get_root_value( $this->default ); /** * Filters a Customize setting value not handled as a theme_mod or option. * * The dynamic portion of the hook name, `$id_base`, refers to * the base slug of the setting name, initialized from `$this->id_data['base']`. * * For settings handled as theme_mods or options, see those corresponding * functions for available hooks. * * @since 3.4.0 * @since 4.6.0 Added the `$this` setting instance as the second parameter. * * @param mixed $default_value The setting default value. Default empty. * @param WP_Customize_Setting $setting The setting instance. */ $value = apply_filters( "customize_value_{$id_base}", $value, $this ); } elseif ( $this->is_multidimensional_aggregated ) { $root_value = self::$aggregated_multidimensionals[ $this->type ][ $id_base ]['root_value']; $value = $this->multidimensional_get( $root_value, $this->id_data['keys'], $this->default ); // Ensure that the post value is used if the setting is previewed, since preview filters aren't applying on cached $root_value. if ( $this->is_previewed ) { $value = $this->post_value( $value ); } } else { $value = $this->get_root_value( $this->default ); } return $value; } /** * Sanitize the setting's value for use in JavaScript. * * @since 3.4.0 * * @return mixed The requested escaped value. */ public function js_value() { /** * Filters a Customize setting value for use in JavaScript. * * The dynamic portion of the hook name, `$this->id`, refers to the setting ID. * * @since 3.4.0 * * @param mixed $value The setting value. * @param WP_Customize_Setting $setting WP_Customize_Setting instance. */ $value = apply_filters( "customize_sanitize_js_{$this->id}", $this->value(), $this ); if ( is_string( $value ) ) { return html_entity_decode( $value, ENT_QUOTES, 'UTF-8' ); } return $value; } /** * Retrieves the data to export to the client via JSON. * * @since 4.6.0 * * @return array Array of parameters passed to JavaScript. */ public function json() { return array( 'value' => $this->js_value(), 'transport' => $this->transport, 'dirty' => $this->dirty, 'type' => $this->type, ); } /** * Validate user capabilities whether the theme supports the setting. * * @since 3.4.0 * * @return bool False if theme doesn't support the setting or user can't change setting, otherwise true. */ final public function check_capabilities() { if ( $this->capability && ! current_user_can( $this->capability ) ) { return false; } if ( $this->theme_supports && ! current_theme_supports( ... (array) $this->theme_supports ) ) { return false; } return true; } /** * Multidimensional helper function. * * @since 3.4.0 * * @param array $root * @param array $keys * @param bool $create Default false. * @return array|void Keys are 'root', 'node', and 'key'. */ final protected function multidimensional( &$root, $keys, $create = false ) { if ( $create && empty( $root ) ) { $root = array(); } if ( ! isset( $root ) || empty( $keys ) ) { return; } $last = array_pop( $keys ); $node = &$root; foreach ( $keys as $key ) { if ( $create && ! isset( $node[ $key ] ) ) { $node[ $key ] = array(); } if ( ! is_array( $node ) || ! isset( $node[ $key ] ) ) { return; } $node = &$node[ $key ]; } if ( $create ) { if ( ! is_array( $node ) ) { // Account for an array overriding a string or object value. $node = array(); } if ( ! isset( $node[ $last ] ) ) { $node[ $last ] = array(); } } if ( ! isset( $node[ $last ] ) ) { return; } return array( 'root' => &$root, 'node' => &$node, 'key' => $last, ); } /** * Will attempt to replace a specific value in a multidimensional array. * * @since 3.4.0 * * @param array $root * @param array $keys * @param mixed $value The value to update. * @return mixed */ final protected function multidimensional_replace( $root, $keys, $value ) { if ( ! isset( $value ) ) { return $root; } elseif ( empty( $keys ) ) { // If there are no keys, we're replacing the root. return $value; } $result = $this->multidimensional( $root, $keys, true ); if ( isset( $result ) ) { $result['node'][ $result['key'] ] = $value; } return $root; } /** * Will attempt to fetch a specific value from a multidimensional array. * * @since 3.4.0 * * @param array $root * @param array $keys * @param mixed $default_value A default value which is used as a fallback. Default null. * @return mixed The requested value or the default value. */ final protected function multidimensional_get( $root, $keys, $default_value = null ) { if ( empty( $keys ) ) { // If there are no keys, test the root. return isset( $root ) ? $root : $default_value; } $result = $this->multidimensional( $root, $keys ); return isset( $result ) ? $result['node'][ $result['key'] ] : $default_value; } /** * Will attempt to check if a specific value in a multidimensional array is set. * * @since 3.4.0 * * @param array $root * @param array $keys * @return bool True if value is set, false if not. */ final protected function multidimensional_isset( $root, $keys ) { $result = $this->multidimensional_get( $root, $keys ); return isset( $result ); } } ``` | Used By | Description | | --- | --- | | [WP\_Customize\_Custom\_CSS\_Setting](wp_customize_custom_css_setting) wp-includes/customize/class-wp-customize-custom-css-setting.php | Custom Setting to handle WP Custom CSS. | | [WP\_Customize\_Nav\_Menu\_Setting](wp_customize_nav_menu_setting) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Customize Setting to represent a nav\_menu. | | [WP\_Customize\_Nav\_Menu\_Item\_Setting](wp_customize_nav_menu_item_setting) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Customize Setting to represent a nav\_menu. | | [WP\_Customize\_Filter\_Setting](wp_customize_filter_setting) wp-includes/customize/class-wp-customize-filter-setting.php | A setting that is used to filter a value, but will not save the results. | | [WP\_Customize\_Header\_Image\_Setting](wp_customize_header_image_setting) wp-includes/customize/class-wp-customize-header-image-setting.php | A setting that is used to filter a value, but will not save the results. | | [WP\_Customize\_Background\_Image\_Setting](wp_customize_background_image_setting) wp-includes/customize/class-wp-customize-background-image-setting.php | Customizer Background Image Setting class. | | Version | Description | | --- | --- | | [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
programming_docs
wordpress class WP_Users_List_Table {} class WP\_Users\_List\_Table {} =============================== Core class used to implement displaying users in a list table. * [WP\_List\_Table](wp_list_table) * [\_\_construct](wp_users_list_table/__construct) β€” Constructor. * [ajax\_user\_can](wp_users_list_table/ajax_user_can) β€” Check the current user's permissions. * [current\_action](wp_users_list_table/current_action) β€” Capture the bulk action required, and return it. * [display\_rows](wp_users_list_table/display_rows) β€” Generate the list table rows. * [extra\_tablenav](wp_users_list_table/extra_tablenav) β€” Output the controls to allow user roles to be changed in bulk. * [get\_bulk\_actions](wp_users_list_table/get_bulk_actions) β€” Retrieve an associative array of bulk actions available on this table. * [get\_columns](wp_users_list_table/get_columns) β€” Get a list of columns for the list table. * [get\_default\_primary\_column\_name](wp_users_list_table/get_default_primary_column_name) β€” Gets the name of the default primary column. * [get\_role\_list](wp_users_list_table/get_role_list) β€” Returns an array of translated user role names for a given user object. * [get\_sortable\_columns](wp_users_list_table/get_sortable_columns) β€” Get a list of sortable columns for the list table. * [get\_views](wp_users_list_table/get_views) β€” Return an associative array listing all the views that can be used with this table. * [no\_items](wp_users_list_table/no_items) β€” Output 'no users' message. * [prepare\_items](wp_users_list_table/prepare_items) β€” Prepare the users list for display. * [single\_row](wp_users_list_table/single_row) β€” Generate HTML for a single row on the users.php admin panel. 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/) ``` class WP_Users_List_Table extends WP_List_Table { /** * Site ID to generate the Users list table for. * * @since 3.1.0 * @var int */ public $site_id; /** * Whether or not the current Users list table is for Multisite. * * @since 3.1.0 * @var bool */ public $is_site_users; /** * Constructor. * * @since 3.1.0 * * @see WP_List_Table::__construct() for more information on default arguments. * * @param array $args An associative array of arguments. */ 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; } } /** * Check the current user's permissions. * * @since 3.1.0 * * @return bool */ public function ajax_user_can() { if ( $this->is_site_users ) { return current_user_can( 'manage_sites' ); } else { return current_user_can( 'list_users' ); } } /** * Prepare the users list for display. * * @since 3.1.0 * * @global string $role * @global string $usersearch */ 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, ) ); } /** * Output 'no users' message. * * @since 3.1.0 */ public function no_items() { _e( 'No users found.' ); } /** * 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. * * @since 3.1.0 * * @global string $role * * @return string[] An array of HTML links keyed by their view. */ 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 ); } /** * Retrieve an associative array of bulk actions available on this table. * * @since 3.1.0 * * @return array Array of bulk action labels keyed by their action. */ 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; } /** * Output the controls to allow user roles to be changed in bulk. * * @since 3.1.0 * * @param string $which Whether this is being invoked above ("top") * or below the table ("bottom"). */ 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&hellip;' ); ?></label> <select name="<?php echo $id; ?>" id="<?php echo $id; ?>"> <option value=""><?php _e( 'Change role to&hellip;' ); ?></option> <?php wp_dropdown_roles(); ?> <option value="none"><?php _e( '&mdash; No role for this site &mdash;' ); ?></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 ); } /** * Capture the bulk action required, and return it. * * Overridden from the base class implementation to capture * the role change drop-down. * * @since 3.1.0 * * @return string The bulk action required. */ public function current_action() { if ( isset( $_REQUEST['changeit'] ) && ! empty( $_REQUEST['new_role'] ) ) { return 'promote'; } return parent::current_action(); } /** * Get a list of columns for the list table. * * @since 3.1.0 * * @return string[] Array of column titles keyed by their column name. */ 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; } /** * Get a list of sortable columns for the list table. * * @since 3.1.0 * * @return array Array of sortable columns. */ protected function get_sortable_columns() { $columns = array( 'username' => 'login', 'email' => 'email', ); return $columns; } /** * Generate the list table rows. * * @since 3.1.0 */ 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 ); } } /** * Generate HTML for a single row on the users.php admin panel. * * @since 3.1.0 * @since 4.2.0 The `$style` parameter was deprecated. * @since 4.4.0 The `$role` parameter was deprecated. * * @param WP_User $user_object The current user object. * @param string $style Deprecated. Not used. * @param string $role Deprecated. Not used. * @param int $numposts Optional. Post count to display for this user. Defaults * to zero, as in, a new user has made zero posts. * @return string Output for a single row. */ 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}&amp;"; } 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 = ' &mdash; ' . __( '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&amp;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&amp;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&amp;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">&#8212;</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; } /** * Gets the name of the default primary column. * * @since 4.3.0 * * @return string Name of the default primary column, in this case, 'username'. */ protected function get_default_primary_column_name() { return 'username'; } /** * Returns an array of translated user role names for a given user object. * * @since 4.4.0 * * @param WP_User $user_object The WP_User object. * @return string[] An array of user role names keyed by role. */ 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 ); } } ``` | Uses | Description | | --- | --- | | [WP\_List\_Table](wp_list_table) wp-admin/includes/class-wp-list-table.php | Base class for displaying a list of items in an ajaxified HTML table. | | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
programming_docs
wordpress class Gettext_Translations {} class Gettext\_Translations {} ============================== * [gettext\_select\_plural\_form](gettext_translations/gettext_select_plural_form) β€” The gettext implementation of select\_plural\_form. * [make\_headers](gettext_translations/make_headers) * [make\_plural\_form\_function](gettext_translations/make_plural_form_function) β€” Makes a function, which will return the right translation index, according to the plural forms header * [nplurals\_and\_expression\_from\_header](gettext_translations/nplurals_and_expression_from_header) * [parenthesize\_plural\_exression](gettext_translations/parenthesize_plural_exression) β€” Adds parentheses to the inner parts of ternary operators in plural expressions, because PHP evaluates ternary oerators from left to right * [set\_header](gettext_translations/set_header) File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/) ``` class Gettext_Translations extends Translations { /** * Number of plural forms. * * @var int */ public $_nplurals; /** * Callback to retrieve the plural form. * * @var callable */ public $_gettext_select_plural_form; /** * The gettext implementation of select_plural_form. * * It lives in this class, because there are more than one descendand, which will use it and * they can't share it effectively. * * @param int $count */ public function gettext_select_plural_form( $count ) { if ( ! isset( $this->_gettext_select_plural_form ) || is_null( $this->_gettext_select_plural_form ) ) { list( $nplurals, $expression ) = $this->nplurals_and_expression_from_header( $this->get_header( 'Plural-Forms' ) ); $this->_nplurals = $nplurals; $this->_gettext_select_plural_form = $this->make_plural_form_function( $nplurals, $expression ); } return call_user_func( $this->_gettext_select_plural_form, $count ); } /** * @param string $header * @return array */ public function nplurals_and_expression_from_header( $header ) { if ( preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s+plural\s*=\s*(.+)$/', $header, $matches ) ) { $nplurals = (int) $matches[1]; $expression = trim( $matches[2] ); return array( $nplurals, $expression ); } else { return array( 2, 'n != 1' ); } } /** * Makes a function, which will return the right translation index, according to the * plural forms header * * @param int $nplurals * @param string $expression */ public function make_plural_form_function( $nplurals, $expression ) { try { $handler = new Plural_Forms( rtrim( $expression, ';' ) ); return array( $handler, 'get' ); } catch ( Exception $e ) { // Fall back to default plural-form function. return $this->make_plural_form_function( 2, 'n != 1' ); } } /** * Adds parentheses to the inner parts of ternary operators in * plural expressions, because PHP evaluates ternary oerators from left to right * * @param string $expression the expression without parentheses * @return string the expression with parentheses added */ public function parenthesize_plural_exression( $expression ) { $expression .= ';'; $res = ''; $depth = 0; for ( $i = 0; $i < strlen( $expression ); ++$i ) { $char = $expression[ $i ]; switch ( $char ) { case '?': $res .= ' ? ('; $depth++; break; case ':': $res .= ') : ('; break; case ';': $res .= str_repeat( ')', $depth ) . ';'; $depth = 0; break; default: $res .= $char; } } return rtrim( $res, ';' ); } /** * @param string $translation * @return array */ public function make_headers( $translation ) { $headers = array(); // Sometimes \n's are used instead of real new lines. $translation = str_replace( '\n', "\n", $translation ); $lines = explode( "\n", $translation ); foreach ( $lines as $line ) { $parts = explode( ':', $line, 2 ); if ( ! isset( $parts[1] ) ) { continue; } $headers[ trim( $parts[0] ) ] = trim( $parts[1] ); } return $headers; } /** * @param string $header * @param string $value */ public function set_header( $header, $value ) { parent::set_header( $header, $value ); if ( 'Plural-Forms' === $header ) { list( $nplurals, $expression ) = $this->nplurals_and_expression_from_header( $this->get_header( 'Plural-Forms' ) ); $this->_nplurals = $nplurals; $this->_gettext_select_plural_form = $this->make_plural_form_function( $nplurals, $expression ); } } } ``` | Uses | Description | | --- | --- | | [Translations](translations) wp-includes/pomo/translations.php | | | Used By | Description | | --- | --- | | [PO](po) wp-includes/pomo/po.php | | | [MO](mo) wp-includes/pomo/mo.php | | wordpress class WP_Rewrite {} class WP\_Rewrite {} ==================== Core class used to implement a rewrite component API. The WordPress Rewrite class writes the rewrite module rules to the .htaccess file. It also handles parsing the request to get the correct setup for the WordPress Query class. The Rewrite along with WP class function as a front controller for WordPress. You can add rules to trigger your page view and processing using this component. The full functionality of a front controller does not exist, meaning you can’t define how the template files load based on the rewrite rules. This document assumes familiarity with [Apache](http://httpd.apache.org)β€˜s [mod\_rewrite](http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html). If you’ve never heard of this before, try reading about [URL Rewriting](https://en.wikipedia.org/wiki/URL_Rewriting). Also see Otto’s explanation of [hierarchy of rewrite rules](http://lists.automattic.com/pipermail/wp-testers/2009-January/011110.html) in the wp-hackers email list. Please note that these rules are usually called inside the init hook. Furthermore, permalinks will need to be refreshed (you can do this in WP Admin under Settings -> Permalinks) before the rewrite changes will take effect. Requires one-time use of `flush_rules()` to take effect. [WP\_Rewrite](wp_rewrite) is WordPress’ class for managing the rewrite rules that allow you to use [Pretty Permalinks](https://wordpress.org/support/article/introduction-to-blogging/#pretty-permalinks "Introduction to Blogging") feature. It has several methods that generate the rewrite rules from values in the database. It is used internally when updating the rewrite rules, and also to find the URL of a specific post, Page, category archive, etc.. It’s defined in wp-includes/rewrite.php as a single instance global variable, $wp\_rewrite, is initialised in wp-settings.php. Try not to access or set the properties directly, instead use the methods to interact with the $wp\_rewrite object. See also [Rewrite API](https://developer.wordpress.org/apis/handbook/rewrite/ "Rewrite API"). $permalink\_structure The permalink structure as in the database. This is what you set on the Permalink Options page, and includes β€˜tags’ like %year%, %month% and %post\_id%. $category\_base Anything to be inserted before category archive URLs. Defaults to β€˜category/’. $category\_structure Structure for category archive URLs. This is just the $category\_base plus β€˜%category%’. $author\_base Anything to be inserted before author archive URLs. Defaults to β€˜author/’. $author\_structure Structure for author archive URLs. This is just the $author\_base plus β€˜%author%’. $pagination\_base Anything to be inserted before pagination indices. Defaults to β€˜page/’. $feeds Supported feeds names (rdf, rss, atom) Use [add\_feed](../functions/add_feed "Rewrite API/add feed") to override or add. $feed\_base Anything to be inserted before feed URLs. Defaults to β€˜feed/’. $feed\_structure Structure for feed URLs. This is just the $feed\_base plus β€˜%feed%’. $search\_base Anything to be inserted before searches. Defaults to β€˜search/’. $search\_structure Structure for search URLs. This is just the $search\_base plus β€˜%search%’. $comments\_base Anything to be inserted just before the $feed\_structure to get the latest comments feed. Defaults to β€˜comments’. $comments\_feed\_structure The structure for the latest comments feed. This is just $comments\_base plus $feed\_base plus β€˜%feed%’. $date\_structure Structure for dated archive URLs. Tries to be β€˜%year%/%monthnum%/%day%’, β€˜%day%/%monthnum%/%year%’ or β€˜%monthnum%/%day%/%year%’, but if none of these are detected in your $permalink\_structure, defaults to β€˜%year%/%monthnum%/%day%’. Various functions use this structure to obtain less specific structures: for example, get\_year\_permastruct() simply removes the β€˜%monthnum%’ and β€˜%day%’ tags from $date\_structure. $page\_structure Structure for Pages. Just β€˜%pagename%’. $front Anything up to the start of the first tag in your $permalink\_structure. $root The root of your WordPress install. Prepended to all structures. $matches Used internally when calculating back references for the redirect part of the rewrite rules. $rules The rewrite rules. Set when rewrite\_rules() is called. $non\_wp\_rules Associative array of β€œrules that don’t redirect to WP’s index.php (and thus shouldn’t be handled by WP at all)” roughly in the form `'Pattern' => 'Substitution'` (see below). $rewritecode An array of all the tags available for the permalink structure. See [Using Permalinks](https://wordpress.org/support/article/using-permalinks/ "Using Permalinks") for a list. $rewritereplace What each tag will be replaced with for the regex part of the rewrite rule. The first element in $rewritereplace is the regex for the first element in $rewritecode, the second corresponds to the second, and so on. $queryreplace What each tag will be replaced with in the rewrite part of the rewrite rule. The same correspondance applies here as with $rewritereplace. As the rewrite rules are a crucial part of your website’s functionality, WordPress allows plugins to hook into the generation process at several points. rewrite\_rules(), specifically, contains nine filters and one hook for really precise control over the rewrite rules process. Here’s what you can filter in rewrite\_rules(): * [post\_rewrite\_rules](../hooks/post_rewrite_rules "Plugin API/Filter Reference/post rewrite rules") – Used to filter the rewrite rules generated for permalink URLs. * [date\_rewrite\_rules](../hooks/date_rewrite_rules "Plugin API/Filter Reference/date rewrite rules") – Used to filter the rewrite rules generated for dated archive URLs. * [{$permastruct}\_rewrite\_rules](../hooks/permastructname_rewrite_rules "Plugin API/Filter Reference/$permastruct rewrite rules") – Can be used to filter permastructs like β€˜category’ or other taxonomies. * [search\_rewrite\_rules](../hooks/search_rewrite_rules "Plugin API/Filter Reference/search rewrite rules") – Used to filter the rewrite rules generated for search URLs. * [comments\_rewrite\_rules](../hooks/comments_rewrite_rules "Plugin API/Filter Reference/comments rewrite rules") – Used to filter the rewrite rules generated for the latest comment feed URLs. * [author\_rewrite\_rules](../hooks/author_rewrite_rules "Plugin API/Filter Reference/author rewrite rules") – Used to filter the rewrite rules generated for author archive URLs. * [page\_rewrite\_rules](../hooks/page_rewrite_rules "Plugin API/Filter Reference/page rewrite rules") – Used to filter the rewrite rules generated for your Pages. * [root\_rewrite\_rules](../hooks/root_rewrite_rules "Plugin API/Filter Reference/root rewrite rules") – Used to filter the rewrite rules generated for the root of your weblog. * [rewrite\_rules\_array](../hooks/rewrite_rules_array "Plugin API/Filter Reference/rewrite rules array") – Use to filter *all* the rewrite rules at once. * [generate\_rewrite\_rules](../hooks/generate_rewrite_rules "Plugin API/Action Reference/generate rewrite rules") – This action hook runs **after** all the rules have been created. If your function takes a parameter, it will be passed a [reference](http://www.php.net/manual/en/language.references.php) to the entire $wp\_rewrite object. mod\_rewrite\_rules() is the function that takes the array generated by rewrite\_rules() and actually turns it into a set of rewrite rules for the .htaccess file. This function also has a filter, mod\_rewrite\_rules, which will pass functions the string of all the rules to be written out to .htaccess, including the <IfModule> surrounding section. (Note: you may also see plugins using the rewrite\_rules hook, but this is deprecated). * [\_\_construct](wp_rewrite/__construct) β€” Constructor - Calls init(), which runs setup. * [add\_endpoint](wp_rewrite/add_endpoint) β€” Adds an endpoint, like /trackback/. * [add\_external\_rule](wp_rewrite/add_external_rule) β€” Adds a rewrite rule that doesn't correspond to index.php. * [add\_permastruct](wp_rewrite/add_permastruct) β€” Adds a new permalink structure. * [add\_rewrite\_tag](wp_rewrite/add_rewrite_tag) β€” Adds or updates existing rewrite tags (e.g. %postname%). * [add\_rule](wp_rewrite/add_rule) β€” Adds a rewrite rule that transforms a URL structure to a set of query vars. * [flush\_rules](wp_rewrite/flush_rules) β€” Removes rewrite rules and then recreate rewrite rules. * [generate\_rewrite\_rule](wp_rewrite/generate_rewrite_rule) β€” Generates rewrite rules with permalink structure and walking directory only. * [generate\_rewrite\_rules](wp_rewrite/generate_rewrite_rules) β€” Generates rewrite rules from a permalink structure. * [get\_author\_permastruct](wp_rewrite/get_author_permastruct) β€” Retrieves the author permalink structure. * [get\_category\_permastruct](wp_rewrite/get_category_permastruct) β€” Retrieves the permalink structure for categories. * [get\_comment\_feed\_permastruct](wp_rewrite/get_comment_feed_permastruct) β€” Retrieves the comment feed permalink structure. * [get\_date\_permastruct](wp_rewrite/get_date_permastruct) β€” Retrieves date permalink structure, with year, month, and day. * [get\_day\_permastruct](wp_rewrite/get_day_permastruct) β€” Retrieves the day permalink structure with month and year. * [get\_extra\_permastruct](wp_rewrite/get_extra_permastruct) β€” Retrieves an extra permalink structure by name. * [get\_feed\_permastruct](wp_rewrite/get_feed_permastruct) β€” Retrieves the feed permalink structure. * [get\_month\_permastruct](wp_rewrite/get_month_permastruct) β€” Retrieves the month permalink structure without day and with year. * [get\_page\_permastruct](wp_rewrite/get_page_permastruct) β€” Retrieves the page permalink structure. * [get\_search\_permastruct](wp_rewrite/get_search_permastruct) β€” Retrieves the search permalink structure. * [get\_tag\_permastruct](wp_rewrite/get_tag_permastruct) β€” Retrieves the permalink structure for tags. * [get\_year\_permastruct](wp_rewrite/get_year_permastruct) β€” Retrieves the year permalink structure without month and day. * [iis7\_url\_rewrite\_rules](wp_rewrite/iis7_url_rewrite_rules) β€” Retrieves IIS7 URL Rewrite formatted rewrite rules to write to web.config file. * [init](wp_rewrite/init) β€” Sets up the object's properties. * [mod\_rewrite\_rules](wp_rewrite/mod_rewrite_rules) β€” Retrieves mod\_rewrite-formatted rewrite rules to write to .htaccess. * [page\_rewrite\_rules](wp_rewrite/page_rewrite_rules) β€” Retrieves all of the rewrite rules for pages. * [page\_uri\_index](wp_rewrite/page_uri_index) β€” Retrieves all pages and attachments for pages URIs. * [preg\_index](wp_rewrite/preg_index) β€” Indexes for matches for usage in preg\_\*() functions. * [remove\_permastruct](wp_rewrite/remove_permastruct) β€” Removes a permalink structure. * [remove\_rewrite\_tag](wp_rewrite/remove_rewrite_tag) β€” Removes an existing rewrite tag. * [rewrite\_rules](wp_rewrite/rewrite_rules) β€” Constructs rewrite matches and queries from permalink structure. * [set\_category\_base](wp_rewrite/set_category_base) β€” Sets the category base for the category permalink. * [set\_permalink\_structure](wp_rewrite/set_permalink_structure) β€” Sets the main permalink structure for the site. * [set\_tag\_base](wp_rewrite/set_tag_base) β€” Sets the tag base for the tag permalink. * [using\_index\_permalinks](wp_rewrite/using_index_permalinks) β€” Determines whether permalinks are being used and rewrite module is not enabled. * [using\_mod\_rewrite\_permalinks](wp_rewrite/using_mod_rewrite_permalinks) β€” Determines whether permalinks are being used and rewrite module is enabled. * [using\_permalinks](wp_rewrite/using_permalinks) β€” Determines whether permalinks are being used. * [wp\_rewrite\_rules](wp_rewrite/wp_rewrite_rules) β€” Retrieves the rewrite rules. File: `wp-includes/class-wp-rewrite.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-rewrite.php/) ``` class WP_Rewrite { /** * Permalink structure for posts. * * @since 1.5.0 * @var string */ public $permalink_structure; /** * Whether to add trailing slashes. * * @since 2.2.0 * @var bool */ public $use_trailing_slashes; /** * Base for the author permalink structure (example.com/$author_base/authorname). * * @since 1.5.0 * @var string */ public $author_base = 'author'; /** * Permalink structure for author archives. * * @since 1.5.0 * @var string */ public $author_structure; /** * Permalink structure for date archives. * * @since 1.5.0 * @var string */ public $date_structure; /** * Permalink structure for pages. * * @since 1.5.0 * @var string */ public $page_structure; /** * Base of the search permalink structure (example.com/$search_base/query). * * @since 1.5.0 * @var string */ public $search_base = 'search'; /** * Permalink structure for searches. * * @since 1.5.0 * @var string */ public $search_structure; /** * Comments permalink base. * * @since 1.5.0 * @var string */ public $comments_base = 'comments'; /** * Pagination permalink base. * * @since 3.1.0 * @var string */ public $pagination_base = 'page'; /** * Comments pagination permalink base. * * @since 4.2.0 * @var string */ public $comments_pagination_base = 'comment-page'; /** * Feed permalink base. * * @since 1.5.0 * @var string */ public $feed_base = 'feed'; /** * Comments feed permalink structure. * * @since 1.5.0 * @var string */ public $comment_feed_structure; /** * Feed request permalink structure. * * @since 1.5.0 * @var string */ public $feed_structure; /** * The static portion of the post permalink structure. * * If the permalink structure is "/archive/%post_id%" then the front * is "/archive/". If the permalink structure is "/%year%/%postname%/" * then the front is "/". * * @since 1.5.0 * @var string * * @see WP_Rewrite::init() */ public $front; /** * The prefix for all permalink structures. * * If PATHINFO/index permalinks are in use then the root is the value of * `WP_Rewrite::$index` with a trailing slash appended. Otherwise the root * will be empty. * * @since 1.5.0 * @var string * * @see WP_Rewrite::init() * @see WP_Rewrite::using_index_permalinks() */ public $root = ''; /** * The name of the index file which is the entry point to all requests. * * @since 1.5.0 * @var string */ public $index = 'index.php'; /** * Variable name to use for regex matches in the rewritten query. * * @since 1.5.0 * @var string */ public $matches = ''; /** * Rewrite rules to match against the request to find the redirect or query. * * @since 1.5.0 * @var string[] */ public $rules; /** * Additional rules added external to the rewrite class. * * Those not generated by the class, see add_rewrite_rule(). * * @since 2.1.0 * @var string[] */ public $extra_rules = array(); /** * Additional rules that belong at the beginning to match first. * * Those not generated by the class, see add_rewrite_rule(). * * @since 2.3.0 * @var string[] */ public $extra_rules_top = array(); /** * Rules that don't redirect to WordPress' index.php. * * These rules are written to the mod_rewrite portion of the .htaccess, * and are added by add_external_rule(). * * @since 2.1.0 * @var string[] */ public $non_wp_rules = array(); /** * Extra permalink structures, e.g. categories, added by add_permastruct(). * * @since 2.1.0 * @var array[] */ public $extra_permastructs = array(); /** * Endpoints (like /trackback/) added by add_rewrite_endpoint(). * * @since 2.1.0 * @var array[] */ public $endpoints; /** * Whether to write every mod_rewrite rule for WordPress into the .htaccess file. * * This is off by default, turning it on might print a lot of rewrite rules * to the .htaccess file. * * @since 2.0.0 * @var bool * * @see WP_Rewrite::mod_rewrite_rules() */ public $use_verbose_rules = false; /** * Could post permalinks be confused with those of pages? * * If the first rewrite tag in the post permalink structure is one that could * also match a page name (e.g. %postname% or %author%) then this flag is * set to true. Prior to WordPress 3.3 this flag indicated that every page * would have a set of rules added to the top of the rewrite rules array. * Now it tells WP::parse_request() to check if a URL matching the page * permastruct is actually a page before accepting it. * * @since 2.5.0 * @var bool * * @see WP_Rewrite::init() */ public $use_verbose_page_rules = true; /** * Rewrite tags that can be used in permalink structures. * * These are translated into the regular expressions stored in * `WP_Rewrite::$rewritereplace` and are rewritten to the query * variables listed in WP_Rewrite::$queryreplace. * * Additional tags can be added with add_rewrite_tag(). * * @since 1.5.0 * @var string[] */ public $rewritecode = array( '%year%', '%monthnum%', '%day%', '%hour%', '%minute%', '%second%', '%postname%', '%post_id%', '%author%', '%pagename%', '%search%', ); /** * Regular expressions to be substituted into rewrite rules in place * of rewrite tags, see WP_Rewrite::$rewritecode. * * @since 1.5.0 * @var string[] */ public $rewritereplace = array( '([0-9]{4})', '([0-9]{1,2})', '([0-9]{1,2})', '([0-9]{1,2})', '([0-9]{1,2})', '([0-9]{1,2})', '([^/]+)', '([0-9]+)', '([^/]+)', '([^/]+?)', '(.+)', ); /** * Query variables that rewrite tags map to, see WP_Rewrite::$rewritecode. * * @since 1.5.0 * @var string[] */ public $queryreplace = array( 'year=', 'monthnum=', 'day=', 'hour=', 'minute=', 'second=', 'name=', 'p=', 'author_name=', 'pagename=', 's=', ); /** * Supported default feeds. * * @since 1.5.0 * @var string[] */ public $feeds = array( 'feed', 'rdf', 'rss', 'rss2', 'atom' ); /** * Determines whether permalinks are being used. * * This can be either rewrite module or permalink in the HTTP query string. * * @since 1.5.0 * * @return bool True, if permalinks are enabled. */ public function using_permalinks() { return ! empty( $this->permalink_structure ); } /** * Determines whether permalinks are being used and rewrite module is not enabled. * * Means that permalink links are enabled and index.php is in the URL. * * @since 1.5.0 * * @return bool Whether permalink links are enabled and index.php is in the URL. */ public function using_index_permalinks() { if ( empty( $this->permalink_structure ) ) { return false; } // If the index is not in the permalink, we're using mod_rewrite. return preg_match( '#^/*' . $this->index . '#', $this->permalink_structure ); } /** * Determines whether permalinks are being used and rewrite module is enabled. * * Using permalinks and index.php is not in the URL. * * @since 1.5.0 * * @return bool Whether permalink links are enabled and index.php is NOT in the URL. */ public function using_mod_rewrite_permalinks() { return $this->using_permalinks() && ! $this->using_index_permalinks(); } /** * Indexes for matches for usage in preg_*() functions. * * The format of the string is, with empty matches property value, '$NUM'. * The 'NUM' will be replaced with the value in the $number parameter. With * the matches property not empty, the value of the returned string will * contain that value of the matches property. The format then will be * '$MATCHES[NUM]', with MATCHES as the value in the property and NUM the * value of the $number parameter. * * @since 1.5.0 * * @param int $number Index number. * @return string */ public function preg_index( $number ) { $match_prefix = '$'; $match_suffix = ''; if ( ! empty( $this->matches ) ) { $match_prefix = '$' . $this->matches . '['; $match_suffix = ']'; } return "$match_prefix$number$match_suffix"; } /** * Retrieves all pages and attachments for pages URIs. * * The attachments are for those that have pages as parents and will be * retrieved. * * @since 2.5.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @return array Array of page URIs as first element and attachment URIs as second element. */ public function page_uri_index() { global $wpdb; // Get pages in order of hierarchy, i.e. children after parents. $pages = $wpdb->get_results( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'page' AND post_status != 'auto-draft'" ); $posts = get_page_hierarchy( $pages ); // If we have no pages get out quick. if ( ! $posts ) { return array( array(), array() ); } // Now reverse it, because we need parents after children for rewrite rules to work properly. $posts = array_reverse( $posts, true ); $page_uris = array(); $page_attachment_uris = array(); foreach ( $posts as $id => $post ) { // URL => page name. $uri = get_page_uri( $id ); $attachments = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'attachment' AND post_parent = %d", $id ) ); if ( ! empty( $attachments ) ) { foreach ( $attachments as $attachment ) { $attach_uri = get_page_uri( $attachment->ID ); $page_attachment_uris[ $attach_uri ] = $attachment->ID; } } $page_uris[ $uri ] = $id; } return array( $page_uris, $page_attachment_uris ); } /** * Retrieves all of the rewrite rules for pages. * * @since 1.5.0 * * @return string[] Page rewrite rules. */ public function page_rewrite_rules() { // The extra .? at the beginning prevents clashes with other regular expressions in the rules array. $this->add_rewrite_tag( '%pagename%', '(.?.+?)', 'pagename=' ); return $this->generate_rewrite_rules( $this->get_page_permastruct(), EP_PAGES, true, true, false, false ); } /** * Retrieves date permalink structure, with year, month, and day. * * The permalink structure for the date, if not set already depends on the * permalink structure. It can be one of three formats. The first is year, * month, day; the second is day, month, year; and the last format is month, * day, year. These are matched against the permalink structure for which * one is used. If none matches, then the default will be used, which is * year, month, day. * * Prevents post ID and date permalinks from overlapping. In the case of * post_id, the date permalink will be prepended with front permalink with * 'date/' before the actual permalink to form the complete date permalink * structure. * * @since 1.5.0 * * @return string|false Date permalink structure on success, false on failure. */ public function get_date_permastruct() { if ( isset( $this->date_structure ) ) { return $this->date_structure; } if ( empty( $this->permalink_structure ) ) { $this->date_structure = ''; return false; } // The date permalink must have year, month, and day separated by slashes. $endians = array( '%year%/%monthnum%/%day%', '%day%/%monthnum%/%year%', '%monthnum%/%day%/%year%' ); $this->date_structure = ''; $date_endian = ''; foreach ( $endians as $endian ) { if ( false !== strpos( $this->permalink_structure, $endian ) ) { $date_endian = $endian; break; } } if ( empty( $date_endian ) ) { $date_endian = '%year%/%monthnum%/%day%'; } /* * Do not allow the date tags and %post_id% to overlap in the permalink * structure. If they do, move the date tags to $front/date/. */ $front = $this->front; preg_match_all( '/%.+?%/', $this->permalink_structure, $tokens ); $tok_index = 1; foreach ( (array) $tokens[0] as $token ) { if ( '%post_id%' === $token && ( $tok_index <= 3 ) ) { $front = $front . 'date/'; break; } $tok_index++; } $this->date_structure = $front . $date_endian; return $this->date_structure; } /** * Retrieves the year permalink structure without month and day. * * Gets the date permalink structure and strips out the month and day * permalink structures. * * @since 1.5.0 * * @return string|false Year permalink structure on success, false on failure. */ public function get_year_permastruct() { $structure = $this->get_date_permastruct(); if ( empty( $structure ) ) { return false; } $structure = str_replace( '%monthnum%', '', $structure ); $structure = str_replace( '%day%', '', $structure ); $structure = preg_replace( '#/+#', '/', $structure ); return $structure; } /** * Retrieves the month permalink structure without day and with year. * * Gets the date permalink structure and strips out the day permalink * structures. Keeps the year permalink structure. * * @since 1.5.0 * * @return string|false Year/Month permalink structure on success, false on failure. */ public function get_month_permastruct() { $structure = $this->get_date_permastruct(); if ( empty( $structure ) ) { return false; } $structure = str_replace( '%day%', '', $structure ); $structure = preg_replace( '#/+#', '/', $structure ); return $structure; } /** * Retrieves the day permalink structure with month and year. * * Keeps date permalink structure with all year, month, and day. * * @since 1.5.0 * * @return string|false Year/Month/Day permalink structure on success, false on failure. */ public function get_day_permastruct() { return $this->get_date_permastruct(); } /** * Retrieves the permalink structure for categories. * * If the category_base property has no value, then the category structure * will have the front property value, followed by 'category', and finally * '%category%'. If it does, then the root property will be used, along with * the category_base property value. * * @since 1.5.0 * * @return string|false Category permalink structure on success, false on failure. */ public function get_category_permastruct() { return $this->get_extra_permastruct( 'category' ); } /** * Retrieves the permalink structure for tags. * * If the tag_base property has no value, then the tag structure will have * the front property value, followed by 'tag', and finally '%tag%'. If it * does, then the root property will be used, along with the tag_base * property value. * * @since 2.3.0 * * @return string|false Tag permalink structure on success, false on failure. */ public function get_tag_permastruct() { return $this->get_extra_permastruct( 'post_tag' ); } /** * Retrieves an extra permalink structure by name. * * @since 2.5.0 * * @param string $name Permalink structure name. * @return string|false Permalink structure string on success, false on failure. */ public function get_extra_permastruct( $name ) { if ( empty( $this->permalink_structure ) ) { return false; } if ( isset( $this->extra_permastructs[ $name ] ) ) { return $this->extra_permastructs[ $name ]['struct']; } return false; } /** * Retrieves the author permalink structure. * * The permalink structure is front property, author base, and finally * '/%author%'. Will set the author_structure property and then return it * without attempting to set the value again. * * @since 1.5.0 * * @return string|false Author permalink structure on success, false on failure. */ public function get_author_permastruct() { if ( isset( $this->author_structure ) ) { return $this->author_structure; } if ( empty( $this->permalink_structure ) ) { $this->author_structure = ''; return false; } $this->author_structure = $this->front . $this->author_base . '/%author%'; return $this->author_structure; } /** * Retrieves the search permalink structure. * * The permalink structure is root property, search base, and finally * '/%search%'. Will set the search_structure property and then return it * without attempting to set the value again. * * @since 1.5.0 * * @return string|false Search permalink structure on success, false on failure. */ public function get_search_permastruct() { if ( isset( $this->search_structure ) ) { return $this->search_structure; } if ( empty( $this->permalink_structure ) ) { $this->search_structure = ''; return false; } $this->search_structure = $this->root . $this->search_base . '/%search%'; return $this->search_structure; } /** * Retrieves the page permalink structure. * * The permalink structure is root property, and '%pagename%'. Will set the * page_structure property and then return it without attempting to set the * value again. * * @since 1.5.0 * * @return string|false Page permalink structure on success, false on failure. */ public function get_page_permastruct() { if ( isset( $this->page_structure ) ) { return $this->page_structure; } if ( empty( $this->permalink_structure ) ) { $this->page_structure = ''; return false; } $this->page_structure = $this->root . '%pagename%'; return $this->page_structure; } /** * Retrieves the feed permalink structure. * * The permalink structure is root property, feed base, and finally * '/%feed%'. Will set the feed_structure property and then return it * without attempting to set the value again. * * @since 1.5.0 * * @return string|false Feed permalink structure on success, false on failure. */ public function get_feed_permastruct() { if ( isset( $this->feed_structure ) ) { return $this->feed_structure; } if ( empty( $this->permalink_structure ) ) { $this->feed_structure = ''; return false; } $this->feed_structure = $this->root . $this->feed_base . '/%feed%'; return $this->feed_structure; } /** * Retrieves the comment feed permalink structure. * * The permalink structure is root property, comment base property, feed * base and finally '/%feed%'. Will set the comment_feed_structure property * and then return it without attempting to set the value again. * * @since 1.5.0 * * @return string|false Comment feed permalink structure on success, false on failure. */ public function get_comment_feed_permastruct() { if ( isset( $this->comment_feed_structure ) ) { return $this->comment_feed_structure; } if ( empty( $this->permalink_structure ) ) { $this->comment_feed_structure = ''; return false; } $this->comment_feed_structure = $this->root . $this->comments_base . '/' . $this->feed_base . '/%feed%'; return $this->comment_feed_structure; } /** * Adds or updates existing rewrite tags (e.g. %postname%). * * If the tag already exists, replace the existing pattern and query for * that tag, otherwise add the new tag. * * @since 1.5.0 * * @see WP_Rewrite::$rewritecode * @see WP_Rewrite::$rewritereplace * @see WP_Rewrite::$queryreplace * * @param string $tag Name of the rewrite tag to add or update. * @param string $regex Regular expression to substitute the tag for in rewrite rules. * @param string $query String to append to the rewritten query. Must end in '='. */ public function add_rewrite_tag( $tag, $regex, $query ) { $position = array_search( $tag, $this->rewritecode, true ); if ( false !== $position && null !== $position ) { $this->rewritereplace[ $position ] = $regex; $this->queryreplace[ $position ] = $query; } else { $this->rewritecode[] = $tag; $this->rewritereplace[] = $regex; $this->queryreplace[] = $query; } } /** * Removes an existing rewrite tag. * * @since 4.5.0 * * @see WP_Rewrite::$rewritecode * @see WP_Rewrite::$rewritereplace * @see WP_Rewrite::$queryreplace * * @param string $tag Name of the rewrite tag to remove. */ public function remove_rewrite_tag( $tag ) { $position = array_search( $tag, $this->rewritecode, true ); if ( false !== $position && null !== $position ) { unset( $this->rewritecode[ $position ] ); unset( $this->rewritereplace[ $position ] ); unset( $this->queryreplace[ $position ] ); } } /** * Generates rewrite rules from a permalink structure. * * The main WP_Rewrite function for building the rewrite rule list. The * contents of the function is a mix of black magic and regular expressions, * so best just ignore the contents and move to the parameters. * * @since 1.5.0 * * @param string $permalink_structure The permalink structure. * @param int $ep_mask Optional. Endpoint mask defining what endpoints are added to the structure. * Accepts a mask of: * - `EP_ALL` * - `EP_NONE` * - `EP_ALL_ARCHIVES` * - `EP_ATTACHMENT` * - `EP_AUTHORS` * - `EP_CATEGORIES` * - `EP_COMMENTS` * - `EP_DATE` * - `EP_DAY` * - `EP_MONTH` * - `EP_PAGES` * - `EP_PERMALINK` * - `EP_ROOT` * - `EP_SEARCH` * - `EP_TAGS` * - `EP_YEAR` * Default `EP_NONE`. * @param bool $paged Optional. Whether archive pagination rules should be added for the structure. * Default true. * @param bool $feed Optional. Whether feed rewrite rules should be added for the structure. * Default true. * @param bool $forcomments Optional. Whether the feed rules should be a query for a comments feed. * Default false. * @param bool $walk_dirs Optional. Whether the 'directories' making up the structure should be walked * over and rewrite rules built for each in-turn. Default true. * @param bool $endpoints Optional. Whether endpoints should be applied to the generated rewrite rules. * Default true. * @return string[] Array of rewrite rules keyed by their regex pattern. */ public function generate_rewrite_rules( $permalink_structure, $ep_mask = EP_NONE, $paged = true, $feed = true, $forcomments = false, $walk_dirs = true, $endpoints = true ) { // Build a regex to match the feed section of URLs, something like (feed|atom|rss|rss2)/? $feedregex2 = ''; foreach ( (array) $this->feeds as $feed_name ) { $feedregex2 .= $feed_name . '|'; } $feedregex2 = '(' . trim( $feedregex2, '|' ) . ')/?$'; /* * $feedregex is identical but with /feed/ added on as well, so URLs like <permalink>/feed/atom * and <permalink>/atom are both possible */ $feedregex = $this->feed_base . '/' . $feedregex2; // Build a regex to match the trackback and page/xx parts of URLs. $trackbackregex = 'trackback/?$'; $pageregex = $this->pagination_base . '/?([0-9]{1,})/?$'; $commentregex = $this->comments_pagination_base . '-([0-9]{1,})/?$'; $embedregex = 'embed/?$'; // Build up an array of endpoint regexes to append => queries to append. if ( $endpoints ) { $ep_query_append = array(); foreach ( (array) $this->endpoints as $endpoint ) { // Match everything after the endpoint name, but allow for nothing to appear there. $epmatch = $endpoint[1] . '(/(.*))?/?$'; // This will be appended on to the rest of the query for each dir. $epquery = '&' . $endpoint[2] . '='; $ep_query_append[ $epmatch ] = array( $endpoint[0], $epquery ); } } // Get everything up to the first rewrite tag. $front = substr( $permalink_structure, 0, strpos( $permalink_structure, '%' ) ); // Build an array of the tags (note that said array ends up being in $tokens[0]). preg_match_all( '/%.+?%/', $permalink_structure, $tokens ); $num_tokens = count( $tokens[0] ); $index = $this->index; // Probably 'index.php'. $feedindex = $index; $trackbackindex = $index; $embedindex = $index; /* * Build a list from the rewritecode and queryreplace arrays, that will look something * like tagname=$matches[i] where i is the current $i. */ $queries = array(); for ( $i = 0; $i < $num_tokens; ++$i ) { if ( 0 < $i ) { $queries[ $i ] = $queries[ $i - 1 ] . '&'; } else { $queries[ $i ] = ''; } $query_token = str_replace( $this->rewritecode, $this->queryreplace, $tokens[0][ $i ] ) . $this->preg_index( $i + 1 ); $queries[ $i ] .= $query_token; } // Get the structure, minus any cruft (stuff that isn't tags) at the front. $structure = $permalink_structure; if ( '/' !== $front ) { $structure = str_replace( $front, '', $structure ); } /* * Create a list of dirs to walk over, making rewrite rules for each level * so for example, a $structure of /%year%/%monthnum%/%postname% would create * rewrite rules for /%year%/, /%year%/%monthnum%/ and /%year%/%monthnum%/%postname% */ $structure = trim( $structure, '/' ); $dirs = $walk_dirs ? explode( '/', $structure ) : array( $structure ); $num_dirs = count( $dirs ); // Strip slashes from the front of $front. $front = preg_replace( '|^/+|', '', $front ); // The main workhorse loop. $post_rewrite = array(); $struct = $front; for ( $j = 0; $j < $num_dirs; ++$j ) { // Get the struct for this dir, and trim slashes off the front. $struct .= $dirs[ $j ] . '/'; // Accumulate. see comment near explode('/', $structure) above. $struct = ltrim( $struct, '/' ); // Replace tags with regexes. $match = str_replace( $this->rewritecode, $this->rewritereplace, $struct ); // Make a list of tags, and store how many there are in $num_toks. $num_toks = preg_match_all( '/%.+?%/', $struct, $toks ); // Get the 'tagname=$matches[i]'. $query = ( ! empty( $num_toks ) && isset( $queries[ $num_toks - 1 ] ) ) ? $queries[ $num_toks - 1 ] : ''; // Set up $ep_mask_specific which is used to match more specific URL types. switch ( $dirs[ $j ] ) { case '%year%': $ep_mask_specific = EP_YEAR; break; case '%monthnum%': $ep_mask_specific = EP_MONTH; break; case '%day%': $ep_mask_specific = EP_DAY; break; default: $ep_mask_specific = EP_NONE; } // Create query for /page/xx. $pagematch = $match . $pageregex; $pagequery = $index . '?' . $query . '&paged=' . $this->preg_index( $num_toks + 1 ); // Create query for /comment-page-xx. $commentmatch = $match . $commentregex; $commentquery = $index . '?' . $query . '&cpage=' . $this->preg_index( $num_toks + 1 ); if ( get_option( 'page_on_front' ) ) { // Create query for Root /comment-page-xx. $rootcommentmatch = $match . $commentregex; $rootcommentquery = $index . '?' . $query . '&page_id=' . get_option( 'page_on_front' ) . '&cpage=' . $this->preg_index( $num_toks + 1 ); } // Create query for /feed/(feed|atom|rss|rss2|rdf). $feedmatch = $match . $feedregex; $feedquery = $feedindex . '?' . $query . '&feed=' . $this->preg_index( $num_toks + 1 ); // Create query for /(feed|atom|rss|rss2|rdf) (see comment near creation of $feedregex). $feedmatch2 = $match . $feedregex2; $feedquery2 = $feedindex . '?' . $query . '&feed=' . $this->preg_index( $num_toks + 1 ); // Create query and regex for embeds. $embedmatch = $match . $embedregex; $embedquery = $embedindex . '?' . $query . '&embed=true'; // If asked to, turn the feed queries into comment feed ones. if ( $forcomments ) { $feedquery .= '&withcomments=1'; $feedquery2 .= '&withcomments=1'; } // Start creating the array of rewrites for this dir. $rewrite = array(); // ...adding on /feed/ regexes => queries. if ( $feed ) { $rewrite = array( $feedmatch => $feedquery, $feedmatch2 => $feedquery2, $embedmatch => $embedquery, ); } // ...and /page/xx ones. if ( $paged ) { $rewrite = array_merge( $rewrite, array( $pagematch => $pagequery ) ); } // Only on pages with comments add ../comment-page-xx/. if ( EP_PAGES & $ep_mask || EP_PERMALINK & $ep_mask ) { $rewrite = array_merge( $rewrite, array( $commentmatch => $commentquery ) ); } elseif ( EP_ROOT & $ep_mask && get_option( 'page_on_front' ) ) { $rewrite = array_merge( $rewrite, array( $rootcommentmatch => $rootcommentquery ) ); } // Do endpoints. if ( $endpoints ) { foreach ( (array) $ep_query_append as $regex => $ep ) { // Add the endpoints on if the mask fits. if ( $ep[0] & $ep_mask || $ep[0] & $ep_mask_specific ) { $rewrite[ $match . $regex ] = $index . '?' . $query . $ep[1] . $this->preg_index( $num_toks + 2 ); } } } // If we've got some tags in this dir. if ( $num_toks ) { $post = false; $page = false; /* * Check to see if this dir is permalink-level: i.e. the structure specifies an * individual post. Do this by checking it contains at least one of 1) post name, * 2) post ID, 3) page name, 4) timestamp (year, month, day, hour, second and * minute all present). Set these flags now as we need them for the endpoints. */ if ( strpos( $struct, '%postname%' ) !== false || strpos( $struct, '%post_id%' ) !== false || strpos( $struct, '%pagename%' ) !== false || ( strpos( $struct, '%year%' ) !== false && strpos( $struct, '%monthnum%' ) !== false && strpos( $struct, '%day%' ) !== false && strpos( $struct, '%hour%' ) !== false && strpos( $struct, '%minute%' ) !== false && strpos( $struct, '%second%' ) !== false ) ) { $post = true; if ( strpos( $struct, '%pagename%' ) !== false ) { $page = true; } } if ( ! $post ) { // For custom post types, we need to add on endpoints as well. foreach ( get_post_types( array( '_builtin' => false ) ) as $ptype ) { if ( strpos( $struct, "%$ptype%" ) !== false ) { $post = true; // This is for page style attachment URLs. $page = is_post_type_hierarchical( $ptype ); break; } } } // If creating rules for a permalink, do all the endpoints like attachments etc. if ( $post ) { // Create query and regex for trackback. $trackbackmatch = $match . $trackbackregex; $trackbackquery = $trackbackindex . '?' . $query . '&tb=1'; // Create query and regex for embeds. $embedmatch = $match . $embedregex; $embedquery = $embedindex . '?' . $query . '&embed=true'; // Trim slashes from the end of the regex for this dir. $match = rtrim( $match, '/' ); // Get rid of brackets. $submatchbase = str_replace( array( '(', ')' ), '', $match ); // Add a rule for at attachments, which take the form of <permalink>/some-text. $sub1 = $submatchbase . '/([^/]+)/'; // Add trackback regex <permalink>/trackback/... $sub1tb = $sub1 . $trackbackregex; // And <permalink>/feed/(atom|...) $sub1feed = $sub1 . $feedregex; // And <permalink>/(feed|atom...) $sub1feed2 = $sub1 . $feedregex2; // And <permalink>/comment-page-xx $sub1comment = $sub1 . $commentregex; // And <permalink>/embed/... $sub1embed = $sub1 . $embedregex; /* * Add another rule to match attachments in the explicit form: * <permalink>/attachment/some-text */ $sub2 = $submatchbase . '/attachment/([^/]+)/'; // And add trackbacks <permalink>/attachment/trackback. $sub2tb = $sub2 . $trackbackregex; // Feeds, <permalink>/attachment/feed/(atom|...) $sub2feed = $sub2 . $feedregex; // And feeds again on to this <permalink>/attachment/(feed|atom...) $sub2feed2 = $sub2 . $feedregex2; // And <permalink>/comment-page-xx $sub2comment = $sub2 . $commentregex; // And <permalink>/embed/... $sub2embed = $sub2 . $embedregex; // Create queries for these extra tag-ons we've just dealt with. $subquery = $index . '?attachment=' . $this->preg_index( 1 ); $subtbquery = $subquery . '&tb=1'; $subfeedquery = $subquery . '&feed=' . $this->preg_index( 2 ); $subcommentquery = $subquery . '&cpage=' . $this->preg_index( 2 ); $subembedquery = $subquery . '&embed=true'; // Do endpoints for attachments. if ( ! empty( $endpoints ) ) { foreach ( (array) $ep_query_append as $regex => $ep ) { if ( $ep[0] & EP_ATTACHMENT ) { $rewrite[ $sub1 . $regex ] = $subquery . $ep[1] . $this->preg_index( 3 ); $rewrite[ $sub2 . $regex ] = $subquery . $ep[1] . $this->preg_index( 3 ); } } } /* * Now we've finished with endpoints, finish off the $sub1 and $sub2 matches * add a ? as we don't have to match that last slash, and finally a $ so we * match to the end of the URL */ $sub1 .= '?$'; $sub2 .= '?$'; /* * Post pagination, e.g. <permalink>/2/ * Previously: '(/[0-9]+)?/?$', which produced '/2' for page. * When cast to int, returned 0. */ $match = $match . '(?:/([0-9]+))?/?$'; $query = $index . '?' . $query . '&page=' . $this->preg_index( $num_toks + 1 ); // Not matching a permalink so this is a lot simpler. } else { // Close the match and finalize the query. $match .= '?$'; $query = $index . '?' . $query; } /* * Create the final array for this dir by joining the $rewrite array (which currently * only contains rules/queries for trackback, pages etc) to the main regex/query for * this dir */ $rewrite = array_merge( $rewrite, array( $match => $query ) ); // If we're matching a permalink, add those extras (attachments etc) on. if ( $post ) { // Add trackback. $rewrite = array_merge( array( $trackbackmatch => $trackbackquery ), $rewrite ); // Add embed. $rewrite = array_merge( array( $embedmatch => $embedquery ), $rewrite ); // Add regexes/queries for attachments, attachment trackbacks and so on. if ( ! $page ) { // Require <permalink>/attachment/stuff form for pages because of confusion with subpages. $rewrite = array_merge( $rewrite, array( $sub1 => $subquery, $sub1tb => $subtbquery, $sub1feed => $subfeedquery, $sub1feed2 => $subfeedquery, $sub1comment => $subcommentquery, $sub1embed => $subembedquery, ) ); } $rewrite = array_merge( array( $sub2 => $subquery, $sub2tb => $subtbquery, $sub2feed => $subfeedquery, $sub2feed2 => $subfeedquery, $sub2comment => $subcommentquery, $sub2embed => $subembedquery, ), $rewrite ); } } // Add the rules for this dir to the accumulating $post_rewrite. $post_rewrite = array_merge( $rewrite, $post_rewrite ); } // The finished rules. phew! return $post_rewrite; } /** * Generates rewrite rules with permalink structure and walking directory only. * * Shorten version of WP_Rewrite::generate_rewrite_rules() that allows for shorter * list of parameters. See the method for longer description of what generating * rewrite rules does. * * @since 1.5.0 * * @see WP_Rewrite::generate_rewrite_rules() See for long description and rest of parameters. * * @param string $permalink_structure The permalink structure to generate rules. * @param bool $walk_dirs Optional. Whether to create list of directories to walk over. * Default false. * @return array An array of rewrite rules keyed by their regex pattern. */ public function generate_rewrite_rule( $permalink_structure, $walk_dirs = false ) { return $this->generate_rewrite_rules( $permalink_structure, EP_NONE, false, false, false, $walk_dirs ); } /** * Constructs rewrite matches and queries from permalink structure. * * Runs the action {@see 'generate_rewrite_rules'} with the parameter that is an * reference to the current WP_Rewrite instance to further manipulate the * permalink structures and rewrite rules. Runs the {@see 'rewrite_rules_array'} * filter on the full rewrite rule array. * * There are two ways to manipulate the rewrite rules, one by hooking into * the {@see 'generate_rewrite_rules'} action and gaining full control of the * object or just manipulating the rewrite rule array before it is passed * from the function. * * @since 1.5.0 * * @return string[] An associative array of matches and queries. */ public function rewrite_rules() { $rewrite = array(); if ( empty( $this->permalink_structure ) ) { return $rewrite; } // robots.txt -- only if installed at the root. $home_path = parse_url( home_url() ); $robots_rewrite = ( empty( $home_path['path'] ) || '/' === $home_path['path'] ) ? array( 'robots\.txt$' => $this->index . '?robots=1' ) : array(); // favicon.ico -- only if installed at the root. $favicon_rewrite = ( empty( $home_path['path'] ) || '/' === $home_path['path'] ) ? array( 'favicon\.ico$' => $this->index . '?favicon=1' ) : array(); // Old feed and service files. $deprecated_files = array( '.*wp-(atom|rdf|rss|rss2|feed|commentsrss2)\.php$' => $this->index . '?feed=old', '.*wp-app\.php(/.*)?$' => $this->index . '?error=403', ); // Registration rules. $registration_pages = array(); if ( is_multisite() && is_main_site() ) { $registration_pages['.*wp-signup.php$'] = $this->index . '?signup=true'; $registration_pages['.*wp-activate.php$'] = $this->index . '?activate=true'; } // Deprecated. $registration_pages['.*wp-register.php$'] = $this->index . '?register=true'; // Post rewrite rules. $post_rewrite = $this->generate_rewrite_rules( $this->permalink_structure, EP_PERMALINK ); /** * Filters rewrite rules used for "post" archives. * * @since 1.5.0 * * @param string[] $post_rewrite Array of rewrite rules for posts, keyed by their regex pattern. */ $post_rewrite = apply_filters( 'post_rewrite_rules', $post_rewrite ); // Date rewrite rules. $date_rewrite = $this->generate_rewrite_rules( $this->get_date_permastruct(), EP_DATE ); /** * Filters rewrite rules used for date archives. * * Likely date archives would include `/yyyy/`, `/yyyy/mm/`, and `/yyyy/mm/dd/`. * * @since 1.5.0 * * @param string[] $date_rewrite Array of rewrite rules for date archives, keyed by their regex pattern. */ $date_rewrite = apply_filters( 'date_rewrite_rules', $date_rewrite ); // Root-level rewrite rules. $root_rewrite = $this->generate_rewrite_rules( $this->root . '/', EP_ROOT ); /** * Filters rewrite rules used for root-level archives. * * Likely root-level archives would include pagination rules for the homepage * as well as site-wide post feeds (e.g. `/feed/`, and `/feed/atom/`). * * @since 1.5.0 * * @param string[] $root_rewrite Array of root-level rewrite rules, keyed by their regex pattern. */ $root_rewrite = apply_filters( 'root_rewrite_rules', $root_rewrite ); // Comments rewrite rules. $comments_rewrite = $this->generate_rewrite_rules( $this->root . $this->comments_base, EP_COMMENTS, false, true, true, false ); /** * Filters rewrite rules used for comment feed archives. * * Likely comments feed archives include `/comments/feed/` and `/comments/feed/atom/`. * * @since 1.5.0 * * @param string[] $comments_rewrite Array of rewrite rules for the site-wide comments feeds, keyed by their regex pattern. */ $comments_rewrite = apply_filters( 'comments_rewrite_rules', $comments_rewrite ); // Search rewrite rules. $search_structure = $this->get_search_permastruct(); $search_rewrite = $this->generate_rewrite_rules( $search_structure, EP_SEARCH ); /** * Filters rewrite rules used for search archives. * * Likely search-related archives include `/search/search+query/` as well as * pagination and feed paths for a search. * * @since 1.5.0 * * @param string[] $search_rewrite Array of rewrite rules for search queries, keyed by their regex pattern. */ $search_rewrite = apply_filters( 'search_rewrite_rules', $search_rewrite ); // Author rewrite rules. $author_rewrite = $this->generate_rewrite_rules( $this->get_author_permastruct(), EP_AUTHORS ); /** * Filters rewrite rules used for author archives. * * Likely author archives would include `/author/author-name/`, as well as * pagination and feed paths for author archives. * * @since 1.5.0 * * @param string[] $author_rewrite Array of rewrite rules for author archives, keyed by their regex pattern. */ $author_rewrite = apply_filters( 'author_rewrite_rules', $author_rewrite ); // Pages rewrite rules. $page_rewrite = $this->page_rewrite_rules(); /** * Filters rewrite rules used for "page" post type archives. * * @since 1.5.0 * * @param string[] $page_rewrite Array of rewrite rules for the "page" post type, keyed by their regex pattern. */ $page_rewrite = apply_filters( 'page_rewrite_rules', $page_rewrite ); // Extra permastructs. foreach ( $this->extra_permastructs as $permastructname => $struct ) { if ( is_array( $struct ) ) { if ( count( $struct ) == 2 ) { $rules = $this->generate_rewrite_rules( $struct[0], $struct[1] ); } else { $rules = $this->generate_rewrite_rules( $struct['struct'], $struct['ep_mask'], $struct['paged'], $struct['feed'], $struct['forcomments'], $struct['walk_dirs'], $struct['endpoints'] ); } } else { $rules = $this->generate_rewrite_rules( $struct ); } /** * Filters rewrite rules used for individual permastructs. * * The dynamic portion of the hook name, `$permastructname`, refers * to the name of the registered permastruct. * * Possible hook names include: * * - `category_rewrite_rules` * - `post_format_rewrite_rules` * - `post_tag_rewrite_rules` * * @since 3.1.0 * * @param string[] $rules Array of rewrite rules generated for the current permastruct, keyed by their regex pattern. */ $rules = apply_filters( "{$permastructname}_rewrite_rules", $rules ); if ( 'post_tag' === $permastructname ) { /** * Filters rewrite rules used specifically for Tags. * * @since 2.3.0 * @deprecated 3.1.0 Use {@see 'post_tag_rewrite_rules'} instead. * * @param string[] $rules Array of rewrite rules generated for tags, keyed by their regex pattern. */ $rules = apply_filters_deprecated( 'tag_rewrite_rules', array( $rules ), '3.1.0', 'post_tag_rewrite_rules' ); } $this->extra_rules_top = array_merge( $this->extra_rules_top, $rules ); } // Put them together. if ( $this->use_verbose_page_rules ) { $this->rules = array_merge( $this->extra_rules_top, $robots_rewrite, $favicon_rewrite, $deprecated_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $author_rewrite, $date_rewrite, $page_rewrite, $post_rewrite, $this->extra_rules ); } else { $this->rules = array_merge( $this->extra_rules_top, $robots_rewrite, $favicon_rewrite, $deprecated_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $author_rewrite, $date_rewrite, $post_rewrite, $page_rewrite, $this->extra_rules ); } /** * Fires after the rewrite rules are generated. * * @since 1.5.0 * * @param WP_Rewrite $wp_rewrite Current WP_Rewrite instance (passed by reference). */ do_action_ref_array( 'generate_rewrite_rules', array( &$this ) ); /** * Filters the full set of generated rewrite rules. * * @since 1.5.0 * * @param string[] $rules The compiled array of rewrite rules, keyed by their regex pattern. */ $this->rules = apply_filters( 'rewrite_rules_array', $this->rules ); return $this->rules; } /** * Retrieves the rewrite rules. * * The difference between this method and WP_Rewrite::rewrite_rules() is that * this method stores the rewrite rules in the 'rewrite_rules' option and retrieves * it. This prevents having to process all of the permalinks to get the rewrite rules * in the form of caching. * * @since 1.5.0 * * @return string[] Array of rewrite rules keyed by their regex pattern. */ public function wp_rewrite_rules() { $this->rules = get_option( 'rewrite_rules' ); if ( empty( $this->rules ) ) { $this->matches = 'matches'; $this->rewrite_rules(); if ( ! did_action( 'wp_loaded' ) ) { add_action( 'wp_loaded', array( $this, 'flush_rules' ) ); return $this->rules; } update_option( 'rewrite_rules', $this->rules ); } return $this->rules; } /** * Retrieves mod_rewrite-formatted rewrite rules to write to .htaccess. * * Does not actually write to the .htaccess file, but creates the rules for * the process that will. * * Will add the non_wp_rules property rules to the .htaccess file before * the WordPress rewrite rules one. * * @since 1.5.0 * * @return string */ public function mod_rewrite_rules() { if ( ! $this->using_permalinks() ) { return ''; } $site_root = parse_url( site_url() ); if ( isset( $site_root['path'] ) ) { $site_root = trailingslashit( $site_root['path'] ); } $home_root = parse_url( home_url() ); if ( isset( $home_root['path'] ) ) { $home_root = trailingslashit( $home_root['path'] ); } else { $home_root = '/'; } $rules = "<IfModule mod_rewrite.c>\n"; $rules .= "RewriteEngine On\n"; $rules .= "RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\n"; $rules .= "RewriteBase $home_root\n"; // Prevent -f checks on index.php. $rules .= "RewriteRule ^index\.php$ - [L]\n"; // Add in the rules that don't redirect to WP's index.php (and thus shouldn't be handled by WP at all). foreach ( (array) $this->non_wp_rules as $match => $query ) { // Apache 1.3 does not support the reluctant (non-greedy) modifier. $match = str_replace( '.+?', '.+', $match ); $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n"; } if ( $this->use_verbose_rules ) { $this->matches = ''; $rewrite = $this->rewrite_rules(); $num_rules = count( $rewrite ); $rules .= "RewriteCond %{REQUEST_FILENAME} -f [OR]\n" . "RewriteCond %{REQUEST_FILENAME} -d\n" . "RewriteRule ^.*$ - [S=$num_rules]\n"; foreach ( (array) $rewrite as $match => $query ) { // Apache 1.3 does not support the reluctant (non-greedy) modifier. $match = str_replace( '.+?', '.+', $match ); if ( strpos( $query, $this->index ) !== false ) { $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n"; } else { $rules .= 'RewriteRule ^' . $match . ' ' . $site_root . $query . " [QSA,L]\n"; } } } else { $rules .= "RewriteCond %{REQUEST_FILENAME} !-f\n" . "RewriteCond %{REQUEST_FILENAME} !-d\n" . "RewriteRule . {$home_root}{$this->index} [L]\n"; } $rules .= "</IfModule>\n"; /** * Filters the list of rewrite rules formatted for output to an .htaccess file. * * @since 1.5.0 * * @param string $rules mod_rewrite Rewrite rules formatted for .htaccess. */ $rules = apply_filters( 'mod_rewrite_rules', $rules ); /** * Filters the list of rewrite rules formatted for output to an .htaccess file. * * @since 1.5.0 * @deprecated 1.5.0 Use the {@see 'mod_rewrite_rules'} filter instead. * * @param string $rules mod_rewrite Rewrite rules formatted for .htaccess. */ return apply_filters_deprecated( 'rewrite_rules', array( $rules ), '1.5.0', 'mod_rewrite_rules' ); } /** * Retrieves IIS7 URL Rewrite formatted rewrite rules to write to web.config file. * * Does not actually write to the web.config file, but creates the rules for * the process that will. * * @since 2.8.0 * * @param bool $add_parent_tags Optional. Whether to add parent tags to the rewrite rule sets. * Default false. * @return string IIS7 URL rewrite rule sets. */ public function iis7_url_rewrite_rules( $add_parent_tags = false ) { if ( ! $this->using_permalinks() ) { return ''; } $rules = ''; if ( $add_parent_tags ) { $rules .= '<configuration> <system.webServer> <rewrite> <rules>'; } $rules .= ' <rule name="WordPress: ' . esc_attr( home_url() ) . '" patternSyntax="Wildcard"> <match url="*" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="index.php" /> </rule>'; if ( $add_parent_tags ) { $rules .= ' </rules> </rewrite> </system.webServer> </configuration>'; } /** * Filters the list of rewrite rules formatted for output to a web.config. * * @since 2.8.0 * * @param string $rules Rewrite rules formatted for IIS web.config. */ return apply_filters( 'iis7_url_rewrite_rules', $rules ); } /** * Adds a rewrite rule that transforms a URL structure to a set of query vars. * * Any value in the $after parameter that isn't 'bottom' will result in the rule * being placed at the top of the rewrite rules. * * @since 2.1.0 * @since 4.4.0 Array support was added to the `$query` parameter. * * @param string $regex Regular expression to match request against. * @param string|array $query The corresponding query vars for this rewrite rule. * @param string $after Optional. Priority of the new rule. Accepts 'top' * or 'bottom'. Default 'bottom'. */ public function add_rule( $regex, $query, $after = 'bottom' ) { if ( is_array( $query ) ) { $external = false; $query = add_query_arg( $query, 'index.php' ); } else { $index = false === strpos( $query, '?' ) ? strlen( $query ) : strpos( $query, '?' ); $front = substr( $query, 0, $index ); $external = $front != $this->index; } // "external" = it doesn't correspond to index.php. if ( $external ) { $this->add_external_rule( $regex, $query ); } else { if ( 'bottom' === $after ) { $this->extra_rules = array_merge( $this->extra_rules, array( $regex => $query ) ); } else { $this->extra_rules_top = array_merge( $this->extra_rules_top, array( $regex => $query ) ); } } } /** * Adds a rewrite rule that doesn't correspond to index.php. * * @since 2.1.0 * * @param string $regex Regular expression to match request against. * @param string $query The corresponding query vars for this rewrite rule. */ public function add_external_rule( $regex, $query ) { $this->non_wp_rules[ $regex ] = $query; } /** * Adds an endpoint, like /trackback/. * * @since 2.1.0 * @since 3.9.0 $query_var parameter added. * @since 4.3.0 Added support for skipping query var registration by passing `false` to `$query_var`. * * @see add_rewrite_endpoint() for full documentation. * @global WP $wp Current WordPress environment instance. * * @param string $name Name of the endpoint. * @param int $places Endpoint mask describing the places the endpoint should be added. * Accepts a mask of: * - `EP_ALL` * - `EP_NONE` * - `EP_ALL_ARCHIVES` * - `EP_ATTACHMENT` * - `EP_AUTHORS` * - `EP_CATEGORIES` * - `EP_COMMENTS` * - `EP_DATE` * - `EP_DAY` * - `EP_MONTH` * - `EP_PAGES` * - `EP_PERMALINK` * - `EP_ROOT` * - `EP_SEARCH` * - `EP_TAGS` * - `EP_YEAR` * @param string|bool $query_var Optional. Name of the corresponding query variable. Pass `false` to * skip registering a query_var for this endpoint. Defaults to the * value of `$name`. */ public function add_endpoint( $name, $places, $query_var = true ) { global $wp; // For backward compatibility, if null has explicitly been passed as `$query_var`, assume `true`. if ( true === $query_var || null === $query_var ) { $query_var = $name; } $this->endpoints[] = array( $places, $name, $query_var ); if ( $query_var ) { $wp->add_query_var( $query_var ); } } /** * Adds a new permalink structure. * * A permalink structure (permastruct) is an abstract definition of a set of rewrite rules; * it is an easy way of expressing a set of regular expressions that rewrite to a set of * query strings. The new permastruct is added to the WP_Rewrite::$extra_permastructs array. * * When the rewrite rules are built by WP_Rewrite::rewrite_rules(), all of these extra * permastructs are passed to WP_Rewrite::generate_rewrite_rules() which transforms them * into the regular expressions that many love to hate. * * The `$args` parameter gives you control over how WP_Rewrite::generate_rewrite_rules() * works on the new permastruct. * * @since 2.5.0 * * @param string $name Name for permalink structure. * @param string $struct Permalink structure (e.g. category/%category%) * @param array $args { * Optional. Arguments for building rewrite rules based on the permalink structure. * Default empty array. * * @type bool $with_front Whether the structure should be prepended with `WP_Rewrite::$front`. * Default true. * @type int $ep_mask The endpoint mask defining which endpoints are added to the structure. * Accepts a mask of: * - `EP_ALL` * - `EP_NONE` * - `EP_ALL_ARCHIVES` * - `EP_ATTACHMENT` * - `EP_AUTHORS` * - `EP_CATEGORIES` * - `EP_COMMENTS` * - `EP_DATE` * - `EP_DAY` * - `EP_MONTH` * - `EP_PAGES` * - `EP_PERMALINK` * - `EP_ROOT` * - `EP_SEARCH` * - `EP_TAGS` * - `EP_YEAR` * Default `EP_NONE`. * @type bool $paged Whether archive pagination rules should be added for the structure. * Default true. * @type bool $feed Whether feed rewrite rules should be added for the structure. Default true. * @type bool $forcomments Whether the feed rules should be a query for a comments feed. Default false. * @type bool $walk_dirs Whether the 'directories' making up the structure should be walked over * and rewrite rules built for each in-turn. Default true. * @type bool $endpoints Whether endpoints should be applied to the generated rules. Default true. * } */ public function add_permastruct( $name, $struct, $args = array() ) { // Back-compat for the old parameters: $with_front and $ep_mask. if ( ! is_array( $args ) ) { $args = array( 'with_front' => $args ); } if ( func_num_args() == 4 ) { $args['ep_mask'] = func_get_arg( 3 ); } $defaults = array( 'with_front' => true, 'ep_mask' => EP_NONE, 'paged' => true, 'feed' => true, 'forcomments' => false, 'walk_dirs' => true, 'endpoints' => true, ); $args = array_intersect_key( $args, $defaults ); $args = wp_parse_args( $args, $defaults ); if ( $args['with_front'] ) { $struct = $this->front . $struct; } else { $struct = $this->root . $struct; } $args['struct'] = $struct; $this->extra_permastructs[ $name ] = $args; } /** * Removes a permalink structure. * * @since 4.5.0 * * @param string $name Name for permalink structure. */ public function remove_permastruct( $name ) { unset( $this->extra_permastructs[ $name ] ); } /** * Removes rewrite rules and then recreate rewrite rules. * * Calls WP_Rewrite::wp_rewrite_rules() after removing the 'rewrite_rules' option. * If the function named 'save_mod_rewrite_rules' exists, it will be called. * * @since 2.0.1 * * @param bool $hard Whether to update .htaccess (hard flush) or just update rewrite_rules option (soft flush). Default is true (hard). */ public function flush_rules( $hard = true ) { static $do_hard_later = null; // Prevent this action from running before everyone has registered their rewrites. if ( ! did_action( 'wp_loaded' ) ) { add_action( 'wp_loaded', array( $this, 'flush_rules' ) ); $do_hard_later = ( isset( $do_hard_later ) ) ? $do_hard_later || $hard : $hard; return; } if ( isset( $do_hard_later ) ) { $hard = $do_hard_later; unset( $do_hard_later ); } update_option( 'rewrite_rules', '' ); $this->wp_rewrite_rules(); /** * Filters whether a "hard" rewrite rule flush should be performed when requested. * * A "hard" flush updates .htaccess (Apache) or web.config (IIS). * * @since 3.7.0 * * @param bool $hard Whether to flush rewrite rules "hard". Default true. */ if ( ! $hard || ! apply_filters( 'flush_rewrite_rules_hard', true ) ) { return; } if ( function_exists( 'save_mod_rewrite_rules' ) ) { save_mod_rewrite_rules(); } if ( function_exists( 'iis7_save_url_rewrite_rules' ) ) { iis7_save_url_rewrite_rules(); } } /** * Sets up the object's properties. * * The 'use_verbose_page_rules' object property will be set to true if the * permalink structure begins with one of the following: '%postname%', '%category%', * '%tag%', or '%author%'. * * @since 1.5.0 */ public function init() { $this->extra_rules = array(); $this->non_wp_rules = array(); $this->endpoints = array(); $this->permalink_structure = get_option( 'permalink_structure' ); $this->front = substr( $this->permalink_structure, 0, strpos( $this->permalink_structure, '%' ) ); $this->root = ''; if ( $this->using_index_permalinks() ) { $this->root = $this->index . '/'; } unset( $this->author_structure ); unset( $this->date_structure ); unset( $this->page_structure ); unset( $this->search_structure ); unset( $this->feed_structure ); unset( $this->comment_feed_structure ); $this->use_trailing_slashes = ( '/' === substr( $this->permalink_structure, -1, 1 ) ); // Enable generic rules for pages if permalink structure doesn't begin with a wildcard. if ( preg_match( '/^[^%]*%(?:postname|category|tag|author)%/', $this->permalink_structure ) ) { $this->use_verbose_page_rules = true; } else { $this->use_verbose_page_rules = false; } } /** * Sets the main permalink structure for the site. * * Will update the 'permalink_structure' option, if there is a difference * between the current permalink structure and the parameter value. Calls * WP_Rewrite::init() after the option is updated. * * Fires the {@see 'permalink_structure_changed'} action once the init call has * processed passing the old and new values * * @since 1.5.0 * * @param string $permalink_structure Permalink structure. */ public function set_permalink_structure( $permalink_structure ) { if ( $permalink_structure != $this->permalink_structure ) { $old_permalink_structure = $this->permalink_structure; update_option( 'permalink_structure', $permalink_structure ); $this->init(); /** * Fires after the permalink structure is updated. * * @since 2.8.0 * * @param string $old_permalink_structure The previous permalink structure. * @param string $permalink_structure The new permalink structure. */ do_action( 'permalink_structure_changed', $old_permalink_structure, $permalink_structure ); } } /** * Sets the category base for the category permalink. * * Will update the 'category_base' option, if there is a difference between * the current category base and the parameter value. Calls WP_Rewrite::init() * after the option is updated. * * @since 1.5.0 * * @param string $category_base Category permalink structure base. */ public function set_category_base( $category_base ) { if ( get_option( 'category_base' ) !== $category_base ) { update_option( 'category_base', $category_base ); $this->init(); } } /** * Sets the tag base for the tag permalink. * * Will update the 'tag_base' option, if there is a difference between the * current tag base and the parameter value. Calls WP_Rewrite::init() after * the option is updated. * * @since 2.3.0 * * @param string $tag_base Tag permalink structure base. */ public function set_tag_base( $tag_base ) { if ( get_option( 'tag_base' ) !== $tag_base ) { update_option( 'tag_base', $tag_base ); $this->init(); } } /** * Constructor - Calls init(), which runs setup. * * @since 1.5.0 */ public function __construct() { $this->init(); } } ``` | Version | Description | | --- | --- | | [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
programming_docs
wordpress class Requests_Exception_HTTP_409 {} class Requests\_Exception\_HTTP\_409 {} ======================================= Exception for 409 Conflict responses File: `wp-includes/Requests/Exception/HTTP/409.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/409.php/) ``` class Requests_Exception_HTTP_409 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 409; /** * Reason phrase * * @var string */ protected $reason = 'Conflict'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class Walker_CategoryDropdown {} class Walker\_CategoryDropdown {} ================================= Core class used to create an HTML dropdown list of Categories. * [Walker](walker) * [start\_el](walker_categorydropdown/start_el) β€” Starts the element output. File: `wp-includes/class-walker-category-dropdown.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-category-dropdown.php/) ``` class Walker_CategoryDropdown extends Walker { /** * What the class handles. * * @since 2.1.0 * @var string * * @see Walker::$tree_type */ public $tree_type = 'category'; /** * Database fields to use. * * @since 2.1.0 * @todo Decouple this * @var string[] * * @see Walker::$db_fields */ public $db_fields = array( 'parent' => 'parent', 'id' => 'term_id', ); /** * Starts the element output. * * @since 2.1.0 * @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. * * @see Walker::start_el() * * @param string $output Used to append additional content (passed by reference). * @param WP_Term $data_object Category data object. * @param int $depth Depth of category. Used for padding. * @param array $args Uses 'selected', 'show_count', and 'value_field' keys, if they exist. * See wp_dropdown_categories(). * @param int $current_object_id Optional. ID of the current category. Default 0. */ 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( '&nbsp;', $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 .= '&nbsp;&nbsp;(' . number_format_i18n( $category->count ) . ')'; } $output .= "</option>\n"; } } ``` | Uses | Description | | --- | --- | | [Walker](walker) wp-includes/class-wp-walker.php | A class for displaying various tree-like structures. | | Version | Description | | --- | --- | | [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. | wordpress class WP_Theme {} class WP\_Theme {} ================== [WP\_Theme](wp_theme) Class [WP\_Theme](wp_theme) is a class that helps developers interact with a theme. You shouldn’t alter the properties directly, but instead use the methods to interact with them. For complete list of methods and properties, refer the source code. Name WordPress Theme object. ThemeURI The URI of the theme’s webpage. Description The description of the theme Author The theme’s author AuthorURI The website of the theme author Version The version of the theme Template (Optional β€” used in a child theme) The folder name of the parent theme Status If the theme is published Tags Tags used to describe the theme TextDomain The text domain used in the theme for translation purposes DomainPath Path to the theme translation files * [\_\_construct](wp_theme/__construct) β€” Constructor for WP\_Theme. * [\_\_get](wp_theme/__get) β€” \_\_get() magic method for properties formerly returned by current\_theme\_info() * [\_\_isset](wp_theme/__isset) β€” \_\_isset() magic method for properties formerly returned by current\_theme\_info() * [\_\_toString](wp_theme/__tostring) β€” When converting the object to a string, the theme name is returned. * [\_name\_sort](wp_theme/_name_sort) β€” Callback function for usort() to naturally sort themes by name. * [\_name\_sort\_i18n](wp_theme/_name_sort_i18n) β€” Callback function for usort() to naturally sort themes by translated name. * [cache\_add](wp_theme/cache_add) β€” Adds theme data to cache. * [cache\_delete](wp_theme/cache_delete) β€” Clears the cache for the theme. * [cache\_get](wp_theme/cache_get) β€” Gets theme data from cache. * [display](wp_theme/display) β€” Gets a theme header, formatted and translated for display. * [errors](wp_theme/errors) β€” Returns errors property. * [exists](wp_theme/exists) β€” Determines whether the theme exists. * [get](wp_theme/get) β€” Gets a raw, unformatted theme header. * [get\_allowed](wp_theme/get_allowed) β€” Returns array of stylesheet names of themes allowed on the site or network. * [get\_allowed\_on\_network](wp_theme/get_allowed_on_network) β€” Returns array of stylesheet names of themes allowed on the network. * [get\_allowed\_on\_site](wp_theme/get_allowed_on_site) β€” Returns array of stylesheet names of themes allowed on the site. * [get\_core\_default\_theme](wp_theme/get_core_default_theme) β€” Determines the latest WordPress default theme that is installed. * [get\_file\_path](wp_theme/get_file_path) β€” Retrieves the path of a file in the theme. * [get\_files](wp_theme/get_files) β€” Returns files in the theme's directory. * [get\_page\_templates](wp_theme/get_page_templates) β€” Returns the theme's post templates for a given post type. * [get\_post\_templates](wp_theme/get_post_templates) β€” Returns the theme's post templates. * [get\_screenshot](wp_theme/get_screenshot) β€” Returns the main screenshot file for the theme. * [get\_stylesheet](wp_theme/get_stylesheet) β€” Returns the directory name of the theme's "stylesheet" files, inside the theme root. * [get\_stylesheet\_directory](wp_theme/get_stylesheet_directory) β€” Returns the absolute path to the directory of a theme's "stylesheet" files. * [get\_stylesheet\_directory\_uri](wp_theme/get_stylesheet_directory_uri) β€” Returns the URL to the directory of a theme's "stylesheet" files. * [get\_template](wp_theme/get_template) β€” Returns the directory name of the theme's "template" files, inside the theme root. * [get\_template\_directory](wp_theme/get_template_directory) β€” Returns the absolute path to the directory of a theme's "template" files. * [get\_template\_directory\_uri](wp_theme/get_template_directory_uri) β€” Returns the URL to the directory of a theme's "template" files. * [get\_theme\_root](wp_theme/get_theme_root) β€” Returns the absolute path to the directory of the theme root. * [get\_theme\_root\_uri](wp_theme/get_theme_root_uri) β€” Returns the URL to the directory of the theme root. * [is\_allowed](wp_theme/is_allowed) β€” Determines whether the theme is allowed (multisite only). * [is\_block\_theme](wp_theme/is_block_theme) β€” Returns whether this theme is a block-based theme or not. * [load\_textdomain](wp_theme/load_textdomain) β€” Loads the theme's textdomain. * [markup\_header](wp_theme/markup_header) β€” Marks up a theme header. * [network\_disable\_theme](wp_theme/network_disable_theme) β€” Disables a theme for all sites on the current network. * [network\_enable\_theme](wp_theme/network_enable_theme) β€” Enables a theme for all sites on the current network. * [offsetExists](wp_theme/offsetexists) * [offsetGet](wp_theme/offsetget) * [offsetSet](wp_theme/offsetset) * [offsetUnset](wp_theme/offsetunset) * [parent](wp_theme/parent) β€” Returns reference to the parent theme. * [sanitize\_header](wp_theme/sanitize_header) β€” Sanitizes a theme header. * [scandir](wp_theme/scandir) β€” Scans a directory for files of a certain extension. * [sort\_by\_name](wp_theme/sort_by_name) β€” Sorts themes by name. * [translate\_header](wp_theme/translate_header) β€” Translates a theme header. File: `wp-includes/class-wp-theme.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme.php/) ``` final class WP_Theme implements ArrayAccess { /** * Whether the theme has been marked as updateable. * * @since 4.4.0 * @var bool * * @see WP_MS_Themes_List_Table */ public $update = false; /** * Headers for style.css files. * * @since 3.4.0 * @since 5.4.0 Added `Requires at least` and `Requires PHP` headers. * @since 6.1.0 Added `Update URI` header. * @var string[] */ private static $file_headers = array( 'Name' => 'Theme Name', 'ThemeURI' => 'Theme URI', 'Description' => 'Description', 'Author' => 'Author', 'AuthorURI' => 'Author URI', 'Version' => 'Version', 'Template' => 'Template', 'Status' => 'Status', 'Tags' => 'Tags', 'TextDomain' => 'Text Domain', 'DomainPath' => 'Domain Path', 'RequiresWP' => 'Requires at least', 'RequiresPHP' => 'Requires PHP', 'UpdateURI' => 'Update URI', ); /** * Default themes. * * @since 3.4.0 * @since 3.5.0 Added the Twenty Twelve theme. * @since 3.6.0 Added the Twenty Thirteen theme. * @since 3.8.0 Added the Twenty Fourteen theme. * @since 4.1.0 Added the Twenty Fifteen theme. * @since 4.4.0 Added the Twenty Sixteen theme. * @since 4.7.0 Added the Twenty Seventeen theme. * @since 5.0.0 Added the Twenty Nineteen theme. * @since 5.3.0 Added the Twenty Twenty theme. * @since 5.6.0 Added the Twenty Twenty-One theme. * @since 5.9.0 Added the Twenty Twenty-Two theme. * @var string[] */ private static $default_themes = array( 'classic' => 'WordPress Classic', 'default' => 'WordPress Default', 'twentyten' => 'Twenty Ten', 'twentyeleven' => 'Twenty Eleven', 'twentytwelve' => 'Twenty Twelve', 'twentythirteen' => 'Twenty Thirteen', 'twentyfourteen' => 'Twenty Fourteen', 'twentyfifteen' => 'Twenty Fifteen', 'twentysixteen' => 'Twenty Sixteen', 'twentyseventeen' => 'Twenty Seventeen', 'twentynineteen' => 'Twenty Nineteen', 'twentytwenty' => 'Twenty Twenty', 'twentytwentyone' => 'Twenty Twenty-One', 'twentytwentytwo' => 'Twenty Twenty-Two', 'twentytwentythree' => 'Twenty Twenty-Three', ); /** * Renamed theme tags. * * @since 3.8.0 * @var string[] */ private static $tag_map = array( 'fixed-width' => 'fixed-layout', 'flexible-width' => 'fluid-layout', ); /** * Absolute path to the theme root, usually wp-content/themes * * @since 3.4.0 * @var string */ private $theme_root; /** * Header data from the theme's style.css file. * * @since 3.4.0 * @var array */ private $headers = array(); /** * Header data from the theme's style.css file after being sanitized. * * @since 3.4.0 * @var array */ private $headers_sanitized; /** * Header name from the theme's style.css after being translated. * * Cached due to sorting functions running over the translated name. * * @since 3.4.0 * @var string */ private $name_translated; /** * Errors encountered when initializing the theme. * * @since 3.4.0 * @var WP_Error */ private $errors; /** * The directory name of the theme's files, inside the theme root. * * In the case of a child theme, this is directory name of the child theme. * Otherwise, 'stylesheet' is the same as 'template'. * * @since 3.4.0 * @var string */ private $stylesheet; /** * The directory name of the theme's files, inside the theme root. * * In the case of a child theme, this is the directory name of the parent theme. * Otherwise, 'template' is the same as 'stylesheet'. * * @since 3.4.0 * @var string */ private $template; /** * A reference to the parent theme, in the case of a child theme. * * @since 3.4.0 * @var WP_Theme */ private $parent; /** * URL to the theme root, usually an absolute URL to wp-content/themes * * @since 3.4.0 * @var string */ private $theme_root_uri; /** * Flag for whether the theme's textdomain is loaded. * * @since 3.4.0 * @var bool */ private $textdomain_loaded; /** * Stores an md5 hash of the theme root, to function as the cache key. * * @since 3.4.0 * @var string */ private $cache_hash; /** * Flag for whether the themes cache bucket should be persistently cached. * * Default is false. Can be set with the {@see 'wp_cache_themes_persistently'} filter. * * @since 3.4.0 * @var bool */ private static $persistently_cache; /** * Expiration time for the themes cache bucket. * * By default the bucket is not cached, so this value is useless. * * @since 3.4.0 * @var bool */ private static $cache_expiration = 1800; /** * Constructor for WP_Theme. * * @since 3.4.0 * * @global array $wp_theme_directories * * @param string $theme_dir Directory of the theme within the theme_root. * @param string $theme_root Theme root. * @param WP_Theme|null $_child If this theme is a parent theme, the child may be passed for validation purposes. */ 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 ); } } /** * When converting the object to a string, the theme name is returned. * * @since 3.4.0 * * @return string Theme name, ready for display (translated) */ public function __toString() { return (string) $this->display( 'Name' ); } /** * __isset() magic method for properties formerly returned by current_theme_info() * * @since 3.4.0 * * @param string $offset Property to check if set. * @return bool Whether the given property is set. */ 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 ); } /** * __get() magic method for properties formerly returned by current_theme_info() * * @since 3.4.0 * * @param string $offset Property to get. * @return mixed Property value. */ 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 ); } } /** * Method to implement ArrayAccess for keys formerly returned by get_themes() * * @since 3.4.0 * * @param mixed $offset * @param mixed $value */ #[ReturnTypeWillChange] public function offsetSet( $offset, $value ) {} /** * Method to implement ArrayAccess for keys formerly returned by get_themes() * * @since 3.4.0 * * @param mixed $offset */ #[ReturnTypeWillChange] public function offsetUnset( $offset ) {} /** * Method to implement ArrayAccess for keys formerly returned by get_themes() * * @since 3.4.0 * * @param mixed $offset * @return bool */ #[ReturnTypeWillChange] 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 ); } /** * Method to implement ArrayAccess for keys formerly returned by get_themes(). * * Author, Author Name, Author URI, and Description did not previously return * translated data. We are doing so now as it is safe to do. However, as * Name and Title could have been used as the key for get_themes(), both remain * untranslated for back compatibility. This means that ['Name'] is not ideal, * and care should be taken to use `$theme::display( 'Name' )` to get a properly * translated header. * * @since 3.4.0 * * @param mixed $offset * @return mixed */ #[ReturnTypeWillChange] 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; } } /** * Returns errors property. * * @since 3.4.0 * * @return WP_Error|false WP_Error if there are errors, or false. */ public function errors() { return is_wp_error( $this->errors ) ? $this->errors : false; } /** * 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. * * @since 3.4.0 * * @return bool Whether the theme exists. */ public function exists() { return ! ( $this->errors() && in_array( 'theme_not_found', $this->errors()->get_error_codes(), true ) ); } /** * Returns reference to the parent theme. * * @since 3.4.0 * * @return WP_Theme|false Parent theme, or false if the active theme is not a child theme. */ public function parent() { return isset( $this->parent ) ? $this->parent : false; } /** * Adds theme data to cache. * * Cache entries keyed by the theme and the type of data. * * @since 3.4.0 * * @param string $key Type of data to store (theme, screenshot, headers, post_templates) * @param array|string $data Data to store * @return bool Return value from wp_cache_add() */ private function cache_add( $key, $data ) { return wp_cache_add( $key . '-' . $this->cache_hash, $data, 'themes', self::$cache_expiration ); } /** * Gets theme data from cache. * * Cache entries are keyed by the theme and the type of data. * * @since 3.4.0 * * @param string $key Type of data to retrieve (theme, screenshot, headers, post_templates) * @return mixed Retrieved data */ private function cache_get( $key ) { return wp_cache_get( $key . '-' . $this->cache_hash, 'themes' ); } /** * Clears the cache for the theme. * * @since 3.4.0 */ 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 ); } /** * 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() 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() takes into account where WordPress actually located the theme and * whether it is actually valid. * * @since 3.4.0 * * @param string $header Theme header. Name, Description, Author, Version, ThemeURI, AuthorURI, Status, Tags. * @return string|array|false String or array (for Tags header) on success, false on failure. */ 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 ]; } /** * Gets a theme header, formatted and translated for display. * * @since 3.4.0 * * @param string $header Theme header. Name, Description, Author, Version, ThemeURI, AuthorURI, Status, Tags. * @param bool $markup Optional. Whether to mark up the header. Defaults to true. * @param bool $translate Optional. Whether to translate the header. Defaults to true. * @return string|array|false Processed header. An array for Tags if `$markup` is false, string otherwise. * False on failure. */ 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; } /** * Sanitizes a theme header. * * @since 3.4.0 * @since 5.4.0 Added support for `Requires at least` and `Requires PHP` headers. * @since 6.1.0 Added support for `Update URI` header. * * @param string $header Theme header. Accepts 'Name', 'Description', 'Author', 'Version', * 'ThemeURI', 'AuthorURI', 'Status', 'Tags', 'RequiresWP', 'RequiresPHP', * 'UpdateURI'. * @param string $value Value to sanitize. * @return string|array An array for Tags header, string otherwise. */ 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; } /** * Marks up a theme header. * * @since 3.4.0 * * @param string $header Theme header. Name, Description, Author, Version, ThemeURI, AuthorURI, Status, Tags. * @param string|array $value Value to mark up. An array for Tags header, string otherwise. * @param string $translate Whether the header has been translated. * @return string Value, marked up. */ 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; } /** * Translates a theme header. * * @since 3.4.0 * * @param string $header Theme header. Name, Description, Author, Version, ThemeURI, AuthorURI, Status, Tags. * @param string|array $value Value to translate. An array for Tags header, string otherwise. * @return string|array Translated value. An array for Tags header, string otherwise. */ 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; } /** * 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() is the same as get_template(). * * @since 3.4.0 * * @return string Stylesheet */ public function get_stylesheet() { return $this->stylesheet; } /** * 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() is the same as get_stylesheet(). * * @since 3.4.0 * * @return string Template */ public function get_template() { return $this->template; } /** * 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. * * @since 3.4.0 * * @return string Absolute path of the stylesheet directory. */ 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; } /** * 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. * * @since 3.4.0 * * @return string Absolute path of the template directory. */ 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; } /** * 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. * * @since 3.4.0 * * @return string URL to the stylesheet directory. */ public function get_stylesheet_directory_uri() { return $this->get_theme_root_uri() . '/' . str_replace( '%2F', '/', rawurlencode( $this->stylesheet ) ); } /** * 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. * * @since 3.4.0 * * @return string URL to the template directory. */ 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 ) ); } /** * Returns the absolute path to the directory of the theme root. * * This is typically the absolute path to wp-content/themes. * * @since 3.4.0 * * @return string Theme root. */ public function get_theme_root() { return $this->theme_root; } /** * 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, so we pass it to the public function * get_theme_root_uri() and allow it to run the {@see 'theme_root_uri'} filter. * * @since 3.4.0 * * @return string Theme root URI. */ 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; } /** * 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.) * * @since 3.4.0 * * @param string $uri Type of URL to return, either 'relative' or an absolute URI. Defaults to absolute URI. * @return string|false Screenshot file. False if the theme does not have a screenshot. */ 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; } /** * Returns files in the theme's directory. * * @since 3.4.0 * * @param string[]|string $type Optional. Array of extensions to find, string of a single extension, * or null for all extensions. Default null. * @param int $depth Optional. How deep to search for files. Defaults to a flat scan (0 depth). * -1 depth is infinite. * @param bool $search_parent Optional. Whether to return parent files. Default false. * @return string[] Array of files, keyed by the path to the file relative to the theme's directory, with the values * being absolute paths. */ 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 ); } /** * Returns the theme's post templates. * * @since 4.7.0 * @since 5.8.0 Include block templates. * * @return array[] Array of page template arrays, keyed by post type and filename, * with the value of the translated header name. */ 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; } /** * Returns the theme's post templates for a given post type. * * @since 3.4.0 * @since 4.7.0 Added the `$post_type` parameter. * * @param WP_Post|null $post Optional. The post being edited, provided for context. * @param string $post_type Optional. Post type to get the templates for. Default 'page'. * If a post is provided, its post type is used. * @return string[] Array of template header names keyed by the template file name. */ 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; } /** * Scans a directory for files of a certain extension. * * @since 3.4.0 * * @param string $path Absolute path to search. * @param array|string|null $extensions Optional. Array of extensions to find, string of a single extension, * or null for all extensions. Default null. * @param int $depth Optional. How many levels deep to search for files. Accepts 0, 1+, or * -1 (infinite depth). Default 0. * @param string $relative_path 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 empty. * @return 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. */ 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; } /** * 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. * * @since 3.4.0 * * @return 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. */ 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; } /** * Determines whether the theme is allowed (multisite only). * * @since 3.4.0 * * @param string $check Optional. Whether to check only the 'network'-wide settings, the 'site' * settings, or 'both'. Defaults to 'both'. * @param int $blog_id Optional. Ignored if only network-wide settings are checked. Defaults to current site. * @return bool Whether the theme is allowed for the network. Returns true in single-site. */ 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; } /** * Returns whether this theme is a block-based theme or not. * * @since 5.9.0 * * @return bool */ 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; } /** * 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. * * @since 5.9.0 * * @param string $file Optional. File to search for in the stylesheet directory. * @return string The path of the file. */ 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 ); } /** * Determines the latest WordPress default theme that is installed. * * This hits the filesystem. * * @since 4.4.0 * * @return WP_Theme|false Object, or false if no theme is installed, which would be bad. */ 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; } /** * Returns array of stylesheet names of themes allowed on the site or network. * * @since 3.4.0 * * @param int $blog_id Optional. ID of the site. Defaults to the current site. * @return string[] Array of stylesheet names. */ 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 ); } /** * Returns array of stylesheet names of themes allowed on the network. * * @since 3.4.0 * * @return string[] Array of stylesheet names. */ 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; } /** * Returns array of stylesheet names of themes allowed on the site. * * @since 3.4.0 * * @param int $blog_id Optional. ID of the site. Defaults to the current site. * @return string[] Array of stylesheet names. */ 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 ); } /** * Enables a theme for all sites on the current network. * * @since 4.6.0 * * @param string|string[] $stylesheets Stylesheet name or array of stylesheet names. */ 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 ); } /** * Disables a theme for all sites on the current network. * * @since 4.6.0 * * @param string|string[] $stylesheets Stylesheet name or array of stylesheet names. */ 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 ); } /** * Sorts themes by name. * * @since 3.4.0 * * @param WP_Theme[] $themes Array of theme objects to sort (passed by reference). */ 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' ) ); } } /** * 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(). * * @since 3.4.0 * * @param WP_Theme $a First theme. * @param WP_Theme $b Second theme. * @return 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(). */ private static function _name_sort( $a, $b ) { return strnatcasecmp( $a->headers['Name'], $b->headers['Name'] ); } /** * Callback function for usort() to naturally sort themes by translated name. * * @since 3.4.0 * * @param WP_Theme $a First theme. * @param WP_Theme $b Second theme. * @return 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(). */ 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. |
programming_docs
wordpress class IXR_Request {} class IXR\_Request {} ===================== [IXR\_Request](ixr_request) * [\_\_construct](ixr_request/__construct) β€” PHP5 constructor. * [getLength](ixr_request/getlength) * [getXml](ixr_request/getxml) * [IXR\_Request](ixr_request/ixr_request) β€” PHP4 constructor. File: `wp-includes/IXR/class-IXR-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-request.php/) ``` class IXR_Request { var $method; var $args; var $xml; /** * PHP5 constructor. */ function __construct($method, $args) { $this->method = $method; $this->args = $args; $this->xml = <<<EOD <?xml version="1.0"?> <methodCall> <methodName>{$this->method}</methodName> <params> EOD; foreach ($this->args as $arg) { $this->xml .= '<param><value>'; $v = new IXR_Value($arg); $this->xml .= $v->getXml(); $this->xml .= "</value></param>\n"; } $this->xml .= '</params></methodCall>'; } /** * PHP4 constructor. */ public function IXR_Request( $method, $args ) { self::__construct( $method, $args ); } function getLength() { return strlen($this->xml); } function getXml() { return $this->xml; } } ``` | Version | Description | | --- | --- | | [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. | wordpress class Requests_Utility_CaseInsensitiveDictionary {} class Requests\_Utility\_CaseInsensitiveDictionary {} ===================================================== Case-insensitive dictionary, suitable for HTTP headers * [\_\_construct](requests_utility_caseinsensitivedictionary/__construct) β€” Creates a case insensitive dictionary. * [getAll](requests_utility_caseinsensitivedictionary/getall) β€” Get the headers as an array * [getIterator](requests_utility_caseinsensitivedictionary/getiterator) β€” Get an iterator for the data * [offsetExists](requests_utility_caseinsensitivedictionary/offsetexists) β€” Check if the given item exists * [offsetGet](requests_utility_caseinsensitivedictionary/offsetget) β€” Get the value for the item * [offsetSet](requests_utility_caseinsensitivedictionary/offsetset) β€” Set the given item * [offsetUnset](requests_utility_caseinsensitivedictionary/offsetunset) β€” Unset the given header File: `wp-includes/Requests/Utility/CaseInsensitiveDictionary.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/utility/caseinsensitivedictionary.php/) ``` class Requests_Utility_CaseInsensitiveDictionary implements ArrayAccess, IteratorAggregate { /** * Actual item data * * @var array */ protected $data = array(); /** * Creates a case insensitive dictionary. * * @param array $data Dictionary/map to convert to case-insensitive */ public function __construct(array $data = array()) { foreach ($data as $key => $value) { $this->offsetSet($key, $value); } } /** * Check if the given item exists * * @param string $key Item key * @return boolean Does the item exist? */ public function offsetExists($key) { $key = strtolower($key); return isset($this->data[$key]); } /** * Get the value for the item * * @param string $key Item key * @return string|null Item value (null if offsetExists is false) */ public function offsetGet($key) { $key = strtolower($key); if (!isset($this->data[$key])) { return null; } return $this->data[$key]; } /** * Set the given item * * @throws Requests_Exception On attempting to use dictionary as list (`invalidset`) * * @param string $key Item name * @param string $value Item value */ 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; } /** * Unset the given header * * @param string $key */ public function offsetUnset($key) { unset($this->data[strtolower($key)]); } /** * Get an iterator for the data * * @return ArrayIterator */ public function getIterator() { return new ArrayIterator($this->data); } /** * Get the headers as an array * * @return array Header data */ public function getAll() { return $this->data; } } ``` | Used By | Description | | --- | --- | | [Requests\_Response\_Headers](requests_response_headers) wp-includes/Requests/Response/Headers.php | Case-insensitive dictionary, suitable for HTTP headers | wordpress class WP_Terms_List_Table {} class WP\_Terms\_List\_Table {} =============================== Core class used to implement displaying terms in a list table. * [WP\_List\_Table](wp_list_table) * [\_\_construct](wp_terms_list_table/__construct) β€” Constructor. * [\_rows](wp_terms_list_table/_rows) * [ajax\_user\_can](wp_terms_list_table/ajax_user_can) * [column\_cb](wp_terms_list_table/column_cb) * [column\_default](wp_terms_list_table/column_default) * [column\_description](wp_terms_list_table/column_description) * [column\_links](wp_terms_list_table/column_links) * [column\_name](wp_terms_list_table/column_name) * [column\_posts](wp_terms_list_table/column_posts) * [column\_slug](wp_terms_list_table/column_slug) * [current\_action](wp_terms_list_table/current_action) * [display\_rows\_or\_placeholder](wp_terms_list_table/display_rows_or_placeholder) * [get\_bulk\_actions](wp_terms_list_table/get_bulk_actions) * [get\_columns](wp_terms_list_table/get_columns) * [get\_default\_primary\_column\_name](wp_terms_list_table/get_default_primary_column_name) β€” Gets the name of the default primary column. * [get\_sortable\_columns](wp_terms_list_table/get_sortable_columns) * [handle\_row\_actions](wp_terms_list_table/handle_row_actions) β€” Generates and displays row action links. * [has\_items](wp_terms_list_table/has_items) * [inline\_edit](wp_terms_list_table/inline_edit) β€” Outputs the hidden row displayed when inline editing * [no\_items](wp_terms_list_table/no_items) * [prepare\_items](wp_terms_list_table/prepare_items) * [single\_row](wp_terms_list_table/single_row) File: `wp-admin/includes/class-wp-terms-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-terms-list-table.php/) ``` class WP_Terms_List_Table extends WP_List_Table { public $callback_args; private $level; /** * Constructor. * * @since 3.1.0 * * @see WP_List_Table::__construct() for more information on default arguments. * * @global string $post_type * @global string $taxonomy * @global string $action * @global object $tax * * @param array $args An associative array of arguments. */ public function __construct( $args = array() ) { global $post_type, $taxonomy, $action, $tax; parent::__construct( array( 'plural' => 'tags', 'singular' => 'tag', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); $action = $this->screen->action; $post_type = $this->screen->post_type; $taxonomy = $this->screen->taxonomy; if ( empty( $taxonomy ) ) { $taxonomy = 'post_tag'; } if ( ! taxonomy_exists( $taxonomy ) ) { wp_die( __( 'Invalid taxonomy.' ) ); } $tax = get_taxonomy( $taxonomy ); // @todo Still needed? Maybe just the show_ui part. if ( empty( $post_type ) || ! in_array( $post_type, get_post_types( array( 'show_ui' => true ) ), true ) ) { $post_type = 'post'; } } /** * @return bool */ public function ajax_user_can() { return current_user_can( get_taxonomy( $this->screen->taxonomy )->cap->manage_terms ); } /** */ public function prepare_items() { $taxonomy = $this->screen->taxonomy; $tags_per_page = $this->get_items_per_page( "edit_{$taxonomy}_per_page" ); if ( 'post_tag' === $taxonomy ) { /** * Filters the number of terms displayed per page for the Tags list table. * * @since 2.8.0 * * @param int $tags_per_page Number of tags to be displayed. Default 20. */ $tags_per_page = apply_filters( 'edit_tags_per_page', $tags_per_page ); /** * Filters the number of terms displayed per page for the Tags list table. * * @since 2.7.0 * @deprecated 2.8.0 Use {@see 'edit_tags_per_page'} instead. * * @param int $tags_per_page Number of tags to be displayed. Default 20. */ $tags_per_page = apply_filters_deprecated( 'tagsperpage', array( $tags_per_page ), '2.8.0', 'edit_tags_per_page' ); } elseif ( 'category' === $taxonomy ) { /** * Filters the number of terms displayed per page for the Categories list table. * * @since 2.8.0 * * @param int $tags_per_page Number of categories to be displayed. Default 20. */ $tags_per_page = apply_filters( 'edit_categories_per_page', $tags_per_page ); } $search = ! empty( $_REQUEST['s'] ) ? trim( wp_unslash( $_REQUEST['s'] ) ) : ''; $args = array( 'taxonomy' => $taxonomy, 'search' => $search, 'page' => $this->get_pagenum(), 'number' => $tags_per_page, 'hide_empty' => 0, ); if ( ! empty( $_REQUEST['orderby'] ) ) { $args['orderby'] = trim( wp_unslash( $_REQUEST['orderby'] ) ); } if ( ! empty( $_REQUEST['order'] ) ) { $args['order'] = trim( wp_unslash( $_REQUEST['order'] ) ); } $args['offset'] = ( $args['page'] - 1 ) * $args['number']; // Save the values because 'number' and 'offset' can be subsequently overridden. $this->callback_args = $args; if ( is_taxonomy_hierarchical( $taxonomy ) && ! isset( $args['orderby'] ) ) { // We'll need the full set of terms then. $args['number'] = 0; $args['offset'] = $args['number']; } $this->items = get_terms( $args ); $this->set_pagination_args( array( 'total_items' => wp_count_terms( array( 'taxonomy' => $taxonomy, 'search' => $search, ) ), 'per_page' => $tags_per_page, ) ); } /** */ public function no_items() { echo get_taxonomy( $this->screen->taxonomy )->labels->not_found; } /** * @return array */ protected function get_bulk_actions() { $actions = array(); if ( current_user_can( get_taxonomy( $this->screen->taxonomy )->cap->delete_terms ) ) { $actions['delete'] = __( 'Delete' ); } return $actions; } /** * @return string */ public function current_action() { if ( isset( $_REQUEST['action'] ) && isset( $_REQUEST['delete_tags'] ) && 'delete' === $_REQUEST['action'] ) { return 'bulk-delete'; } return parent::current_action(); } /** * @return array */ public function get_columns() { $columns = array( 'cb' => '<input type="checkbox" />', 'name' => _x( 'Name', 'term name' ), 'description' => __( 'Description' ), 'slug' => __( 'Slug' ), ); if ( 'link_category' === $this->screen->taxonomy ) { $columns['links'] = __( 'Links' ); } else { $columns['posts'] = _x( 'Count', 'Number/count of items' ); } return $columns; } /** * @return array */ protected function get_sortable_columns() { return array( 'name' => 'name', 'description' => 'description', 'slug' => 'slug', 'posts' => 'count', 'links' => 'count', ); } /** */ public function display_rows_or_placeholder() { $taxonomy = $this->screen->taxonomy; $number = $this->callback_args['number']; $offset = $this->callback_args['offset']; // Convert it to table rows. $count = 0; if ( empty( $this->items ) || ! is_array( $this->items ) ) { echo '<tr class="no-items"><td class="colspanchange" colspan="' . $this->get_column_count() . '">'; $this->no_items(); echo '</td></tr>'; return; } if ( is_taxonomy_hierarchical( $taxonomy ) && ! isset( $this->callback_args['orderby'] ) ) { if ( ! empty( $this->callback_args['search'] ) ) {// Ignore children on searches. $children = array(); } else { $children = _get_term_hierarchy( $taxonomy ); } /* * Some funky recursion to get the job done (paging & parents mainly) is contained within. * Skip it for non-hierarchical taxonomies for performance sake. */ $this->_rows( $taxonomy, $this->items, $children, $offset, $number, $count ); } else { foreach ( $this->items as $term ) { $this->single_row( $term ); } } } /** * @param string $taxonomy * @param array $terms * @param array $children * @param int $start * @param int $per_page * @param int $count * @param int $parent_term * @param int $level */ private function _rows( $taxonomy, $terms, &$children, $start, $per_page, &$count, $parent_term = 0, $level = 0 ) { $end = $start + $per_page; foreach ( $terms as $key => $term ) { if ( $count >= $end ) { break; } if ( $term->parent !== $parent_term && empty( $_REQUEST['s'] ) ) { continue; } // If the page starts in a subtree, print the parents. if ( $count === $start && $term->parent > 0 && empty( $_REQUEST['s'] ) ) { $my_parents = array(); $parent_ids = array(); $p = $term->parent; while ( $p ) { $my_parent = get_term( $p, $taxonomy ); $my_parents[] = $my_parent; $p = $my_parent->parent; if ( in_array( $p, $parent_ids, true ) ) { // Prevent parent loops. break; } $parent_ids[] = $p; } unset( $parent_ids ); $num_parents = count( $my_parents ); while ( $my_parent = array_pop( $my_parents ) ) { echo "\t"; $this->single_row( $my_parent, $level - $num_parents ); $num_parents--; } } if ( $count >= $start ) { echo "\t"; $this->single_row( $term, $level ); } ++$count; unset( $terms[ $key ] ); if ( isset( $children[ $term->term_id ] ) && empty( $_REQUEST['s'] ) ) { $this->_rows( $taxonomy, $terms, $children, $start, $per_page, $count, $term->term_id, $level + 1 ); } } } /** * @global string $taxonomy * @param WP_Term $tag Term object. * @param int $level */ public function single_row( $tag, $level = 0 ) { global $taxonomy; $tag = sanitize_term( $tag, $taxonomy ); $this->level = $level; if ( $tag->parent ) { $count = count( get_ancestors( $tag->term_id, $taxonomy, 'taxonomy' ) ); $level = 'level-' . $count; } else { $level = 'level-0'; } echo '<tr id="tag-' . $tag->term_id . '" class="' . $level . '">'; $this->single_row_columns( $tag ); echo '</tr>'; } /** * @since 5.9.0 Renamed `$tag` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Term $item Term object. * @return string */ public function column_cb( $item ) { // Restores the more descriptive, specific name for use within this method. $tag = $item; if ( current_user_can( 'delete_term', $tag->term_id ) ) { return sprintf( '<label class="screen-reader-text" for="cb-select-%1$s">%2$s</label>' . '<input type="checkbox" name="delete_tags[]" value="%1$s" id="cb-select-%1$s" />', $tag->term_id, /* translators: %s: Taxonomy term name. */ sprintf( __( 'Select %s' ), $tag->name ) ); } return '&nbsp;'; } /** * @param WP_Term $tag Term object. * @return string */ public function column_name( $tag ) { $taxonomy = $this->screen->taxonomy; $pad = str_repeat( '&#8212; ', max( 0, $this->level ) ); /** * Filters display of the term name in the terms list table. * * The default output may include padding due to the term's * current level in the term hierarchy. * * @since 2.5.0 * * @see WP_Terms_List_Table::column_name() * * @param string $pad_tag_name The term name, padded if not top-level. * @param WP_Term $tag Term object. */ $name = apply_filters( 'term_name', $pad . ' ' . $tag->name, $tag ); $qe_data = get_term( $tag->term_id, $taxonomy, OBJECT, 'edit' ); $uri = wp_doing_ajax() ? wp_get_referer() : $_SERVER['REQUEST_URI']; $edit_link = get_edit_term_link( $tag, $taxonomy, $this->screen->post_type ); if ( $edit_link ) { $edit_link = add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $uri ) ), $edit_link ); $name = sprintf( '<a class="row-title" href="%s" aria-label="%s">%s</a>', esc_url( $edit_link ), /* translators: %s: Taxonomy term name. */ esc_attr( sprintf( __( '&#8220;%s&#8221; (Edit)' ), $tag->name ) ), $name ); } $output = sprintf( '<strong>%s</strong><br />', $name ); $output .= '<div class="hidden" id="inline_' . $qe_data->term_id . '">'; $output .= '<div class="name">' . $qe_data->name . '</div>'; /** This filter is documented in wp-admin/edit-tag-form.php */ $output .= '<div class="slug">' . apply_filters( 'editable_slug', $qe_data->slug, $qe_data ) . '</div>'; $output .= '<div class="parent">' . $qe_data->parent . '</div></div>'; return $output; } /** * Gets the name of the default primary column. * * @since 4.3.0 * * @return string Name of the default primary column, in this case, 'name'. */ protected function get_default_primary_column_name() { return 'name'; } /** * Generates and displays row action links. * * @since 4.3.0 * @since 5.9.0 Renamed `$tag` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Term $item Tag being acted upon. * @param string $column_name Current column name. * @param string $primary Primary column name. * @return string Row actions output for terms, or an empty string * if the current column is not the primary column. */ 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. $tag = $item; $taxonomy = $this->screen->taxonomy; $uri = wp_doing_ajax() ? wp_get_referer() : $_SERVER['REQUEST_URI']; $edit_link = add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $uri ) ), get_edit_term_link( $tag, $taxonomy, $this->screen->post_type ) ); $actions = array(); if ( current_user_can( 'edit_term', $tag->term_id ) ) { $actions['edit'] = sprintf( '<a href="%s" aria-label="%s">%s</a>', esc_url( $edit_link ), /* translators: %s: Taxonomy term name. */ esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $tag->name ) ), __( 'Edit' ) ); $actions['inline hide-if-no-js'] = sprintf( '<button type="button" class="button-link editinline" aria-label="%s" aria-expanded="false">%s</button>', /* translators: %s: Taxonomy term name. */ esc_attr( sprintf( __( 'Quick edit &#8220;%s&#8221; inline' ), $tag->name ) ), __( 'Quick&nbsp;Edit' ) ); } if ( current_user_can( 'delete_term', $tag->term_id ) ) { $actions['delete'] = sprintf( '<a href="%s" class="delete-tag aria-button-if-js" aria-label="%s">%s</a>', wp_nonce_url( "edit-tags.php?action=delete&amp;taxonomy=$taxonomy&amp;tag_ID=$tag->term_id", 'delete-tag_' . $tag->term_id ), /* translators: %s: Taxonomy term name. */ esc_attr( sprintf( __( 'Delete &#8220;%s&#8221;' ), $tag->name ) ), __( 'Delete' ) ); } if ( is_term_publicly_viewable( $tag ) ) { $actions['view'] = sprintf( '<a href="%s" aria-label="%s">%s</a>', get_term_link( $tag ), /* translators: %s: Taxonomy term name. */ esc_attr( sprintf( __( 'View &#8220;%s&#8221; archive' ), $tag->name ) ), __( 'View' ) ); } /** * Filters the action links displayed for each term in the Tags list table. * * @since 2.8.0 * @since 3.0.0 Deprecated in favor of {@see '{$taxonomy}_row_actions'} filter. * @since 5.4.2 Restored (un-deprecated). * * @param string[] $actions An array of action links to be displayed. Default * 'Edit', 'Quick Edit', 'Delete', and 'View'. * @param WP_Term $tag Term object. */ $actions = apply_filters( 'tag_row_actions', $actions, $tag ); /** * Filters the action links displayed for each term in the terms list table. * * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug. * * Possible hook names include: * * - `category_row_actions` * - `post_tag_row_actions` * * @since 3.0.0 * * @param string[] $actions An array of action links to be displayed. Default * 'Edit', 'Quick Edit', 'Delete', and 'View'. * @param WP_Term $tag Term object. */ $actions = apply_filters( "{$taxonomy}_row_actions", $actions, $tag ); return $this->row_actions( $actions ); } /** * @param WP_Term $tag Term object. * @return string */ public function column_description( $tag ) { if ( $tag->description ) { return $tag->description; } else { return '<span aria-hidden="true">&#8212;</span><span class="screen-reader-text">' . __( 'No description' ) . '</span>'; } } /** * @param WP_Term $tag Term object. * @return string */ public function column_slug( $tag ) { /** This filter is documented in wp-admin/edit-tag-form.php */ return apply_filters( 'editable_slug', $tag->slug, $tag ); } /** * @param WP_Term $tag Term object. * @return string */ public function column_posts( $tag ) { $count = number_format_i18n( $tag->count ); $tax = get_taxonomy( $this->screen->taxonomy ); $ptype_object = get_post_type_object( $this->screen->post_type ); if ( ! $ptype_object->show_ui ) { return $count; } if ( $tax->query_var ) { $args = array( $tax->query_var => $tag->slug ); } else { $args = array( 'taxonomy' => $tax->name, 'term' => $tag->slug, ); } if ( 'post' !== $this->screen->post_type ) { $args['post_type'] = $this->screen->post_type; } if ( 'attachment' === $this->screen->post_type ) { return "<a href='" . esc_url( add_query_arg( $args, 'upload.php' ) ) . "'>$count</a>"; } return "<a href='" . esc_url( add_query_arg( $args, 'edit.php' ) ) . "'>$count</a>"; } /** * @param WP_Term $tag Term object. * @return string */ public function column_links( $tag ) { $count = number_format_i18n( $tag->count ); if ( $count ) { $count = "<a href='link-manager.php?cat_id=$tag->term_id'>$count</a>"; } return $count; } /** * @since 5.9.0 Renamed `$tag` to `$item` to match parent class for PHP 8 named parameter support. * * @param WP_Term $item Term object. * @param string $column_name Name of the column. * @return string */ public function column_default( $item, $column_name ) { /** * Filters the displayed columns in the terms list table. * * The dynamic portion of the hook name, `$this->screen->taxonomy`, * refers to the slug of the current taxonomy. * * Possible hook names include: * * - `manage_category_custom_column` * - `manage_post_tag_custom_column` * * @since 2.8.0 * * @param string $string Custom column output. Default empty. * @param string $column_name Name of the column. * @param int $term_id Term ID. */ return apply_filters( "manage_{$this->screen->taxonomy}_custom_column", '', $column_name, $item->term_id ); } /** * Outputs the hidden row displayed when inline editing * * @since 3.1.0 */ public function inline_edit() { $tax = get_taxonomy( $this->screen->taxonomy ); if ( ! current_user_can( $tax->cap->edit_terms ) ) { return; } ?> <form method="get"> <table style="display: none"><tbody id="inlineedit"> <tr id="inline-edit" class="inline-edit-row" style="display: none"> <td colspan="<?php echo $this->get_column_count(); ?>" class="colspanchange"> <div class="inline-edit-wrapper"> <fieldset> <legend class="inline-edit-legend"><?php _e( 'Quick Edit' ); ?></legend> <div class="inline-edit-col"> <label> <span class="title"><?php _ex( 'Name', 'term name' ); ?></span> <span class="input-text-wrap"><input type="text" name="name" class="ptitle" value="" /></span> </label> <label> <span class="title"><?php _e( 'Slug' ); ?></span> <span class="input-text-wrap"><input type="text" name="slug" class="ptitle" value="" /></span> </label> </div> </fieldset> <?php $core_columns = array( 'cb' => true, 'description' => true, 'name' => true, 'slug' => true, 'posts' => true, ); list( $columns ) = $this->get_column_info(); foreach ( $columns as $column_name => $column_display_name ) { if ( isset( $core_columns[ $column_name ] ) ) { continue; } /** This action is documented in wp-admin/includes/class-wp-posts-list-table.php */ do_action( 'quick_edit_custom_box', $column_name, 'edit-tags', $this->screen->taxonomy ); } ?> <div class="inline-edit-save submit"> <button type="button" class="save button button-primary"><?php echo $tax->labels->update_item; ?></button> <button type="button" class="cancel button"><?php _e( 'Cancel' ); ?></button> <span class="spinner"></span> <?php wp_nonce_field( 'taxinlineeditnonce', '_inline_edit', false ); ?> <input type="hidden" name="taxonomy" value="<?php echo esc_attr( $this->screen->taxonomy ); ?>" /> <input type="hidden" name="post_type" value="<?php echo esc_attr( $this->screen->post_type ); ?>" /> <div class="notice notice-error notice-alt inline hidden"> <p class="error"></p> </div> </div> </div> </td></tr> </tbody></table> </form> <?php } } ``` | Uses | Description | | --- | --- | | [WP\_List\_Table](wp_list_table) wp-admin/includes/class-wp-list-table.php | Base class for displaying a list of items in an ajaxified HTML table. | | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
programming_docs
wordpress class WP_REST_Search_Controller {} class WP\_REST\_Search\_Controller {} ===================================== Core class to search through all WordPress content via the REST API. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_search_controller/__construct) β€” Constructor. * [get\_collection\_params](wp_rest_search_controller/get_collection_params) β€” Retrieves the query params for the search results collection. * [get\_item\_schema](wp_rest_search_controller/get_item_schema) β€” Retrieves the item schema, conforming to JSON Schema. * [get\_items](wp_rest_search_controller/get_items) β€” Retrieves a collection of search results. * [get\_items\_permission\_check](wp_rest_search_controller/get_items_permission_check) β€” Checks if a given request has access to search content. * [get\_search\_handler](wp_rest_search_controller/get_search_handler) β€” Gets the search handler to handle the current request. * [prepare\_item\_for\_response](wp_rest_search_controller/prepare_item_for_response) β€” Prepares a single search result for response. * [register\_routes](wp_rest_search_controller/register_routes) β€” Registers the routes for the search controller. * [sanitize\_subtypes](wp_rest_search_controller/sanitize_subtypes) β€” Sanitizes the list of subtypes, to ensure only subtypes of the passed type are included. File: `wp-includes/rest-api/endpoints/class-wp-rest-search-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-search-controller.php/) ``` class WP_REST_Search_Controller extends WP_REST_Controller { /** * ID property name. */ const PROP_ID = 'id'; /** * Title property name. */ const PROP_TITLE = 'title'; /** * URL property name. */ const PROP_URL = 'url'; /** * Type property name. */ const PROP_TYPE = 'type'; /** * Subtype property name. */ const PROP_SUBTYPE = 'subtype'; /** * Identifier for the 'any' type. */ const TYPE_ANY = 'any'; /** * Search handlers used by the controller. * * @since 5.0.0 * @var WP_REST_Search_Handler[] */ protected $search_handlers = array(); /** * Constructor. * * @since 5.0.0 * * @param array $search_handlers List of search handlers to use in the controller. Each search * handler instance must extend the `WP_REST_Search_Handler` class. */ public function __construct( array $search_handlers ) { $this->namespace = 'wp/v2'; $this->rest_base = 'search'; foreach ( $search_handlers as $search_handler ) { if ( ! $search_handler instanceof WP_REST_Search_Handler ) { _doing_it_wrong( __METHOD__, /* translators: %s: PHP class name. */ sprintf( __( 'REST search handlers must extend the %s class.' ), 'WP_REST_Search_Handler' ), '5.0.0' ); continue; } $this->search_handlers[ $search_handler->get_type() ] = $search_handler; } } /** * Registers the routes for the search controller. * * @since 5.0.0 * * @see register_rest_route() */ 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_permission_check' ), 'args' => $this->get_collection_params(), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks if a given request has access to search content. * * @since 5.0.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has search access, WP_Error object otherwise. */ public function get_items_permission_check( $request ) { return true; } /** * Retrieves a collection of search results. * * @since 5.0.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function get_items( $request ) { $handler = $this->get_search_handler( $request ); if ( is_wp_error( $handler ) ) { return $handler; } $result = $handler->search_items( $request ); if ( ! isset( $result[ WP_REST_Search_Handler::RESULT_IDS ] ) || ! is_array( $result[ WP_REST_Search_Handler::RESULT_IDS ] ) || ! isset( $result[ WP_REST_Search_Handler::RESULT_TOTAL ] ) ) { return new WP_Error( 'rest_search_handler_error', __( 'Internal search handler error.' ), array( 'status' => 500 ) ); } $ids = $result[ WP_REST_Search_Handler::RESULT_IDS ]; $results = array(); foreach ( $ids as $id ) { $data = $this->prepare_item_for_response( $id, $request ); $results[] = $this->prepare_response_for_collection( $data ); } $total = (int) $result[ WP_REST_Search_Handler::RESULT_TOTAL ]; $page = (int) $request['page']; $per_page = (int) $request['per_page']; $max_pages = ceil( $total / $per_page ); if ( $page > $max_pages && $total > 0 ) { return new WP_Error( 'rest_search_invalid_page_number', __( 'The page number requested is larger than the number of pages available.' ), array( 'status' => 400 ) ); } $response = rest_ensure_response( $results ); $response->header( 'X-WP-Total', $total ); $response->header( 'X-WP-TotalPages', $max_pages ); $request_params = $request->get_query_params(); $base = add_query_arg( urlencode_deep( $request_params ), rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ) ); if ( $page > 1 ) { $prev_link = add_query_arg( 'page', $page - 1, $base ); $response->link_header( 'prev', $prev_link ); } if ( $page < $max_pages ) { $next_link = add_query_arg( 'page', $page + 1, $base ); $response->link_header( 'next', $next_link ); } return $response; } /** * Prepares a single search result for response. * * @since 5.0.0 * @since 5.6.0 The `$id` parameter can accept a string. * @since 5.9.0 Renamed `$id` to `$item` to match parent class for PHP 8 named parameter support. * * @param int|string $item ID of the item to prepare. * @param WP_REST_Request $request Request object. * @return WP_REST_Response Response object. */ public function prepare_item_for_response( $item, $request ) { // Restores the more descriptive, specific name for use within this method. $item_id = $item; $handler = $this->get_search_handler( $request ); if ( is_wp_error( $handler ) ) { return new WP_REST_Response(); } $fields = $this->get_fields_for_response( $request ); $data = $handler->prepare_item( $item_id, $fields ); $data = $this->add_additional_fields_to_object( $data, $request ); $context = ! empty( $request['context'] ) ? $request['context'] : 'view'; $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 = $handler->prepare_item_links( $item_id ); $links['collection'] = array( 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ), ); $response->add_links( $links ); } return $response; } /** * Retrieves the item schema, conforming to JSON Schema. * * @since 5.0.0 * * @return array Item schema data. */ public function get_item_schema() { if ( $this->schema ) { return $this->add_additional_fields_schema( $this->schema ); } $types = array(); $subtypes = array(); foreach ( $this->search_handlers as $search_handler ) { $types[] = $search_handler->get_type(); $subtypes = array_merge( $subtypes, $search_handler->get_subtypes() ); } $types = array_unique( $types ); $subtypes = array_unique( $subtypes ); $schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'search-result', 'type' => 'object', 'properties' => array( self::PROP_ID => array( 'description' => __( 'Unique identifier for the object.' ), 'type' => array( 'integer', 'string' ), 'context' => array( 'view', 'embed' ), 'readonly' => true, ), self::PROP_TITLE => array( 'description' => __( 'The title for the object.' ), 'type' => 'string', 'context' => array( 'view', 'embed' ), 'readonly' => true, ), self::PROP_URL => array( 'description' => __( 'URL to the object.' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'view', 'embed' ), 'readonly' => true, ), self::PROP_TYPE => array( 'description' => __( 'Object type.' ), 'type' => 'string', 'enum' => $types, 'context' => array( 'view', 'embed' ), 'readonly' => true, ), self::PROP_SUBTYPE => array( 'description' => __( 'Object subtype.' ), 'type' => 'string', 'enum' => $subtypes, 'context' => array( 'view', 'embed' ), 'readonly' => true, ), ), ); $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the query params for the search results collection. * * @since 5.0.0 * * @return array Collection parameters. */ public function get_collection_params() { $types = array(); $subtypes = array(); foreach ( $this->search_handlers as $search_handler ) { $types[] = $search_handler->get_type(); $subtypes = array_merge( $subtypes, $search_handler->get_subtypes() ); } $types = array_unique( $types ); $subtypes = array_unique( $subtypes ); $query_params = parent::get_collection_params(); $query_params['context']['default'] = 'view'; $query_params[ self::PROP_TYPE ] = array( 'default' => $types[0], 'description' => __( 'Limit results to items of an object type.' ), 'type' => 'string', 'enum' => $types, ); $query_params[ self::PROP_SUBTYPE ] = array( 'default' => self::TYPE_ANY, 'description' => __( 'Limit results to items of one or more object subtypes.' ), 'type' => 'array', 'items' => array( 'enum' => array_merge( $subtypes, array( self::TYPE_ANY ) ), 'type' => 'string', ), 'sanitize_callback' => array( $this, 'sanitize_subtypes' ), ); $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(), ); return $query_params; } /** * Sanitizes the list of subtypes, to ensure only subtypes of the passed type are included. * * @since 5.0.0 * * @param string|array $subtypes One or more subtypes. * @param WP_REST_Request $request Full details about the request. * @param string $parameter Parameter name. * @return array|WP_Error List of valid subtypes, or WP_Error object on failure. */ public function sanitize_subtypes( $subtypes, $request, $parameter ) { $subtypes = wp_parse_slug_list( $subtypes ); $subtypes = rest_parse_request_arg( $subtypes, $request, $parameter ); if ( is_wp_error( $subtypes ) ) { return $subtypes; } // 'any' overrides any other subtype. if ( in_array( self::TYPE_ANY, $subtypes, true ) ) { return array( self::TYPE_ANY ); } $handler = $this->get_search_handler( $request ); if ( is_wp_error( $handler ) ) { return $handler; } return array_intersect( $subtypes, $handler->get_subtypes() ); } /** * Gets the search handler to handle the current request. * * @since 5.0.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Search_Handler|WP_Error Search handler for the request type, or WP_Error object on failure. */ protected function get_search_handler( $request ) { $type = $request->get_param( self::PROP_TYPE ); if ( ! $type || ! isset( $this->search_handlers[ $type ] ) ) { return new WP_Error( 'rest_search_invalid_type', __( 'Invalid type parameter.' ), array( 'status' => 400 ) ); } return $this->search_handlers[ $type ]; } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. | wordpress class WP_REST_Sidebars_Controller {} class WP\_REST\_Sidebars\_Controller {} ======================================= Core class used to manage a site’s sidebars. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_sidebars_controller/__construct) β€” Sidebars controller constructor. * [check\_read\_permission](wp_rest_sidebars_controller/check_read_permission) β€” Checks if a sidebar can be read publicly. * [do\_permissions\_check](wp_rest_sidebars_controller/do_permissions_check) β€” Checks if the user has permissions to make the request. * [get\_item](wp_rest_sidebars_controller/get_item) β€” Retrieves one sidebar from the collection. * [get\_item\_permissions\_check](wp_rest_sidebars_controller/get_item_permissions_check) β€” Checks if a given request has access to get a single sidebar. * [get\_item\_schema](wp_rest_sidebars_controller/get_item_schema) β€” Retrieves the block type' schema, conforming to JSON Schema. * [get\_items](wp_rest_sidebars_controller/get_items) β€” Retrieves the list of sidebars (active or inactive). * [get\_items\_permissions\_check](wp_rest_sidebars_controller/get_items_permissions_check) β€” Checks if a given request has access to get sidebars. * [get\_sidebar](wp_rest_sidebars_controller/get_sidebar) β€” Retrieves the registered sidebar with the given id. * [prepare\_item\_for\_response](wp_rest_sidebars_controller/prepare_item_for_response) β€” Prepares a single sidebar output for response. * [prepare\_links](wp_rest_sidebars_controller/prepare_links) β€” Prepares links for the sidebar. * [register\_routes](wp_rest_sidebars_controller/register_routes) β€” Registers the controllers routes. * [retrieve\_widgets](wp_rest_sidebars_controller/retrieve_widgets) β€” Looks for "lost" widgets once per request. * [update\_item](wp_rest_sidebars_controller/update_item) β€” Updates a sidebar. * [update\_item\_permissions\_check](wp_rest_sidebars_controller/update_item_permissions_check) β€” Checks if a given request has access to update sidebars. 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/) ``` class WP_REST_Sidebars_Controller extends WP_REST_Controller { /** * Tracks whether {@see retrieve_widgets()} has been called in the current request. * * @since 5.9.0 * @var bool */ protected $widgets_retrieved = false; /** * Sidebars controller constructor. * * @since 5.8.0 */ public function __construct() { $this->namespace = 'wp/v2'; $this->rest_base = 'sidebars'; } /** * Registers the controllers routes. * * @since 5.8.0 */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => array( 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\w-]+)', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'permission_callback' => array( $this, 'get_item_permissions_check' ), 'args' => array( 'id' => array( 'description' => __( 'The id of a registered sidebar' ), 'type' => 'string', ), 'context' => $this->get_context_param( array( 'default' => 'view' ) ), ), ), array( 'methods' => WP_REST_Server::EDITABLE, 'callback' => array( $this, 'update_item' ), 'permission_callback' => array( $this, 'update_item_permissions_check' ), 'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ), ), 'schema' => array( $this, 'get_public_item_schema' ), ) ); } /** * Checks if a given request has access to get sidebars. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_items_permissions_check( $request ) { $this->retrieve_widgets(); foreach ( wp_get_sidebars_widgets() as $id => $widgets ) { $sidebar = $this->get_sidebar( $id ); if ( ! $sidebar ) { continue; } if ( $this->check_read_permission( $sidebar ) ) { return true; } } return $this->do_permissions_check(); } /** * Retrieves the list of sidebars (active or inactive). * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response Response object on success. */ public function get_items( $request ) { $this->retrieve_widgets(); $data = array(); $permissions_check = $this->do_permissions_check(); foreach ( wp_get_sidebars_widgets() as $id => $widgets ) { $sidebar = $this->get_sidebar( $id ); if ( ! $sidebar ) { continue; } if ( is_wp_error( $permissions_check ) && ! $this->check_read_permission( $sidebar ) ) { continue; } $data[] = $this->prepare_response_for_collection( $this->prepare_item_for_response( $sidebar, $request ) ); } return rest_ensure_response( $data ); } /** * Checks if a given request has access to get a single sidebar. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function get_item_permissions_check( $request ) { $this->retrieve_widgets(); $sidebar = $this->get_sidebar( $request['id'] ); if ( $sidebar && $this->check_read_permission( $sidebar ) ) { return true; } return $this->do_permissions_check(); } /** * Checks if a sidebar can be read publicly. * * @since 5.9.0 * * @param array $sidebar The registered sidebar configuration. * @return bool Whether the side can be read. */ protected function check_read_permission( $sidebar ) { return ! empty( $sidebar['show_in_rest'] ); } /** * Retrieves one sidebar from the collection. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ 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 ); } /** * Checks if a given request has access to update sidebars. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ public function update_item_permissions_check( $request ) { return $this->do_permissions_check(); } /** * Updates a sidebar. * * @since 5.8.0 * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response Response object on success, or WP_Error object on failure. */ public function update_item( $request ) { if ( isset( $request['widgets'] ) ) { $sidebars = wp_get_sidebars_widgets(); foreach ( $sidebars as $sidebar_id => $widgets ) { foreach ( $widgets as $i => $widget_id ) { // This automatically removes the passed widget IDs from any other sidebars in use. if ( $sidebar_id !== $request['id'] && in_array( $widget_id, $request['widgets'], true ) ) { unset( $sidebars[ $sidebar_id ][ $i ] ); } // This automatically removes omitted widget IDs to the inactive sidebar. if ( $sidebar_id === $request['id'] && ! in_array( $widget_id, $request['widgets'], true ) ) { $sidebars['wp_inactive_widgets'][] = $widget_id; } } } $sidebars[ $request['id'] ] = $request['widgets']; wp_set_sidebars_widgets( $sidebars ); } $request['context'] = 'edit'; $sidebar = $this->get_sidebar( $request['id'] ); /** * Fires after a sidebar is updated via the REST API. * * @since 5.8.0 * * @param array $sidebar The updated sidebar. * @param WP_REST_Request $request Request object. */ do_action( 'rest_save_sidebar', $sidebar, $request ); return $this->prepare_item_for_response( $sidebar, $request ); } /** * Checks if the user has permissions to make the request. * * @since 5.8.0 * * @return true|WP_Error True if the request has read access, WP_Error object otherwise. */ protected function do_permissions_check() { // Verify if the current user has edit_theme_options capability. // This capability is required to access the widgets screen. if ( ! current_user_can( 'edit_theme_options' ) ) { return new WP_Error( 'rest_cannot_manage_widgets', __( 'Sorry, you are not allowed to manage widgets on this site.' ), array( 'status' => rest_authorization_required_code() ) ); } return true; } /** * Retrieves the registered sidebar with the given id. * * @since 5.8.0 * * @param string|int $id ID of the sidebar. * @return array|null The discovered sidebar, or null if it is not registered. */ protected function get_sidebar( $id ) { return wp_get_sidebar( $id ); } /** * Looks for "lost" widgets once per request. * * @since 5.9.0 * * @see retrieve_widgets() */ protected function retrieve_widgets() { if ( ! $this->widgets_retrieved ) { retrieve_widgets(); $this->widgets_retrieved = true; } } /** * Prepares a single sidebar output for response. * * @since 5.8.0 * @since 5.9.0 Renamed `$raw_sidebar` to `$item` to match parent class for PHP 8 named parameter support. * * @global array $wp_registered_sidebars The registered sidebars. * @global array $wp_registered_widgets The registered widgets. * * @param array $item Sidebar instance. * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response Prepared response object. */ public function prepare_item_for_response( $item, $request ) { global $wp_registered_sidebars, $wp_registered_widgets; // Restores the more descriptive, specific name for use within this method. $raw_sidebar = $item; $id = $raw_sidebar['id']; $sidebar = array( 'id' => $id ); if ( isset( $wp_registered_sidebars[ $id ] ) ) { $registered_sidebar = $wp_registered_sidebars[ $id ]; $sidebar['status'] = 'active'; $sidebar['name'] = isset( $registered_sidebar['name'] ) ? $registered_sidebar['name'] : ''; $sidebar['description'] = isset( $registered_sidebar['description'] ) ? wp_sidebar_description( $id ) : ''; $sidebar['class'] = isset( $registered_sidebar['class'] ) ? $registered_sidebar['class'] : ''; $sidebar['before_widget'] = isset( $registered_sidebar['before_widget'] ) ? $registered_sidebar['before_widget'] : ''; $sidebar['after_widget'] = isset( $registered_sidebar['after_widget'] ) ? $registered_sidebar['after_widget'] : ''; $sidebar['before_title'] = isset( $registered_sidebar['before_title'] ) ? $registered_sidebar['before_title'] : ''; $sidebar['after_title'] = isset( $registered_sidebar['after_title'] ) ? $registered_sidebar['after_title'] : ''; } else { $sidebar['status'] = 'inactive'; $sidebar['name'] = $raw_sidebar['name']; $sidebar['description'] = ''; $sidebar['class'] = ''; } $fields = $this->get_fields_for_response( $request ); if ( rest_is_field_included( 'widgets', $fields ) ) { $sidebars = wp_get_sidebars_widgets(); $widgets = array_filter( isset( $sidebars[ $sidebar['id'] ] ) ? $sidebars[ $sidebar['id'] ] : array(), static function ( $widget_id ) use ( $wp_registered_widgets ) { return isset( $wp_registered_widgets[ $widget_id ] ); } ); $sidebar['widgets'] = array_values( $widgets ); } $schema = $this->get_item_schema(); $data = array(); foreach ( $schema['properties'] as $property_id => $property ) { if ( isset( $sidebar[ $property_id ] ) && true === rest_validate_value_from_schema( $sidebar[ $property_id ], $property ) ) { $data[ $property_id ] = $sidebar[ $property_id ]; } elseif ( isset( $property['default'] ) ) { $data[ $property_id ] = $property['default']; } } $context = ! empty( $request['context'] ) ? $request['context'] : 'view'; $data = $this->add_additional_fields_to_object( $data, $request ); $data = $this->filter_response_by_context( $data, $context ); $response = rest_ensure_response( $data ); if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) { $response->add_links( $this->prepare_links( $sidebar ) ); } /** * Filters the REST API response for a sidebar. * * @since 5.8.0 * * @param WP_REST_Response $response The response object. * @param array $raw_sidebar The raw sidebar data. * @param WP_REST_Request $request The request object. */ return apply_filters( 'rest_prepare_sidebar', $response, $raw_sidebar, $request ); } /** * Prepares links for the sidebar. * * @since 5.8.0 * * @param array $sidebar Sidebar. * @return array Links for the given widget. */ protected function prepare_links( $sidebar ) { return array( 'collection' => array( 'href' => rest_url( sprintf( '%s/%s', $this->namespace, $this->rest_base ) ), ), 'self' => array( 'href' => rest_url( sprintf( '%s/%s/%s', $this->namespace, $this->rest_base, $sidebar['id'] ) ), ), 'https://api.w.org/widget' => array( 'href' => add_query_arg( 'sidebar', $sidebar['id'], rest_url( '/wp/v2/widgets' ) ), 'embeddable' => true, ), ); } /** * Retrieves the block type' schema, conforming to JSON Schema. * * @since 5.8.0 * * @return array Item schema data. */ public function get_item_schema() { if ( $this->schema ) { return $this->add_additional_fields_schema( $this->schema ); } $schema = array( '$schema' => 'http://json-schema.org/draft-04/schema#', 'title' => 'sidebar', 'type' => 'object', 'properties' => array( 'id' => array( 'description' => __( 'ID of sidebar.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'name' => array( 'description' => __( 'Unique name identifying the sidebar.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'description' => array( 'description' => __( 'Description of sidebar.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'class' => array( 'description' => __( 'Extra CSS class to assign to the sidebar in the Widgets interface.' ), 'type' => 'string', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'before_widget' => array( 'description' => __( 'HTML content to prepend to each widget\'s HTML output when assigned to this sidebar. Default is an opening list item element.' ), 'type' => 'string', 'default' => '', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'after_widget' => array( 'description' => __( 'HTML content to append to each widget\'s HTML output when assigned to this sidebar. Default is a closing list item element.' ), 'type' => 'string', 'default' => '', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'before_title' => array( 'description' => __( 'HTML content to prepend to the sidebar title when displayed. Default is an opening h2 element.' ), 'type' => 'string', 'default' => '', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'after_title' => array( 'description' => __( 'HTML content to append to the sidebar title when displayed. Default is a closing h2 element.' ), 'type' => 'string', 'default' => '', 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'status' => array( 'description' => __( 'Status of sidebar.' ), 'type' => 'string', 'enum' => array( 'active', 'inactive' ), 'context' => array( 'embed', 'view', 'edit' ), 'readonly' => true, ), 'widgets' => array( 'description' => __( 'Nested widgets.' ), 'type' => 'array', 'items' => array( 'type' => array( 'object', 'string' ), ), 'default' => array(), 'context' => array( 'embed', 'view', 'edit' ), ), ), ); $this->schema = $schema; return $this->add_additional_fields_schema( $this->schema ); } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
programming_docs
wordpress class Requests_IRI {} class Requests\_IRI {} ====================== IRI parser/serialiser/normaliser Copyright (c) 2007-2010, Geoffrey Sneddon and Steve Minutillo. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the SimplePie Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * [\_\_construct](requests_iri/__construct) β€” Create a new IRI object, from a specified string * [\_\_get](requests_iri/__get) β€” Overload \_\_get() to provide access via properties * [\_\_isset](requests_iri/__isset) β€” Overload \_\_isset() to provide access via properties * [\_\_set](requests_iri/__set) β€” Overload \_\_set() to provide access via properties * [\_\_toString](requests_iri/__tostring) β€” Return the entire IRI when you try and read the object as a string * [\_\_unset](requests_iri/__unset) β€” Overload \_\_unset() to provide access via properties * [absolutize](requests_iri/absolutize) β€” Create a new IRI object by resolving a relative IRI * [get\_authority](requests_iri/get_authority) β€” Get the complete authority * [get\_iauthority](requests_iri/get_iauthority) β€” Get the complete iauthority * [get\_iri](requests_iri/get_iri) β€” Get the complete IRI * [get\_uri](requests_iri/get_uri) β€” Get the complete URI * [is\_valid](requests_iri/is_valid) β€” Check if the object represents a valid IRI. This needs to be done on each call as some things change depending on another part of the IRI. * [parse\_iri](requests_iri/parse_iri) β€” Parse an IRI into scheme/authority/path/query/fragment segments * [remove\_dot\_segments](requests_iri/remove_dot_segments) β€” Remove dot segments from a path * [remove\_iunreserved\_percent\_encoded](requests_iri/remove_iunreserved_percent_encoded) β€” Callback function for preg\_replace\_callback. * [replace\_invalid\_with\_pct\_encoding](requests_iri/replace_invalid_with_pct_encoding) β€” Replace invalid character with percent encoding * [scheme\_normalization](requests_iri/scheme_normalization) * [set\_authority](requests_iri/set_authority) β€” Set the authority. Returns true on success, false on failure (if there are any invalid characters). * [set\_fragment](requests_iri/set_fragment) β€” Set the ifragment. * [set\_host](requests_iri/set_host) β€” Set the ihost. Returns true on success, false on failure (if there are any invalid characters). * [set\_iri](requests_iri/set_iri) β€” Set the entire IRI. Returns true on success, false on failure (if there are any invalid characters). * [set\_path](requests_iri/set_path) β€” Set the ipath. * [set\_port](requests_iri/set_port) β€” Set the port. Returns true on success, false on failure (if there are any invalid characters). * [set\_query](requests_iri/set_query) β€” Set the iquery. * [set\_scheme](requests_iri/set_scheme) β€” Set the scheme. Returns true on success, false on failure (if there are any invalid characters). * [set\_userinfo](requests_iri/set_userinfo) β€” Set the iuserinfo. * [to\_uri](requests_iri/to_uri) β€” Convert an IRI to a URI (or parts thereof) File: `wp-includes/Requests/IRI.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/iri.php/) ``` class Requests_IRI { /** * Scheme * * @var string|null */ protected $scheme = null; /** * User Information * * @var string|null */ protected $iuserinfo = null; /** * ihost * * @var string|null */ protected $ihost = null; /** * Port * * @var string|null */ protected $port = null; /** * ipath * * @var string */ protected $ipath = ''; /** * iquery * * @var string|null */ protected $iquery = null; /** * ifragment|null * * @var string */ protected $ifragment = null; /** * Normalization database * * Each key is the scheme, each value is an array with each key as the IRI * part and value as the default value for that part. * * @var array */ protected $normalization = array( 'acap' => array( 'port' => 674 ), 'dict' => array( 'port' => 2628 ), 'file' => array( 'ihost' => 'localhost' ), 'http' => array( 'port' => 80, ), 'https' => array( 'port' => 443, ), ); /** * Return the entire IRI when you try and read the object as a string * * @return string */ public function __toString() { return $this->get_iri(); } /** * Overload __set() to provide access via properties * * @param string $name Property name * @param mixed $value Property value */ public function __set($name, $value) { if (method_exists($this, 'set_' . $name)) { call_user_func(array($this, 'set_' . $name), $value); } elseif ( $name === 'iauthority' || $name === 'iuserinfo' || $name === 'ihost' || $name === 'ipath' || $name === 'iquery' || $name === 'ifragment' ) { call_user_func(array($this, 'set_' . substr($name, 1)), $value); } } /** * Overload __get() to provide access via properties * * @param string $name Property name * @return mixed */ public function __get($name) { // isset() returns false for null, we don't want to do that // Also why we use array_key_exists below instead of isset() $props = get_object_vars($this); if ( $name === 'iri' || $name === 'uri' || $name === 'iauthority' || $name === 'authority' ) { $method = 'get_' . $name; $return = $this->$method(); } elseif (array_key_exists($name, $props)) { $return = $this->$name; } // host -> ihost elseif (($prop = 'i' . $name) && array_key_exists($prop, $props)) { $name = $prop; $return = $this->$prop; } // ischeme -> scheme elseif (($prop = substr($name, 1)) && array_key_exists($prop, $props)) { $name = $prop; $return = $this->$prop; } else { trigger_error('Undefined property: ' . get_class($this) . '::' . $name, E_USER_NOTICE); $return = null; } if ($return === null && isset($this->normalization[$this->scheme][$name])) { return $this->normalization[$this->scheme][$name]; } else { return $return; } } /** * Overload __isset() to provide access via properties * * @param string $name Property name * @return bool */ public function __isset($name) { return (method_exists($this, 'get_' . $name) || isset($this->$name)); } /** * Overload __unset() to provide access via properties * * @param string $name Property name */ public function __unset($name) { if (method_exists($this, 'set_' . $name)) { call_user_func(array($this, 'set_' . $name), ''); } } /** * Create a new IRI object, from a specified string * * @param string|null $iri */ public function __construct($iri = null) { $this->set_iri($iri); } /** * Create a new IRI object by resolving a relative IRI * * Returns false if $base is not absolute, otherwise an IRI. * * @param Requests_IRI|string $base (Absolute) Base IRI * @param Requests_IRI|string $relative Relative IRI * @return Requests_IRI|false */ public static function absolutize($base, $relative) { if (!($relative instanceof Requests_IRI)) { $relative = new Requests_IRI($relative); } if (!$relative->is_valid()) { return false; } elseif ($relative->scheme !== null) { return clone $relative; } if (!($base instanceof Requests_IRI)) { $base = new Requests_IRI($base); } if ($base->scheme === null || !$base->is_valid()) { return false; } if ($relative->get_iri() !== '') { if ($relative->iuserinfo !== null || $relative->ihost !== null || $relative->port !== null) { $target = clone $relative; $target->scheme = $base->scheme; } else { $target = new Requests_IRI; $target->scheme = $base->scheme; $target->iuserinfo = $base->iuserinfo; $target->ihost = $base->ihost; $target->port = $base->port; if ($relative->ipath !== '') { if ($relative->ipath[0] === '/') { $target->ipath = $relative->ipath; } elseif (($base->iuserinfo !== null || $base->ihost !== null || $base->port !== null) && $base->ipath === '') { $target->ipath = '/' . $relative->ipath; } elseif (($last_segment = strrpos($base->ipath, '/')) !== false) { $target->ipath = substr($base->ipath, 0, $last_segment + 1) . $relative->ipath; } else { $target->ipath = $relative->ipath; } $target->ipath = $target->remove_dot_segments($target->ipath); $target->iquery = $relative->iquery; } else { $target->ipath = $base->ipath; if ($relative->iquery !== null) { $target->iquery = $relative->iquery; } elseif ($base->iquery !== null) { $target->iquery = $base->iquery; } } $target->ifragment = $relative->ifragment; } } else { $target = clone $base; $target->ifragment = null; } $target->scheme_normalization(); return $target; } /** * Parse an IRI into scheme/authority/path/query/fragment segments * * @param string $iri * @return array */ protected function parse_iri($iri) { $iri = trim($iri, "\x20\x09\x0A\x0C\x0D"); $has_match = preg_match('/^((?P<scheme>[^:\/?#]+):)?(\/\/(?P<authority>[^\/?#]*))?(?P<path>[^?#]*)(\?(?P<query>[^#]*))?(#(?P<fragment>.*))?$/', $iri, $match); if (!$has_match) { throw new Requests_Exception('Cannot parse supplied IRI', 'iri.cannot_parse', $iri); } if ($match[1] === '') { $match['scheme'] = null; } if (!isset($match[3]) || $match[3] === '') { $match['authority'] = null; } if (!isset($match[5])) { $match['path'] = ''; } if (!isset($match[6]) || $match[6] === '') { $match['query'] = null; } if (!isset($match[8]) || $match[8] === '') { $match['fragment'] = null; } return $match; } /** * Remove dot segments from a path * * @param string $input * @return string */ protected function remove_dot_segments($input) { $output = ''; while (strpos($input, './') !== false || strpos($input, '/.') !== false || $input === '.' || $input === '..') { // A: If the input buffer begins with a prefix of "../" or "./", // then remove that prefix from the input buffer; otherwise, if (strpos($input, '../') === 0) { $input = substr($input, 3); } elseif (strpos($input, './') === 0) { $input = substr($input, 2); } // B: if the input buffer begins with a prefix of "/./" or "/.", // where "." is a complete path segment, then replace that prefix // with "/" in the input buffer; otherwise, elseif (strpos($input, '/./') === 0) { $input = substr($input, 2); } elseif ($input === '/.') { $input = '/'; } // C: if the input buffer begins with a prefix of "/../" or "/..", // where ".." is a complete path segment, then replace that prefix // with "/" in the input buffer and remove the last segment and its // preceding "/" (if any) from the output buffer; otherwise, elseif (strpos($input, '/../') === 0) { $input = substr($input, 3); $output = substr_replace($output, '', strrpos($output, '/')); } elseif ($input === '/..') { $input = '/'; $output = substr_replace($output, '', strrpos($output, '/')); } // D: if the input buffer consists only of "." or "..", then remove // that from the input buffer; otherwise, elseif ($input === '.' || $input === '..') { $input = ''; } // E: move the first path segment in the input buffer to the end of // the output buffer, including the initial "/" character (if any) // and any subsequent characters up to, but not including, the next // "/" character or the end of the input buffer elseif (($pos = strpos($input, '/', 1)) !== false) { $output .= substr($input, 0, $pos); $input = substr_replace($input, '', 0, $pos); } else { $output .= $input; $input = ''; } } return $output . $input; } /** * Replace invalid character with percent encoding * * @param string $string Input string * @param string $extra_chars Valid characters not in iunreserved or * iprivate (this is ASCII-only) * @param bool $iprivate Allow iprivate * @return string */ protected function replace_invalid_with_pct_encoding($string, $extra_chars, $iprivate = false) { // Normalize as many pct-encoded sections as possible $string = preg_replace_callback('/(?:%[A-Fa-f0-9]{2})+/', array($this, 'remove_iunreserved_percent_encoded'), $string); // Replace invalid percent characters $string = preg_replace('/%(?![A-Fa-f0-9]{2})/', '%25', $string); // Add unreserved and % to $extra_chars (the latter is safe because all // pct-encoded sections are now valid). $extra_chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~%'; // Now replace any bytes that aren't allowed with their pct-encoded versions $position = 0; $strlen = strlen($string); while (($position += strspn($string, $extra_chars, $position)) < $strlen) { $value = ord($string[$position]); // Start position $start = $position; // By default we are valid $valid = true; // No one byte sequences are valid due to the while. // Two byte sequence: if (($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 { $valid = false; $length = 1; $remaining = 0; } if ($remaining) { if ($position + $length <= $strlen) { for ($position++; $remaining; $position++) { $value = ord($string[$position]); // Check that the byte is valid, then add it to the character: if (($value & 0xC0) === 0x80) { $character |= ($value & 0x3F) << (--$remaining * 6); } // If it is invalid, count the sequence as invalid and reprocess the current byte: else { $valid = false; $position--; break; } } } else { $position = $strlen - 1; $valid = false; } } // Percent encode anything invalid or not in ucschar if ( // Invalid sequences !$valid // 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 < 0xA0 || $character > 0xEFFFD ) && ( // Everything not in iprivate, if it applies !$iprivate || $character < 0xE000 || $character > 0x10FFFD ) ) { // If we were a character, pretend we weren't, but rather an error. if ($valid) { $position--; } for ($j = $start; $j <= $position; $j++) { $string = substr_replace($string, sprintf('%%%02X', ord($string[$j])), $j, 1); $j += 2; $position += 2; $strlen += 2; } } } return $string; } /** * Callback function for preg_replace_callback. * * Removes sequences of percent encoded bytes that represent UTF-8 * encoded characters in iunreserved * * @param array $match PCRE match * @return string Replacement */ protected function remove_iunreserved_percent_encoded($match) { // As we just have valid percent encoded sequences we can just explode // and ignore the first member of the returned array (an empty string). $bytes = explode('%', $match[0]); // Initialize the new string (this is what will be returned) and that // there are no bytes remaining in the current sequence (unsurprising // at the first byte!). $string = ''; $remaining = 0; // Loop over each and every byte, and set $value to its value for ($i = 1, $len = count($bytes); $i < $len; $i++) { $value = hexdec($bytes[$i]); // If we're the first byte of sequence: if (!$remaining) { // Start position $start = $i; // By default we are valid $valid = true; // One byte sequence: if ($value <= 0x7F) { $character = $value; $length = 1; } // 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 { $valid = false; $remaining = 0; } } // Continuation byte: else { // Check that the byte is valid, then add it to the character: if (($value & 0xC0) === 0x80) { $remaining--; $character |= ($value & 0x3F) << ($remaining * 6); } // If it is invalid, count the sequence as invalid and reprocess the current byte as the start of a sequence: else { $valid = false; $remaining = 0; $i--; } } // If we've reached the end of the current byte sequence, append it to Unicode::$data if (!$remaining) { // Percent encode anything invalid or not in iunreserved if ( // Invalid sequences !$valid // Non-shortest form sequences are invalid || $length > 1 && $character <= 0x7F || $length > 2 && $character <= 0x7FF || $length > 3 && $character <= 0xFFFF // Outside of range of iunreserved codepoints || $character < 0x2D || $character > 0xEFFFD // Noncharacters || ($character & 0xFFFE) === 0xFFFE || $character >= 0xFDD0 && $character <= 0xFDEF // Everything else not in iunreserved (this is all BMP) || $character === 0x2F || $character > 0x39 && $character < 0x41 || $character > 0x5A && $character < 0x61 || $character > 0x7A && $character < 0x7E || $character > 0x7E && $character < 0xA0 || $character > 0xD7FF && $character < 0xF900 ) { for ($j = $start; $j <= $i; $j++) { $string .= '%' . strtoupper($bytes[$j]); } } else { for ($j = $start; $j <= $i; $j++) { $string .= chr(hexdec($bytes[$j])); } } } } // If we have any bytes left over they are invalid (i.e., we are // mid-way through a multi-byte sequence) if ($remaining) { for ($j = $start; $j < $len; $j++) { $string .= '%' . strtoupper($bytes[$j]); } } return $string; } protected function scheme_normalization() { if (isset($this->normalization[$this->scheme]['iuserinfo']) && $this->iuserinfo === $this->normalization[$this->scheme]['iuserinfo']) { $this->iuserinfo = null; } if (isset($this->normalization[$this->scheme]['ihost']) && $this->ihost === $this->normalization[$this->scheme]['ihost']) { $this->ihost = null; } if (isset($this->normalization[$this->scheme]['port']) && $this->port === $this->normalization[$this->scheme]['port']) { $this->port = null; } if (isset($this->normalization[$this->scheme]['ipath']) && $this->ipath === $this->normalization[$this->scheme]['ipath']) { $this->ipath = ''; } if (isset($this->ihost) && empty($this->ipath)) { $this->ipath = '/'; } if (isset($this->normalization[$this->scheme]['iquery']) && $this->iquery === $this->normalization[$this->scheme]['iquery']) { $this->iquery = null; } if (isset($this->normalization[$this->scheme]['ifragment']) && $this->ifragment === $this->normalization[$this->scheme]['ifragment']) { $this->ifragment = null; } } /** * Check if the object represents a valid IRI. This needs to be done on each * call as some things change depending on another part of the IRI. * * @return bool */ public function is_valid() { $isauthority = $this->iuserinfo !== null || $this->ihost !== null || $this->port !== null; if ($this->ipath !== '' && ( $isauthority && $this->ipath[0] !== '/' || ( $this->scheme === null && !$isauthority && strpos($this->ipath, ':') !== false && (strpos($this->ipath, '/') === false ? true : strpos($this->ipath, ':') < strpos($this->ipath, '/')) ) ) ) { return false; } return true; } /** * Set the entire IRI. Returns true on success, false on failure (if there * are any invalid characters). * * @param string $iri * @return bool */ protected function set_iri($iri) { static $cache; if (!$cache) { $cache = array(); } if ($iri === null) { return true; } if (isset($cache[$iri])) { list($this->scheme, $this->iuserinfo, $this->ihost, $this->port, $this->ipath, $this->iquery, $this->ifragment, $return) = $cache[$iri]; return $return; } $parsed = $this->parse_iri((string) $iri); $return = $this->set_scheme($parsed['scheme']) && $this->set_authority($parsed['authority']) && $this->set_path($parsed['path']) && $this->set_query($parsed['query']) && $this->set_fragment($parsed['fragment']); $cache[$iri] = array($this->scheme, $this->iuserinfo, $this->ihost, $this->port, $this->ipath, $this->iquery, $this->ifragment, $return); return $return; } /** * Set the scheme. Returns true on success, false on failure (if there are * any invalid characters). * * @param string $scheme * @return bool */ protected function set_scheme($scheme) { if ($scheme === null) { $this->scheme = null; } elseif (!preg_match('/^[A-Za-z][0-9A-Za-z+\-.]*$/', $scheme)) { $this->scheme = null; return false; } else { $this->scheme = strtolower($scheme); } return true; } /** * Set the authority. Returns true on success, false on failure (if there are * any invalid characters). * * @param string $authority * @return bool */ protected function set_authority($authority) { static $cache; if (!$cache) { $cache = array(); } if ($authority === null) { $this->iuserinfo = null; $this->ihost = null; $this->port = null; return true; } if (isset($cache[$authority])) { list($this->iuserinfo, $this->ihost, $this->port, $return) = $cache[$authority]; return $return; } $remaining = $authority; if (($iuserinfo_end = strrpos($remaining, '@')) !== false) { $iuserinfo = substr($remaining, 0, $iuserinfo_end); $remaining = substr($remaining, $iuserinfo_end + 1); } else { $iuserinfo = null; } if (($port_start = strpos($remaining, ':', strpos($remaining, ']'))) !== false) { $port = substr($remaining, $port_start + 1); if ($port === false || $port === '') { $port = null; } $remaining = substr($remaining, 0, $port_start); } else { $port = null; } $return = $this->set_userinfo($iuserinfo) && $this->set_host($remaining) && $this->set_port($port); $cache[$authority] = array($this->iuserinfo, $this->ihost, $this->port, $return); return $return; } /** * Set the iuserinfo. * * @param string $iuserinfo * @return bool */ protected function set_userinfo($iuserinfo) { if ($iuserinfo === null) { $this->iuserinfo = null; } else { $this->iuserinfo = $this->replace_invalid_with_pct_encoding($iuserinfo, '!$&\'()*+,;=:'); $this->scheme_normalization(); } return true; } /** * Set the ihost. Returns true on success, false on failure (if there are * any invalid characters). * * @param string $ihost * @return bool */ protected function set_host($ihost) { if ($ihost === null) { $this->ihost = null; return true; } if (substr($ihost, 0, 1) === '[' && substr($ihost, -1) === ']') { if (Requests_IPv6::check_ipv6(substr($ihost, 1, -1))) { $this->ihost = '[' . Requests_IPv6::compress(substr($ihost, 1, -1)) . ']'; } else { $this->ihost = null; return false; } } else { $ihost = $this->replace_invalid_with_pct_encoding($ihost, '!$&\'()*+,;='); // Lowercase, but ignore pct-encoded sections (as they should // remain uppercase). This must be done after the previous step // as that can add unescaped characters. $position = 0; $strlen = strlen($ihost); while (($position += strcspn($ihost, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ%', $position)) < $strlen) { if ($ihost[$position] === '%') { $position += 3; } else { $ihost[$position] = strtolower($ihost[$position]); $position++; } } $this->ihost = $ihost; } $this->scheme_normalization(); return true; } /** * Set the port. Returns true on success, false on failure (if there are * any invalid characters). * * @param string $port * @return bool */ protected function set_port($port) { if ($port === null) { $this->port = null; return true; } if (strspn($port, '0123456789') === strlen($port)) { $this->port = (int) $port; $this->scheme_normalization(); return true; } $this->port = null; return false; } /** * Set the ipath. * * @param string $ipath * @return bool */ protected function set_path($ipath) { static $cache; if (!$cache) { $cache = array(); } $ipath = (string) $ipath; if (isset($cache[$ipath])) { $this->ipath = $cache[$ipath][(int) ($this->scheme !== null)]; } else { $valid = $this->replace_invalid_with_pct_encoding($ipath, '!$&\'()*+,;=@:/'); $removed = $this->remove_dot_segments($valid); $cache[$ipath] = array($valid, $removed); $this->ipath = ($this->scheme !== null) ? $removed : $valid; } $this->scheme_normalization(); return true; } /** * Set the iquery. * * @param string $iquery * @return bool */ protected function set_query($iquery) { if ($iquery === null) { $this->iquery = null; } else { $this->iquery = $this->replace_invalid_with_pct_encoding($iquery, '!$&\'()*+,;=:@/?', true); $this->scheme_normalization(); } return true; } /** * Set the ifragment. * * @param string $ifragment * @return bool */ protected function set_fragment($ifragment) { if ($ifragment === null) { $this->ifragment = null; } else { $this->ifragment = $this->replace_invalid_with_pct_encoding($ifragment, '!$&\'()*+,;=:@/?'); $this->scheme_normalization(); } return true; } /** * Convert an IRI to a URI (or parts thereof) * * @param string|bool IRI to convert (or false from {@see get_iri}) * @return string|false URI if IRI is valid, false otherwise. */ protected function to_uri($string) { if (!is_string($string)) { return false; } static $non_ascii; if (!$non_ascii) { $non_ascii = implode('', range("\x80", "\xFF")); } $position = 0; $strlen = strlen($string); while (($position += strcspn($string, $non_ascii, $position)) < $strlen) { $string = substr_replace($string, sprintf('%%%02X', ord($string[$position])), $position, 1); $position += 3; $strlen += 2; } return $string; } /** * Get the complete IRI * * @return string|false */ protected function get_iri() { if (!$this->is_valid()) { return false; } $iri = ''; if ($this->scheme !== null) { $iri .= $this->scheme . ':'; } if (($iauthority = $this->get_iauthority()) !== null) { $iri .= '//' . $iauthority; } $iri .= $this->ipath; if ($this->iquery !== null) { $iri .= '?' . $this->iquery; } if ($this->ifragment !== null) { $iri .= '#' . $this->ifragment; } return $iri; } /** * Get the complete URI * * @return string */ protected function get_uri() { return $this->to_uri($this->get_iri()); } /** * Get the complete iauthority * * @return string|null */ protected function get_iauthority() { if ($this->iuserinfo === null && $this->ihost === null && $this->port === null) { return null; } $iauthority = ''; if ($this->iuserinfo !== null) { $iauthority .= $this->iuserinfo . '@'; } if ($this->ihost !== null) { $iauthority .= $this->ihost; } if ($this->port !== null) { $iauthority .= ':' . $this->port; } return $iauthority; } /** * Get the complete authority * * @return string */ protected function get_authority() { $iauthority = $this->get_iauthority(); if (is_string($iauthority)) { return $this->to_uri($iauthority); } else { return $iauthority; } } } ```
programming_docs
wordpress class AtomParser {} class AtomParser {} =================== AtomLib Atom Parser API * [\_\_construct](atomparser/__construct) β€” PHP5 constructor. * [\_default](atomparser/_default) * [\_p](atomparser/_p) * [AtomParser](atomparser/atomparser) β€” PHP4 constructor. * [cdata](atomparser/cdata) * [end\_element](atomparser/end_element) * [end\_ns](atomparser/end_ns) * [error\_handler](atomparser/error_handler) * [is\_declared\_content\_ns](atomparser/is_declared_content_ns) * [map\_attrs](atomparser/map_attrs) β€” Map attributes to key="val" * [map\_xmlns](atomparser/map_xmlns) β€” Map XML namespace to string. * [ns\_to\_prefix](atomparser/ns_to_prefix) * [parse](atomparser/parse) * [start\_element](atomparser/start_element) * [start\_ns](atomparser/start_ns) * [xml\_escape](atomparser/xml_escape) File: `wp-includes/atomlib.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/atomlib.php/) ``` class AtomParser { var $NS = 'http://www.w3.org/2005/Atom'; var $ATOM_CONTENT_ELEMENTS = array('content','summary','title','subtitle','rights'); var $ATOM_SIMPLE_ELEMENTS = array('id','updated','published','draft'); var $debug = false; var $depth = 0; var $indent = 2; var $in_content; var $ns_contexts = array(); var $ns_decls = array(); var $content_ns_decls = array(); var $content_ns_contexts = array(); var $is_xhtml = false; var $is_html = false; var $is_text = true; var $skipped_div = false; var $FILE = "php://input"; var $feed; var $current; /** * PHP5 constructor. */ function __construct() { $this->feed = new AtomFeed(); $this->current = null; $this->map_attrs_func = array( __CLASS__, 'map_attrs' ); $this->map_xmlns_func = array( __CLASS__, 'map_xmlns' ); } /** * PHP4 constructor. */ public function AtomParser() { self::__construct(); } /** * Map attributes to key="val" * * @param string $k Key * @param string $v Value * @return string */ public static function map_attrs($k, $v) { return "$k=\"$v\""; } /** * Map XML namespace to string. * * @param indexish $p XML Namespace element index * @param array $n Two-element array pair. [ 0 => {namespace}, 1 => {url} ] * @return string 'xmlns="{url}"' or 'xmlns:{namespace}="{url}"' */ public static function map_xmlns($p, $n) { $xd = "xmlns"; if( 0 < strlen($n[0]) ) { $xd .= ":{$n[0]}"; } return "{$xd}=\"{$n[1]}\""; } function _p($msg) { if($this->debug) { print str_repeat(" ", $this->depth * $this->indent) . $msg ."\n"; } } function error_handler($log_level, $log_text, $error_file, $error_line) { $this->error = $log_text; } function parse() { set_error_handler(array(&$this, 'error_handler')); array_unshift($this->ns_contexts, array()); if ( ! function_exists( 'xml_parser_create_ns' ) ) { trigger_error( __( "PHP's XML extension is not available. Please contact your hosting provider to enable PHP's XML extension." ) ); return false; } $parser = xml_parser_create_ns(); xml_set_object($parser, $this); xml_set_element_handler($parser, "start_element", "end_element"); xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0); xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,0); xml_set_character_data_handler($parser, "cdata"); xml_set_default_handler($parser, "_default"); xml_set_start_namespace_decl_handler($parser, "start_ns"); xml_set_end_namespace_decl_handler($parser, "end_ns"); $this->content = ''; $ret = true; $fp = fopen($this->FILE, "r"); while ($data = fread($fp, 4096)) { if($this->debug) $this->content .= $data; if(!xml_parse($parser, $data, feof($fp))) { /* translators: 1: Error message, 2: Line number. */ trigger_error(sprintf(__('XML Error: %1$s at line %2$s')."\n", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); $ret = false; break; } } fclose($fp); xml_parser_free($parser); unset($parser); restore_error_handler(); return $ret; } function start_element($parser, $name, $attrs) { $name_parts = explode(":", $name); $tag = array_pop($name_parts); switch($name) { case $this->NS . ':feed': $this->current = $this->feed; break; case $this->NS . ':entry': $this->current = new AtomEntry(); break; }; $this->_p("start_element('$name')"); #$this->_p(print_r($this->ns_contexts,true)); #$this->_p('current(' . $this->current . ')'); array_unshift($this->ns_contexts, $this->ns_decls); $this->depth++; if(!empty($this->in_content)) { $this->content_ns_decls = array(); if($this->is_html || $this->is_text) trigger_error("Invalid content in element found. Content must not be of type text or html if it contains markup."); $attrs_prefix = array(); // resolve prefixes for attributes foreach($attrs as $key => $value) { $with_prefix = $this->ns_to_prefix($key, true); $attrs_prefix[$with_prefix[1]] = $this->xml_escape($value); } $attrs_str = join(' ', array_map($this->map_attrs_func, array_keys($attrs_prefix), array_values($attrs_prefix))); if(strlen($attrs_str) > 0) { $attrs_str = " " . $attrs_str; } $with_prefix = $this->ns_to_prefix($name); if(!$this->is_declared_content_ns($with_prefix[0])) { array_push($this->content_ns_decls, $with_prefix[0]); } $xmlns_str = ''; if(count($this->content_ns_decls) > 0) { array_unshift($this->content_ns_contexts, $this->content_ns_decls); $xmlns_str .= join(' ', array_map($this->map_xmlns_func, array_keys($this->content_ns_contexts[0]), array_values($this->content_ns_contexts[0]))); if(strlen($xmlns_str) > 0) { $xmlns_str = " " . $xmlns_str; } } array_push($this->in_content, array($tag, $this->depth, "<". $with_prefix[1] ."{$xmlns_str}{$attrs_str}" . ">")); } else if(in_array($tag, $this->ATOM_CONTENT_ELEMENTS) || in_array($tag, $this->ATOM_SIMPLE_ELEMENTS)) { $this->in_content = array(); $this->is_xhtml = $attrs['type'] == 'xhtml'; $this->is_html = $attrs['type'] == 'html' || $attrs['type'] == 'text/html'; $this->is_text = !in_array('type',array_keys($attrs)) || $attrs['type'] == 'text'; $type = $this->is_xhtml ? 'XHTML' : ($this->is_html ? 'HTML' : ($this->is_text ? 'TEXT' : $attrs['type'])); if(in_array('src',array_keys($attrs))) { $this->current->$tag = $attrs; } else { array_push($this->in_content, array($tag,$this->depth, $type)); } } else if($tag == 'link') { array_push($this->current->links, $attrs); } else if($tag == 'category') { array_push($this->current->categories, $attrs); } $this->ns_decls = array(); } function end_element($parser, $name) { $name_parts = explode(":", $name); $tag = array_pop($name_parts); $ccount = count($this->in_content); # if we are *in* content, then let's proceed to serialize it if(!empty($this->in_content)) { # if we are ending the original content element # then let's finalize the content if($this->in_content[0][0] == $tag && $this->in_content[0][1] == $this->depth) { $origtype = $this->in_content[0][2]; array_shift($this->in_content); $newcontent = array(); foreach($this->in_content as $c) { if(count($c) == 3) { array_push($newcontent, $c[2]); } else { if($this->is_xhtml || $this->is_text) { array_push($newcontent, $this->xml_escape($c)); } else { array_push($newcontent, $c); } } } if(in_array($tag, $this->ATOM_CONTENT_ELEMENTS)) { $this->current->$tag = array($origtype, join('',$newcontent)); } else { $this->current->$tag = join('',$newcontent); } $this->in_content = array(); } else if($this->in_content[$ccount-1][0] == $tag && $this->in_content[$ccount-1][1] == $this->depth) { $this->in_content[$ccount-1][2] = substr($this->in_content[$ccount-1][2],0,-1) . "/>"; } else { # else, just finalize the current element's content $endtag = $this->ns_to_prefix($name); array_push($this->in_content, array($tag, $this->depth, "</$endtag[1]>")); } } array_shift($this->ns_contexts); $this->depth--; if($name == ($this->NS . ':entry')) { array_push($this->feed->entries, $this->current); $this->current = null; } $this->_p("end_element('$name')"); } function start_ns($parser, $prefix, $uri) { $this->_p("starting: " . $prefix . ":" . $uri); array_push($this->ns_decls, array($prefix,$uri)); } function end_ns($parser, $prefix) { $this->_p("ending: #" . $prefix . "#"); } function cdata($parser, $data) { $this->_p("data: #" . str_replace(array("\n"), array("\\n"), trim($data)) . "#"); if(!empty($this->in_content)) { array_push($this->in_content, $data); } } function _default($parser, $data) { # when does this gets called? } function ns_to_prefix($qname, $attr=false) { # split 'http://www.w3.org/1999/xhtml:div' into ('http','//www.w3.org/1999/xhtml','div') $components = explode(":", $qname); # grab the last one (e.g 'div') $name = array_pop($components); if(!empty($components)) { # re-join back the namespace component $ns = join(":",$components); foreach($this->ns_contexts as $context) { foreach($context as $mapping) { if($mapping[1] == $ns && strlen($mapping[0]) > 0) { return array($mapping, "$mapping[0]:$name"); } } } } if($attr) { return array(null, $name); } else { foreach($this->ns_contexts as $context) { foreach($context as $mapping) { if(strlen($mapping[0]) == 0) { return array($mapping, $name); } } } } } function is_declared_content_ns($new_mapping) { foreach($this->content_ns_contexts as $context) { foreach($context as $mapping) { if($new_mapping == $mapping) { return true; } } } return false; } function xml_escape($content) { return str_replace(array('&','"',"'",'<','>'), array('&amp;','&quot;','&apos;','&lt;','&gt;'), $content ); } } ``` wordpress class POMO_FileReader {} class POMO\_FileReader {} ========================= * [\_\_construct](pomo_filereader/__construct) * [close](pomo_filereader/close) * [feof](pomo_filereader/feof) * [is\_resource](pomo_filereader/is_resource) * [POMO\_FileReader](pomo_filereader/pomo_filereader) β€” PHP4 constructor. β€” deprecated * [read](pomo_filereader/read) * [read\_all](pomo_filereader/read_all) * [seekto](pomo_filereader/seekto) File: `wp-includes/pomo/streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/streams.php/) ``` class POMO_FileReader extends POMO_Reader { /** * File pointer resource. * * @var resource|false */ public $_f; /** * @param string $filename */ public function __construct( $filename ) { parent::__construct(); $this->_f = fopen( $filename, 'rb' ); } /** * PHP4 constructor. * * @deprecated 5.4.0 Use __construct() instead. * * @see POMO_FileReader::__construct() */ public function POMO_FileReader( $filename ) { _deprecated_constructor( self::class, '5.4.0', static::class ); self::__construct( $filename ); } /** * @param int $bytes * @return string|false Returns read string, otherwise false. */ public function read( $bytes ) { return fread( $this->_f, $bytes ); } /** * @param int $pos * @return bool */ public function seekto( $pos ) { if ( -1 == fseek( $this->_f, $pos, SEEK_SET ) ) { return false; } $this->_pos = $pos; return true; } /** * @return bool */ public function is_resource() { return is_resource( $this->_f ); } /** * @return bool */ public function feof() { return feof( $this->_f ); } /** * @return bool */ public function close() { return fclose( $this->_f ); } /** * @return string */ public function read_all() { return stream_get_contents( $this->_f ); } } ``` | Uses | Description | | --- | --- | | [POMO\_Reader](pomo_reader) wp-includes/pomo/streams.php | | wordpress class Requests_Exception_HTTP_413 {} class Requests\_Exception\_HTTP\_413 {} ======================================= Exception for 413 Request Entity Too Large responses File: `wp-includes/Requests/Exception/HTTP/413.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/413.php/) ``` class Requests_Exception_HTTP_413 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 413; /** * Reason phrase * * @var string */ protected $reason = 'Request Entity Too Large'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_Sitemaps_Provider {} class WP\_Sitemaps\_Provider {} =============================== Class [WP\_Sitemaps\_Provider](wp_sitemaps_provider). * [get\_max\_num\_pages](wp_sitemaps_provider/get_max_num_pages) β€” Gets the max number of pages available for the object type. * [get\_object\_subtypes](wp_sitemaps_provider/get_object_subtypes) β€” Returns the list of supported object subtypes exposed by the provider. * [get\_sitemap\_entries](wp_sitemaps_provider/get_sitemap_entries) β€” Lists sitemap pages exposed by this provider. * [get\_sitemap\_type\_data](wp_sitemaps_provider/get_sitemap_type_data) β€” Gets data about each sitemap type. * [get\_sitemap\_url](wp_sitemaps_provider/get_sitemap_url) β€” Gets the URL of a sitemap entry. * [get\_url\_list](wp_sitemaps_provider/get_url_list) β€” Gets a URL list for a sitemap. File: `wp-includes/sitemaps/class-wp-sitemaps-provider.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps-provider.php/) ``` abstract class WP_Sitemaps_Provider { /** * Provider name. * * This will also be used as the public-facing name in URLs. * * @since 5.5.0 * * @var string */ protected $name = ''; /** * Object type name (e.g. 'post', 'term', 'user'). * * @since 5.5.0 * * @var string */ protected $object_type = ''; /** * Gets a URL list for a sitemap. * * @since 5.5.0 * * @param int $page_num Page of results. * @param string $object_subtype Optional. Object subtype name. Default empty. * @return array[] Array of URL information for a sitemap. */ abstract public function get_url_list( $page_num, $object_subtype = '' ); /** * Gets the max number of pages available for the object type. * * @since 5.5.0 * * @param string $object_subtype Optional. Object subtype. Default empty. * @return int Total number of pages. */ abstract public function get_max_num_pages( $object_subtype = '' ); /** * Gets data about each sitemap type. * * @since 5.5.0 * * @return array[] Array of sitemap types including object subtype name and number of pages. */ public function get_sitemap_type_data() { $sitemap_data = array(); $object_subtypes = $this->get_object_subtypes(); // If there are no object subtypes, include a single sitemap for the // entire object type. if ( empty( $object_subtypes ) ) { $sitemap_data[] = array( 'name' => '', 'pages' => $this->get_max_num_pages(), ); return $sitemap_data; } // Otherwise, include individual sitemaps for every object subtype. foreach ( $object_subtypes as $object_subtype_name => $data ) { $object_subtype_name = (string) $object_subtype_name; $sitemap_data[] = array( 'name' => $object_subtype_name, 'pages' => $this->get_max_num_pages( $object_subtype_name ), ); } return $sitemap_data; } /** * Lists sitemap pages exposed by this provider. * * The returned data is used to populate the sitemap entries of the index. * * @since 5.5.0 * * @return array[] Array of sitemap entries. */ public function get_sitemap_entries() { $sitemaps = array(); $sitemap_types = $this->get_sitemap_type_data(); foreach ( $sitemap_types as $type ) { for ( $page = 1; $page <= $type['pages']; $page ++ ) { $sitemap_entry = array( 'loc' => $this->get_sitemap_url( $type['name'], $page ), ); /** * Filters the sitemap entry for the sitemap index. * * @since 5.5.0 * * @param array $sitemap_entry Sitemap entry for the post. * @param string $object_type Object empty name. * @param string $object_subtype Object subtype name. * Empty string if the object type does not support subtypes. * @param int $page Page number of results. */ $sitemap_entry = apply_filters( 'wp_sitemaps_index_entry', $sitemap_entry, $this->object_type, $type['name'], $page ); $sitemaps[] = $sitemap_entry; } } return $sitemaps; } /** * Gets the URL of a sitemap entry. * * @since 5.5.0 * * @global WP_Rewrite $wp_rewrite WordPress rewrite component. * * @param string $name The name of the sitemap. * @param int $page The page of the sitemap. * @return string The composed URL for a sitemap entry. */ public function get_sitemap_url( $name, $page ) { global $wp_rewrite; // Accounts for cases where name is not included, ex: sitemaps-users-1.xml. $params = array_filter( array( 'sitemap' => $this->name, 'sitemap-subtype' => $name, 'paged' => $page, ) ); $basename = sprintf( '/wp-sitemap-%1$s.xml', implode( '-', $params ) ); if ( ! $wp_rewrite->using_permalinks() ) { $basename = '/?' . http_build_query( $params, '', '&' ); } return home_url( $basename ); } /** * Returns the list of supported object subtypes exposed by the provider. * * @since 5.5.0 * * @return array List of object subtypes objects keyed by their name. */ public function get_object_subtypes() { return array(); } } ``` | Used By | Description | | --- | --- | | [WP\_Sitemaps\_Users](wp_sitemaps_users) wp-includes/sitemaps/providers/class-wp-sitemaps-users.php | Users XML sitemap provider. | | [WP\_Sitemaps\_Taxonomies](wp_sitemaps_taxonomies) wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php | Taxonomies XML sitemap provider. | | [WP\_Sitemaps\_Posts](wp_sitemaps_posts) wp-includes/sitemaps/providers/class-wp-sitemaps-posts.php | Posts XML sitemap provider. | | Version | Description | | --- | --- | | [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
programming_docs
wordpress class WP_Plugins_List_Table {} class WP\_Plugins\_List\_Table {} ================================= Core class used to implement displaying installed plugins in a list table. * [WP\_List\_Table](wp_list_table) * [\_\_construct](wp_plugins_list_table/__construct) β€” Constructor. * [\_order\_callback](wp_plugins_list_table/_order_callback) * [\_search\_callback](wp_plugins_list_table/_search_callback) * [ajax\_user\_can](wp_plugins_list_table/ajax_user_can) * [bulk\_actions](wp_plugins_list_table/bulk_actions) * [current\_action](wp_plugins_list_table/current_action) * [display\_rows](wp_plugins_list_table/display_rows) * [extra\_tablenav](wp_plugins_list_table/extra_tablenav) * [get\_bulk\_actions](wp_plugins_list_table/get_bulk_actions) * [get\_columns](wp_plugins_list_table/get_columns) * [get\_primary\_column\_name](wp_plugins_list_table/get_primary_column_name) β€” Gets the name of the primary column for this specific list table. * [get\_sortable\_columns](wp_plugins_list_table/get_sortable_columns) * [get\_table\_classes](wp_plugins_list_table/get_table_classes) * [get\_views](wp_plugins_list_table/get_views) * [no\_items](wp_plugins_list_table/no_items) * [prepare\_items](wp_plugins_list_table/prepare_items) * [search\_box](wp_plugins_list_table/search_box) β€” Displays the search box. * [single\_row](wp_plugins_list_table/single_row) File: `wp-admin/includes/class-wp-plugins-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugins-list-table.php/) ``` class WP_Plugins_List_Table extends WP_List_Table { /** * Whether to show the auto-updates UI. * * @since 5.5.0 * * @var bool True if auto-updates UI is to be shown, false otherwise. */ protected $show_autoupdates = true; /** * Constructor. * * @since 3.1.0 * * @see WP_List_Table::__construct() for more information on default arguments. * * @global string $status * @global int $page * * @param array $args An associative array of arguments. */ public function __construct( $args = array() ) { global $status, $page; parent::__construct( array( 'plural' => 'plugins', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); $allowed_statuses = array( 'active', 'inactive', 'recently_activated', 'upgrade', 'mustuse', 'dropins', 'search', 'paused', 'auto-update-enabled', 'auto-update-disabled' ); $status = 'all'; if ( isset( $_REQUEST['plugin_status'] ) && in_array( $_REQUEST['plugin_status'], $allowed_statuses, true ) ) { $status = $_REQUEST['plugin_status']; } if ( isset( $_REQUEST['s'] ) ) { $_SERVER['REQUEST_URI'] = add_query_arg( 's', wp_unslash( $_REQUEST['s'] ) ); } $page = $this->get_pagenum(); $this->show_autoupdates = wp_is_auto_update_enabled_for_type( 'plugin' ) && current_user_can( 'update_plugins' ) && ( ! is_multisite() || $this->screen->in_admin( 'network' ) ) && ! in_array( $status, array( 'mustuse', 'dropins' ), true ); } /** * @return array */ protected function get_table_classes() { return array( 'widefat', $this->_args['plural'] ); } /** * @return bool */ public function ajax_user_can() { return current_user_can( 'activate_plugins' ); } /** * @global string $status * @global array $plugins * @global array $totals * @global int $page * @global string $orderby * @global string $order * @global string $s */ public function prepare_items() { global $status, $plugins, $totals, $page, $orderby, $order, $s; wp_reset_vars( array( 'orderby', 'order' ) ); /** * Filters the full array of plugins to list in the Plugins list table. * * @since 3.0.0 * * @see get_plugins() * * @param array $all_plugins An array of plugins to display in the list table. */ $all_plugins = apply_filters( 'all_plugins', get_plugins() ); $plugins = array( 'all' => $all_plugins, 'search' => array(), 'active' => array(), 'inactive' => array(), 'recently_activated' => array(), 'upgrade' => array(), 'mustuse' => array(), 'dropins' => array(), 'paused' => array(), ); if ( $this->show_autoupdates ) { $auto_updates = (array) get_site_option( 'auto_update_plugins', array() ); $plugins['auto-update-enabled'] = array(); $plugins['auto-update-disabled'] = array(); } $screen = $this->screen; if ( ! is_multisite() || ( $screen->in_admin( 'network' ) && current_user_can( 'manage_network_plugins' ) ) ) { /** * Filters whether to display the advanced plugins list table. * * There are two types of advanced plugins - must-use and drop-ins - * which can be used in a single site or Multisite network. * * The $type parameter allows you to differentiate between the type of advanced * plugins to filter the display of. Contexts include 'mustuse' and 'dropins'. * * @since 3.0.0 * * @param bool $show Whether to show the advanced plugins for the specified * plugin type. Default true. * @param string $type The plugin type. Accepts 'mustuse', 'dropins'. */ if ( apply_filters( 'show_advanced_plugins', true, 'mustuse' ) ) { $plugins['mustuse'] = get_mu_plugins(); } /** This action is documented in wp-admin/includes/class-wp-plugins-list-table.php */ if ( apply_filters( 'show_advanced_plugins', true, 'dropins' ) ) { $plugins['dropins'] = get_dropins(); } if ( current_user_can( 'update_plugins' ) ) { $current = get_site_transient( 'update_plugins' ); foreach ( (array) $plugins['all'] as $plugin_file => $plugin_data ) { if ( isset( $current->response[ $plugin_file ] ) ) { $plugins['all'][ $plugin_file ]['update'] = true; $plugins['upgrade'][ $plugin_file ] = $plugins['all'][ $plugin_file ]; } } } } if ( ! $screen->in_admin( 'network' ) ) { $show = current_user_can( 'manage_network_plugins' ); /** * Filters whether to display network-active plugins alongside plugins active for the current site. * * This also controls the display of inactive network-only plugins (plugins with * "Network: true" in the plugin header). * * Plugins cannot be network-activated or network-deactivated from this screen. * * @since 4.4.0 * * @param bool $show Whether to show network-active plugins. Default is whether the current * user can manage network plugins (ie. a Super Admin). */ $show_network_active = apply_filters( 'show_network_active_plugins', $show ); } if ( $screen->in_admin( 'network' ) ) { $recently_activated = get_site_option( 'recently_activated', array() ); } else { $recently_activated = get_option( 'recently_activated', array() ); } foreach ( $recently_activated as $key => $time ) { if ( $time + WEEK_IN_SECONDS < time() ) { unset( $recently_activated[ $key ] ); } } if ( $screen->in_admin( 'network' ) ) { update_site_option( 'recently_activated', $recently_activated ); } else { update_option( 'recently_activated', $recently_activated ); } $plugin_info = get_site_transient( 'update_plugins' ); foreach ( (array) $plugins['all'] as $plugin_file => $plugin_data ) { // Extra info if known. array_merge() ensures $plugin_data has precedence if keys collide. if ( isset( $plugin_info->response[ $plugin_file ] ) ) { $plugin_data = array_merge( (array) $plugin_info->response[ $plugin_file ], array( 'update-supported' => true ), $plugin_data ); } elseif ( isset( $plugin_info->no_update[ $plugin_file ] ) ) { $plugin_data = array_merge( (array) $plugin_info->no_update[ $plugin_file ], array( 'update-supported' => true ), $plugin_data ); } elseif ( empty( $plugin_data['update-supported'] ) ) { $plugin_data['update-supported'] = false; } /* * Create the payload that's used for the auto_update_plugin filter. * This is the same data contained within $plugin_info->(response|no_update) however * not all plugins will be contained in those keys, this avoids unexpected warnings. */ $filter_payload = array( 'id' => $plugin_file, 'slug' => '', 'plugin' => $plugin_file, 'new_version' => '', 'url' => '', 'package' => '', 'icons' => array(), 'banners' => array(), 'banners_rtl' => array(), 'tested' => '', 'requires_php' => '', 'compatibility' => new stdClass(), ); $filter_payload = (object) wp_parse_args( $plugin_data, $filter_payload ); $auto_update_forced = wp_is_auto_update_forced_for_item( 'plugin', null, $filter_payload ); if ( ! is_null( $auto_update_forced ) ) { $plugin_data['auto-update-forced'] = $auto_update_forced; } $plugins['all'][ $plugin_file ] = $plugin_data; // Make sure that $plugins['upgrade'] also receives the extra info since it is used on ?plugin_status=upgrade. if ( isset( $plugins['upgrade'][ $plugin_file ] ) ) { $plugins['upgrade'][ $plugin_file ] = $plugin_data; } // Filter into individual sections. if ( is_multisite() && ! $screen->in_admin( 'network' ) && is_network_only_plugin( $plugin_file ) && ! is_plugin_active( $plugin_file ) ) { if ( $show_network_active ) { // On the non-network screen, show inactive network-only plugins if allowed. $plugins['inactive'][ $plugin_file ] = $plugin_data; } else { // On the non-network screen, filter out network-only plugins as long as they're not individually active. unset( $plugins['all'][ $plugin_file ] ); } } elseif ( ! $screen->in_admin( 'network' ) && is_plugin_active_for_network( $plugin_file ) ) { if ( $show_network_active ) { // On the non-network screen, show network-active plugins if allowed. $plugins['active'][ $plugin_file ] = $plugin_data; } else { // On the non-network screen, filter out network-active plugins. unset( $plugins['all'][ $plugin_file ] ); } } elseif ( ( ! $screen->in_admin( 'network' ) && is_plugin_active( $plugin_file ) ) || ( $screen->in_admin( 'network' ) && is_plugin_active_for_network( $plugin_file ) ) ) { // On the non-network screen, populate the active list with plugins that are individually activated. // On the network admin screen, populate the active list with plugins that are network-activated. $plugins['active'][ $plugin_file ] = $plugin_data; if ( ! $screen->in_admin( 'network' ) && is_plugin_paused( $plugin_file ) ) { $plugins['paused'][ $plugin_file ] = $plugin_data; } } else { if ( isset( $recently_activated[ $plugin_file ] ) ) { // Populate the recently activated list with plugins that have been recently activated. $plugins['recently_activated'][ $plugin_file ] = $plugin_data; } // Populate the inactive list with plugins that aren't activated. $plugins['inactive'][ $plugin_file ] = $plugin_data; } if ( $this->show_autoupdates ) { $enabled = in_array( $plugin_file, $auto_updates, true ) && $plugin_data['update-supported']; if ( isset( $plugin_data['auto-update-forced'] ) ) { $enabled = (bool) $plugin_data['auto-update-forced']; } if ( $enabled ) { $plugins['auto-update-enabled'][ $plugin_file ] = $plugin_data; } else { $plugins['auto-update-disabled'][ $plugin_file ] = $plugin_data; } } } if ( strlen( $s ) ) { $status = 'search'; $plugins['search'] = array_filter( $plugins['all'], array( $this, '_search_callback' ) ); } $totals = array(); foreach ( $plugins as $type => $list ) { $totals[ $type ] = count( $list ); } if ( empty( $plugins[ $status ] ) && ! in_array( $status, array( 'all', 'search' ), true ) ) { $status = 'all'; } $this->items = array(); foreach ( $plugins[ $status ] as $plugin_file => $plugin_data ) { // Translate, don't apply markup, sanitize HTML. $this->items[ $plugin_file ] = _get_plugin_data_markup_translate( $plugin_file, $plugin_data, false, true ); } $total_this_page = $totals[ $status ]; $js_plugins = array(); foreach ( $plugins as $key => $list ) { $js_plugins[ $key ] = array_keys( $list ); } wp_localize_script( 'updates', '_wpUpdatesItemCounts', array( 'plugins' => $js_plugins, 'totals' => wp_get_update_data(), ) ); if ( ! $orderby ) { $orderby = 'Name'; } else { $orderby = ucfirst( $orderby ); } $order = strtoupper( $order ); uasort( $this->items, array( $this, '_order_callback' ) ); $plugins_per_page = $this->get_items_per_page( str_replace( '-', '_', $screen->id . '_per_page' ), 999 ); $start = ( $page - 1 ) * $plugins_per_page; if ( $total_this_page > $plugins_per_page ) { $this->items = array_slice( $this->items, $start, $plugins_per_page ); } $this->set_pagination_args( array( 'total_items' => $total_this_page, 'per_page' => $plugins_per_page, ) ); } /** * @global string $s URL encoded search term. * * @param array $plugin * @return bool */ public function _search_callback( $plugin ) { global $s; foreach ( $plugin as $value ) { if ( is_string( $value ) && false !== stripos( strip_tags( $value ), urldecode( $s ) ) ) { return true; } } return false; } /** * @global string $orderby * @global string $order * @param array $plugin_a * @param array $plugin_b * @return int */ public function _order_callback( $plugin_a, $plugin_b ) { global $orderby, $order; $a = $plugin_a[ $orderby ]; $b = $plugin_b[ $orderby ]; if ( $a === $b ) { return 0; } if ( 'DESC' === $order ) { return strcasecmp( $b, $a ); } else { return strcasecmp( $a, $b ); } } /** * @global array $plugins */ public function no_items() { global $plugins; if ( ! empty( $_REQUEST['s'] ) ) { $s = esc_html( wp_unslash( $_REQUEST['s'] ) ); /* translators: %s: Plugin search term. */ printf( __( 'No plugins found for: %s.' ), '<strong>' . $s . '</strong>' ); // We assume that somebody who can install plugins in multisite is experienced enough to not need this helper link. if ( ! is_multisite() && current_user_can( 'install_plugins' ) ) { echo ' <a href="' . esc_url( admin_url( 'plugin-install.php?tab=search&s=' . urlencode( $s ) ) ) . '">' . __( 'Search for plugins in the WordPress Plugin Directory.' ) . '</a>'; } } elseif ( ! empty( $plugins['all'] ) ) { _e( 'No plugins found.' ); } else { _e( 'No plugins are currently available.' ); } } /** * Displays the search box. * * @since 4.6.0 * * @param string $text The 'submit' button label. * @param string $input_id ID attribute value for the search input field. */ 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'] ) . '" />'; } ?> <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 ); ?>" class="wp-filter-search" name="s" value="<?php _admin_search_query(); ?>" placeholder="<?php esc_attr_e( 'Search installed plugins...' ); ?>" /> <?php submit_button( $text, 'hide-if-js', '', false, array( 'id' => 'search-submit' ) ); ?> </p> <?php } /** * @global string $status * @return array */ public function get_columns() { global $status; $columns = array( 'cb' => ! in_array( $status, array( 'mustuse', 'dropins' ), true ) ? '<input type="checkbox" />' : '', 'name' => __( 'Plugin' ), 'description' => __( 'Description' ), ); if ( $this->show_autoupdates ) { $columns['auto-updates'] = __( 'Automatic Updates' ); } return $columns; } /** * @return array */ protected function get_sortable_columns() { return array(); } /** * @global array $totals * @global string $status * @return array */ protected function get_views() { global $totals, $status; $status_links = array(); foreach ( $totals as $type => $count ) { if ( ! $count ) { continue; } switch ( $type ) { case 'all': /* translators: %s: Number of plugins. */ $text = _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $count, 'plugins' ); break; case 'active': /* translators: %s: Number of plugins. */ $text = _n( 'Active <span class="count">(%s)</span>', 'Active <span class="count">(%s)</span>', $count ); break; case 'recently_activated': /* translators: %s: Number of plugins. */ $text = _n( 'Recently Active <span class="count">(%s)</span>', 'Recently Active <span class="count">(%s)</span>', $count ); break; case 'inactive': /* translators: %s: Number of plugins. */ $text = _n( 'Inactive <span class="count">(%s)</span>', 'Inactive <span class="count">(%s)</span>', $count ); break; case 'mustuse': /* translators: %s: Number of plugins. */ $text = _n( 'Must-Use <span class="count">(%s)</span>', 'Must-Use <span class="count">(%s)</span>', $count ); break; case 'dropins': /* translators: %s: Number of plugins. */ $text = _n( 'Drop-in <span class="count">(%s)</span>', 'Drop-ins <span class="count">(%s)</span>', $count ); break; case 'paused': /* translators: %s: Number of plugins. */ $text = _n( 'Paused <span class="count">(%s)</span>', 'Paused <span class="count">(%s)</span>', $count ); break; case 'upgrade': /* translators: %s: Number of plugins. */ $text = _n( 'Update Available <span class="count">(%s)</span>', 'Update Available <span class="count">(%s)</span>', $count ); break; case 'auto-update-enabled': /* translators: %s: Number of plugins. */ $text = _n( 'Auto-updates Enabled <span class="count">(%s)</span>', 'Auto-updates Enabled <span class="count">(%s)</span>', $count ); break; case 'auto-update-disabled': /* translators: %s: Number of plugins. */ $text = _n( 'Auto-updates Disabled <span class="count">(%s)</span>', 'Auto-updates Disabled <span class="count">(%s)</span>', $count ); break; } if ( 'search' !== $type ) { $status_links[ $type ] = array( 'url' => add_query_arg( 'plugin_status', $type, 'plugins.php' ), 'label' => sprintf( $text, number_format_i18n( $count ) ), 'current' => $type === $status, ); } } return $this->get_views_links( $status_links ); } /** * @global string $status * @return array */ protected function get_bulk_actions() { global $status; $actions = array(); if ( 'active' !== $status ) { $actions['activate-selected'] = $this->screen->in_admin( 'network' ) ? __( 'Network Activate' ) : __( 'Activate' ); } if ( 'inactive' !== $status && 'recent' !== $status ) { $actions['deactivate-selected'] = $this->screen->in_admin( 'network' ) ? __( 'Network Deactivate' ) : __( 'Deactivate' ); } if ( ! is_multisite() || $this->screen->in_admin( 'network' ) ) { if ( current_user_can( 'update_plugins' ) ) { $actions['update-selected'] = __( 'Update' ); } if ( current_user_can( 'delete_plugins' ) && ( 'active' !== $status ) ) { $actions['delete-selected'] = __( 'Delete' ); } if ( $this->show_autoupdates ) { if ( 'auto-update-enabled' !== $status ) { $actions['enable-auto-update-selected'] = __( 'Enable Auto-updates' ); } if ( 'auto-update-disabled' !== $status ) { $actions['disable-auto-update-selected'] = __( 'Disable Auto-updates' ); } } } return $actions; } /** * @global string $status * @param string $which */ public function bulk_actions( $which = '' ) { global $status; if ( in_array( $status, array( 'mustuse', 'dropins' ), true ) ) { return; } parent::bulk_actions( $which ); } /** * @global string $status * @param string $which */ protected function extra_tablenav( $which ) { global $status; if ( ! in_array( $status, array( 'recently_activated', 'mustuse', 'dropins' ), true ) ) { return; } echo '<div class="alignleft actions">'; if ( 'recently_activated' === $status ) { submit_button( __( 'Clear List' ), '', 'clear-recent-list', false ); } elseif ( 'top' === $which && 'mustuse' === $status ) { echo '<p>' . sprintf( /* translators: %s: mu-plugins directory name. */ __( 'Files in the %s directory are executed automatically.' ), '<code>' . str_replace( ABSPATH, '/', WPMU_PLUGIN_DIR ) . '</code>' ) . '</p>'; } elseif ( 'top' === $which && 'dropins' === $status ) { echo '<p>' . sprintf( /* translators: %s: wp-content directory name. */ __( 'Drop-ins are single files, found in the %s directory, that replace or enhance WordPress features in ways that are not possible for traditional plugins.' ), '<code>' . str_replace( ABSPATH, '', WP_CONTENT_DIR ) . '</code>' ) . '</p>'; } echo '</div>'; } /** * @return string */ public function current_action() { if ( isset( $_POST['clear-recent-list'] ) ) { return 'clear-recent-list'; } return parent::current_action(); } /** * @global string $status */ public function display_rows() { global $status; if ( is_multisite() && ! $this->screen->in_admin( 'network' ) && in_array( $status, array( 'mustuse', 'dropins' ), true ) ) { return; } foreach ( $this->items as $plugin_file => $plugin_data ) { $this->single_row( array( $plugin_file, $plugin_data ) ); } } /** * @global string $status * @global int $page * @global string $s * @global array $totals * * @param array $item */ public function single_row( $item ) { global $status, $page, $s, $totals; static $plugin_id_attrs = array(); list( $plugin_file, $plugin_data ) = $item; $plugin_slug = isset( $plugin_data['slug'] ) ? $plugin_data['slug'] : sanitize_title( $plugin_data['Name'] ); $plugin_id_attr = $plugin_slug; // Ensure the ID attribute is unique. $suffix = 2; while ( in_array( $plugin_id_attr, $plugin_id_attrs, true ) ) { $plugin_id_attr = "$plugin_slug-$suffix"; $suffix++; } $plugin_id_attrs[] = $plugin_id_attr; $context = $status; $screen = $this->screen; // Pre-order. $actions = array( 'deactivate' => '', 'activate' => '', 'details' => '', 'delete' => '', ); // Do not restrict by default. $restrict_network_active = false; $restrict_network_only = false; $requires_php = isset( $plugin_data['RequiresPHP'] ) ? $plugin_data['RequiresPHP'] : null; $requires_wp = isset( $plugin_data['RequiresWP'] ) ? $plugin_data['RequiresWP'] : null; $compatible_php = is_php_version_compatible( $requires_php ); $compatible_wp = is_wp_version_compatible( $requires_wp ); if ( 'mustuse' === $context ) { $is_active = true; } elseif ( 'dropins' === $context ) { $dropins = _get_dropins(); $plugin_name = $plugin_file; if ( $plugin_file !== $plugin_data['Name'] ) { $plugin_name .= '<br />' . $plugin_data['Name']; } if ( true === ( $dropins[ $plugin_file ][1] ) ) { // Doesn't require a constant. $is_active = true; $description = '<p><strong>' . $dropins[ $plugin_file ][0] . '</strong></p>'; } elseif ( defined( $dropins[ $plugin_file ][1] ) && constant( $dropins[ $plugin_file ][1] ) ) { // Constant is true. $is_active = true; $description = '<p><strong>' . $dropins[ $plugin_file ][0] . '</strong></p>'; } else { $is_active = false; $description = '<p><strong>' . $dropins[ $plugin_file ][0] . ' <span class="error-message">' . __( 'Inactive:' ) . '</span></strong> ' . sprintf( /* translators: 1: Drop-in constant name, 2: wp-config.php */ __( 'Requires %1$s in %2$s file.' ), "<code>define('" . $dropins[ $plugin_file ][1] . "', true);</code>", '<code>wp-config.php</code>' ) . '</p>'; } if ( $plugin_data['Description'] ) { $description .= '<p>' . $plugin_data['Description'] . '</p>'; } } else { if ( $screen->in_admin( 'network' ) ) { $is_active = is_plugin_active_for_network( $plugin_file ); } else { $is_active = is_plugin_active( $plugin_file ); $restrict_network_active = ( is_multisite() && is_plugin_active_for_network( $plugin_file ) ); $restrict_network_only = ( is_multisite() && is_network_only_plugin( $plugin_file ) && ! $is_active ); } if ( $screen->in_admin( 'network' ) ) { if ( $is_active ) { if ( current_user_can( 'manage_network_plugins' ) ) { $actions['deactivate'] = sprintf( '<a href="%s" id="deactivate-%s" aria-label="%s">%s</a>', wp_nonce_url( 'plugins.php?action=deactivate&amp;plugin=' . urlencode( $plugin_file ) . '&amp;plugin_status=' . $context . '&amp;paged=' . $page . '&amp;s=' . $s, 'deactivate-plugin_' . $plugin_file ), esc_attr( $plugin_id_attr ), /* translators: %s: Plugin name. */ esc_attr( sprintf( _x( 'Network Deactivate %s', 'plugin' ), $plugin_data['Name'] ) ), __( 'Network Deactivate' ) ); } } else { if ( current_user_can( 'manage_network_plugins' ) ) { if ( $compatible_php && $compatible_wp ) { $actions['activate'] = sprintf( '<a href="%s" id="activate-%s" class="edit" aria-label="%s">%s</a>', wp_nonce_url( 'plugins.php?action=activate&amp;plugin=' . urlencode( $plugin_file ) . '&amp;plugin_status=' . $context . '&amp;paged=' . $page . '&amp;s=' . $s, 'activate-plugin_' . $plugin_file ), esc_attr( $plugin_id_attr ), /* translators: %s: Plugin name. */ esc_attr( sprintf( _x( 'Network Activate %s', 'plugin' ), $plugin_data['Name'] ) ), __( 'Network Activate' ) ); } else { $actions['activate'] = sprintf( '<span>%s</span>', _x( 'Cannot Activate', 'plugin' ) ); } } if ( current_user_can( 'delete_plugins' ) && ! is_plugin_active( $plugin_file ) ) { $actions['delete'] = sprintf( '<a href="%s" id="delete-%s" class="delete" aria-label="%s">%s</a>', wp_nonce_url( 'plugins.php?action=delete-selected&amp;checked[]=' . urlencode( $plugin_file ) . '&amp;plugin_status=' . $context . '&amp;paged=' . $page . '&amp;s=' . $s, 'bulk-plugins' ), esc_attr( $plugin_id_attr ), /* translators: %s: Plugin name. */ esc_attr( sprintf( _x( 'Delete %s', 'plugin' ), $plugin_data['Name'] ) ), __( 'Delete' ) ); } } } else { if ( $restrict_network_active ) { $actions = array( 'network_active' => __( 'Network Active' ), ); } elseif ( $restrict_network_only ) { $actions = array( 'network_only' => __( 'Network Only' ), ); } elseif ( $is_active ) { if ( current_user_can( 'deactivate_plugin', $plugin_file ) ) { $actions['deactivate'] = sprintf( '<a href="%s" id="deactivate-%s" aria-label="%s">%s</a>', wp_nonce_url( 'plugins.php?action=deactivate&amp;plugin=' . urlencode( $plugin_file ) . '&amp;plugin_status=' . $context . '&amp;paged=' . $page . '&amp;s=' . $s, 'deactivate-plugin_' . $plugin_file ), esc_attr( $plugin_id_attr ), /* translators: %s: Plugin name. */ esc_attr( sprintf( _x( 'Deactivate %s', 'plugin' ), $plugin_data['Name'] ) ), __( 'Deactivate' ) ); } if ( current_user_can( 'resume_plugin', $plugin_file ) && is_plugin_paused( $plugin_file ) ) { $actions['resume'] = sprintf( '<a href="%s" id="resume-%s" class="resume-link" aria-label="%s">%s</a>', wp_nonce_url( 'plugins.php?action=resume&amp;plugin=' . urlencode( $plugin_file ) . '&amp;plugin_status=' . $context . '&amp;paged=' . $page . '&amp;s=' . $s, 'resume-plugin_' . $plugin_file ), esc_attr( $plugin_id_attr ), /* translators: %s: Plugin name. */ esc_attr( sprintf( _x( 'Resume %s', 'plugin' ), $plugin_data['Name'] ) ), __( 'Resume' ) ); } } else { if ( current_user_can( 'activate_plugin', $plugin_file ) ) { if ( $compatible_php && $compatible_wp ) { $actions['activate'] = sprintf( '<a href="%s" id="activate-%s" class="edit" aria-label="%s">%s</a>', wp_nonce_url( 'plugins.php?action=activate&amp;plugin=' . urlencode( $plugin_file ) . '&amp;plugin_status=' . $context . '&amp;paged=' . $page . '&amp;s=' . $s, 'activate-plugin_' . $plugin_file ), esc_attr( $plugin_id_attr ), /* translators: %s: Plugin name. */ esc_attr( sprintf( _x( 'Activate %s', 'plugin' ), $plugin_data['Name'] ) ), __( 'Activate' ) ); } else { $actions['activate'] = sprintf( '<span>%s</span>', _x( 'Cannot Activate', 'plugin' ) ); } } if ( ! is_multisite() && current_user_can( 'delete_plugins' ) ) { $actions['delete'] = sprintf( '<a href="%s" id="delete-%s" class="delete" aria-label="%s">%s</a>', wp_nonce_url( 'plugins.php?action=delete-selected&amp;checked[]=' . urlencode( $plugin_file ) . '&amp;plugin_status=' . $context . '&amp;paged=' . $page . '&amp;s=' . $s, 'bulk-plugins' ), esc_attr( $plugin_id_attr ), /* translators: %s: Plugin name. */ esc_attr( sprintf( _x( 'Delete %s', 'plugin' ), $plugin_data['Name'] ) ), __( 'Delete' ) ); } } // End if $is_active. } // End if $screen->in_admin( 'network' ). } // End if $context. $actions = array_filter( $actions ); if ( $screen->in_admin( 'network' ) ) { /** * Filters the action links displayed for each plugin in the Network Admin Plugins list table. * * @since 3.1.0 * * @param string[] $actions An array of plugin action links. By default this can include * 'activate', 'deactivate', and 'delete'. * @param string $plugin_file Path to the plugin file relative to the plugins directory. * @param array $plugin_data An array of plugin data. See get_plugin_data() * and the {@see 'plugin_row_meta'} filter for the list * of possible values. * @param string $context The plugin context. By default this can include 'all', * 'active', 'inactive', 'recently_activated', 'upgrade', * 'mustuse', 'dropins', and 'search'. */ $actions = apply_filters( 'network_admin_plugin_action_links', $actions, $plugin_file, $plugin_data, $context ); /** * Filters the list of action links displayed for a specific plugin in the Network Admin Plugins list table. * * The dynamic portion of the hook name, `$plugin_file`, refers to the path * to the plugin file, relative to the plugins directory. * * @since 3.1.0 * * @param string[] $actions An array of plugin action links. By default this can include * 'activate', 'deactivate', and 'delete'. * @param string $plugin_file Path to the plugin file relative to the plugins directory. * @param array $plugin_data An array of plugin data. See get_plugin_data() * and the {@see 'plugin_row_meta'} filter for the list * of possible values. * @param string $context The plugin context. By default this can include 'all', * 'active', 'inactive', 'recently_activated', 'upgrade', * 'mustuse', 'dropins', and 'search'. */ $actions = apply_filters( "network_admin_plugin_action_links_{$plugin_file}", $actions, $plugin_file, $plugin_data, $context ); } else { /** * Filters the action links displayed for each plugin in the Plugins list table. * * @since 2.5.0 * @since 2.6.0 The `$context` parameter was added. * @since 4.9.0 The 'Edit' link was removed from the list of action links. * * @param string[] $actions An array of plugin action links. By default this can include * 'activate', 'deactivate', and 'delete'. With Multisite active * this can also include 'network_active' and 'network_only' items. * @param string $plugin_file Path to the plugin file relative to the plugins directory. * @param array $plugin_data An array of plugin data. See get_plugin_data() * and the {@see 'plugin_row_meta'} filter for the list * of possible values. * @param string $context The plugin context. By default this can include 'all', * 'active', 'inactive', 'recently_activated', 'upgrade', * 'mustuse', 'dropins', and 'search'. */ $actions = apply_filters( 'plugin_action_links', $actions, $plugin_file, $plugin_data, $context ); /** * Filters the list of action links displayed for a specific plugin in the Plugins list table. * * The dynamic portion of the hook name, `$plugin_file`, refers to the path * to the plugin file, relative to the plugins directory. * * @since 2.7.0 * @since 4.9.0 The 'Edit' link was removed from the list of action links. * * @param string[] $actions An array of plugin action links. By default this can include * 'activate', 'deactivate', and 'delete'. With Multisite active * this can also include 'network_active' and 'network_only' items. * @param string $plugin_file Path to the plugin file relative to the plugins directory. * @param array $plugin_data An array of plugin data. See get_plugin_data() * and the {@see 'plugin_row_meta'} filter for the list * of possible values. * @param string $context The plugin context. By default this can include 'all', * 'active', 'inactive', 'recently_activated', 'upgrade', * 'mustuse', 'dropins', and 'search'. */ $actions = apply_filters( "plugin_action_links_{$plugin_file}", $actions, $plugin_file, $plugin_data, $context ); } $class = $is_active ? 'active' : 'inactive'; $checkbox_id = 'checkbox_' . md5( $plugin_file ); if ( $restrict_network_active || $restrict_network_only || in_array( $status, array( 'mustuse', 'dropins' ), true ) || ! $compatible_php ) { $checkbox = ''; } else { $checkbox = sprintf( '<label class="screen-reader-text" for="%1$s">%2$s</label>' . '<input type="checkbox" name="checked[]" value="%3$s" id="%1$s" />', $checkbox_id, /* translators: %s: Plugin name. */ sprintf( __( 'Select %s' ), $plugin_data['Name'] ), esc_attr( $plugin_file ) ); } if ( 'dropins' !== $context ) { $description = '<p>' . ( $plugin_data['Description'] ? $plugin_data['Description'] : '&nbsp;' ) . '</p>'; $plugin_name = $plugin_data['Name']; } if ( ! empty( $totals['upgrade'] ) && ! empty( $plugin_data['update'] ) || ! $compatible_php || ! $compatible_wp ) { $class .= ' update'; } $paused = ! $screen->in_admin( 'network' ) && is_plugin_paused( $plugin_file ); if ( $paused ) { $class .= ' paused'; } if ( is_uninstallable_plugin( $plugin_file ) ) { $class .= ' is-uninstallable'; } printf( '<tr class="%s" data-slug="%s" data-plugin="%s">', esc_attr( $class ), esc_attr( $plugin_slug ), esc_attr( $plugin_file ) ); list( $columns, $hidden, $sortable, $primary ) = $this->get_column_info(); $auto_updates = (array) get_site_option( 'auto_update_plugins', array() ); $available_updates = get_site_transient( 'update_plugins' ); foreach ( $columns as $column_name => $column_display_name ) { $extra_classes = ''; if ( in_array( $column_name, $hidden, true ) ) { $extra_classes = ' hidden'; } switch ( $column_name ) { case 'cb': echo "<th scope='row' class='check-column'>$checkbox</th>"; break; case 'name': echo "<td class='plugin-title column-primary'><strong>$plugin_name</strong>"; echo $this->row_actions( $actions, true ); echo '</td>'; break; case 'description': $classes = 'column-description desc'; echo "<td class='$classes{$extra_classes}'> <div class='plugin-description'>$description</div> <div class='$class second plugin-version-author-uri'>"; $plugin_meta = array(); if ( ! empty( $plugin_data['Version'] ) ) { /* translators: %s: Plugin version number. */ $plugin_meta[] = sprintf( __( 'Version %s' ), $plugin_data['Version'] ); } if ( ! empty( $plugin_data['Author'] ) ) { $author = $plugin_data['Author']; if ( ! empty( $plugin_data['AuthorURI'] ) ) { $author = '<a href="' . $plugin_data['AuthorURI'] . '">' . $plugin_data['Author'] . '</a>'; } /* translators: %s: Plugin author name. */ $plugin_meta[] = sprintf( __( 'By %s' ), $author ); } // Details link using API info, if available. if ( isset( $plugin_data['slug'] ) && current_user_can( 'install_plugins' ) ) { $plugin_meta[] = sprintf( '<a href="%s" class="thickbox open-plugin-details-modal" aria-label="%s" data-title="%s">%s</a>', esc_url( network_admin_url( 'plugin-install.php?tab=plugin-information&plugin=' . $plugin_data['slug'] . '&TB_iframe=true&width=600&height=550' ) ), /* translators: %s: Plugin name. */ esc_attr( sprintf( __( 'More information about %s' ), $plugin_name ) ), esc_attr( $plugin_name ), __( 'View details' ) ); } elseif ( ! empty( $plugin_data['PluginURI'] ) ) { /* translators: %s: Plugin name. */ $aria_label = sprintf( __( 'Visit plugin site for %s' ), $plugin_name ); $plugin_meta[] = sprintf( '<a href="%s" aria-label="%s">%s</a>', esc_url( $plugin_data['PluginURI'] ), esc_attr( $aria_label ), __( 'Visit plugin site' ) ); } /** * Filters the array of row meta for each plugin in the Plugins list table. * * @since 2.8.0 * * @param string[] $plugin_meta An array of the plugin's metadata, including * the version, author, author URI, and plugin URI. * @param string $plugin_file Path to the plugin file relative to the plugins directory. * @param array $plugin_data { * An array of plugin data. * * @type string $id Plugin ID, e.g. `w.org/plugins/[plugin-name]`. * @type string $slug Plugin slug. * @type string $plugin Plugin basename. * @type string $new_version New plugin version. * @type string $url Plugin URL. * @type string $package Plugin update package URL. * @type string[] $icons An array of plugin icon URLs. * @type string[] $banners An array of plugin banner URLs. * @type string[] $banners_rtl An array of plugin RTL banner URLs. * @type string $requires The version of WordPress which the plugin requires. * @type string $tested The version of WordPress the plugin is tested against. * @type string $requires_php The version of PHP which the plugin requires. * @type string $upgrade_notice The upgrade notice for the new plugin version. * @type bool $update-supported Whether the plugin supports updates. * @type string $Name The human-readable name of the plugin. * @type string $PluginURI Plugin URI. * @type string $Version Plugin version. * @type string $Description Plugin description. * @type string $Author Plugin author. * @type string $AuthorURI Plugin author URI. * @type string $TextDomain Plugin textdomain. * @type string $DomainPath Relative path to the plugin's .mo file(s). * @type bool $Network Whether the plugin can only be activated network-wide. * @type string $RequiresWP The version of WordPress which the plugin requires. * @type string $RequiresPHP The version of PHP which the plugin requires. * @type string $UpdateURI ID of the plugin for update purposes, should be a URI. * @type string $Title The human-readable title of the plugin. * @type string $AuthorName Plugin author's name. * @type bool $update Whether there's an available update. Default null. * } * @param string $status Status filter currently applied to the plugin list. Possible * values are: 'all', 'active', 'inactive', 'recently_activated', * 'upgrade', 'mustuse', 'dropins', 'search', 'paused', * 'auto-update-enabled', 'auto-update-disabled'. */ $plugin_meta = apply_filters( 'plugin_row_meta', $plugin_meta, $plugin_file, $plugin_data, $status ); echo implode( ' | ', $plugin_meta ); echo '</div>'; if ( $paused ) { $notice_text = __( 'This plugin failed to load properly and is paused during recovery mode.' ); printf( '<p><span class="dashicons dashicons-warning"></span> <strong>%s</strong></p>', $notice_text ); $error = wp_get_plugin_error( $plugin_file ); if ( false !== $error ) { printf( '<div class="error-display"><p>%s</p></div>', wp_get_extension_error_description( $error ) ); } } echo '</td>'; break; case 'auto-updates': if ( ! $this->show_autoupdates ) { break; } echo "<td class='column-auto-updates{$extra_classes}'>"; $html = array(); if ( isset( $plugin_data['auto-update-forced'] ) ) { if ( $plugin_data['auto-update-forced'] ) { // Forced on. $text = __( 'Auto-updates enabled' ); } else { $text = __( 'Auto-updates disabled' ); } $action = 'unavailable'; $time_class = ' hidden'; } elseif ( empty( $plugin_data['update-supported'] ) ) { $text = ''; $action = 'unavailable'; $time_class = ' hidden'; } elseif ( in_array( $plugin_file, $auto_updates, true ) ) { $text = __( 'Disable auto-updates' ); $action = 'disable'; $time_class = ''; } else { $text = __( 'Enable auto-updates' ); $action = 'enable'; $time_class = ' hidden'; } $query_args = array( 'action' => "{$action}-auto-update", 'plugin' => $plugin_file, 'paged' => $page, 'plugin_status' => $status, ); $url = add_query_arg( $query_args, 'plugins.php' ); if ( 'unavailable' === $action ) { $html[] = '<span class="label">' . $text . '</span>'; } else { $html[] = sprintf( '<a href="%s" class="toggle-auto-update aria-button-if-js" data-wp-action="%s">', wp_nonce_url( $url, 'updates' ), $action ); $html[] = '<span class="dashicons dashicons-update spin hidden" aria-hidden="true"></span>'; $html[] = '<span class="label">' . $text . '</span>'; $html[] = '</a>'; } if ( ! empty( $plugin_data['update'] ) ) { $html[] = sprintf( '<div class="auto-update-time%s">%s</div>', $time_class, wp_get_auto_update_message() ); } $html = implode( '', $html ); /** * Filters the HTML of the auto-updates setting for each plugin in the Plugins list table. * * @since 5.5.0 * * @param string $html The HTML of the plugin's auto-update column content, * including toggle auto-update action links and * time to next update. * @param string $plugin_file Path to the plugin file relative to the plugins directory. * @param array $plugin_data An array of plugin data. See get_plugin_data() * and the {@see 'plugin_row_meta'} filter for the list * of possible values. */ echo apply_filters( 'plugin_auto_update_setting_html', $html, $plugin_file, $plugin_data ); echo '<div class="notice notice-error notice-alt inline hidden"><p></p></div>'; echo '</td>'; break; default: $classes = "$column_name column-$column_name $class"; echo "<td class='$classes{$extra_classes}'>"; /** * Fires inside each custom column of the Plugins list table. * * @since 3.1.0 * * @param string $column_name Name of the column. * @param string $plugin_file Path to the plugin file relative to the plugins directory. * @param array $plugin_data An array of plugin data. See get_plugin_data() * and the {@see 'plugin_row_meta'} filter for the list * of possible values. */ do_action( 'manage_plugins_custom_column', $column_name, $plugin_file, $plugin_data ); echo '</td>'; } } echo '</tr>'; if ( ! $compatible_php || ! $compatible_wp ) { printf( '<tr class="plugin-update-tr">' . '<td colspan="%s" class="plugin-update colspanchange">' . '<div class="update-message notice inline notice-error notice-alt"><p>', esc_attr( $this->get_column_count() ) ); if ( ! $compatible_php && ! $compatible_wp ) { _e( 'This plugin does not work with your versions of WordPress and PHP.' ); if ( current_user_can( 'update_core' ) && current_user_can( 'update_php' ) ) { printf( /* translators: 1: URL to WordPress Updates screen, 2: URL to Update PHP page. */ ' ' . __( '<a href="%1$s">Please update WordPress</a>, and then <a href="%2$s">learn more about updating PHP</a>.' ), self_admin_url( 'update-core.php' ), esc_url( wp_get_update_php_url() ) ); wp_update_php_annotation( '</p><p><em>', '</em>' ); } elseif ( current_user_can( 'update_core' ) ) { printf( /* translators: %s: URL to WordPress Updates screen. */ ' ' . __( '<a href="%s">Please update WordPress</a>.' ), self_admin_url( 'update-core.php' ) ); } elseif ( current_user_can( 'update_php' ) ) { printf( /* translators: %s: URL to Update PHP page. */ ' ' . __( '<a href="%s">Learn more about updating PHP</a>.' ), esc_url( wp_get_update_php_url() ) ); wp_update_php_annotation( '</p><p><em>', '</em>' ); } } elseif ( ! $compatible_wp ) { _e( 'This plugin does not work with your version of WordPress.' ); if ( current_user_can( 'update_core' ) ) { printf( /* translators: %s: URL to WordPress Updates screen. */ ' ' . __( '<a href="%s">Please update WordPress</a>.' ), self_admin_url( 'update-core.php' ) ); } } elseif ( ! $compatible_php ) { _e( 'This plugin does not work with your version of PHP.' ); if ( current_user_can( 'update_php' ) ) { printf( /* translators: %s: URL to Update PHP page. */ ' ' . __( '<a href="%s">Learn more about updating PHP</a>.' ), esc_url( wp_get_update_php_url() ) ); wp_update_php_annotation( '</p><p><em>', '</em>' ); } } echo '</p></div></td></tr>'; } /** * Fires after each row in the Plugins list table. * * @since 2.3.0 * @since 5.5.0 Added 'auto-update-enabled' and 'auto-update-disabled' * to possible values for `$status`. * * @param string $plugin_file Path to the plugin file relative to the plugins directory. * @param array $plugin_data An array of plugin data. See get_plugin_data() * and the {@see 'plugin_row_meta'} filter for the list * of possible values. * @param string $status Status filter currently applied to the plugin list. * Possible values are: 'all', 'active', 'inactive', * 'recently_activated', 'upgrade', 'mustuse', 'dropins', * 'search', 'paused', 'auto-update-enabled', 'auto-update-disabled'. */ do_action( 'after_plugin_row', $plugin_file, $plugin_data, $status ); /** * Fires after each specific row in the Plugins list table. * * The dynamic portion of the hook name, `$plugin_file`, refers to the path * to the plugin file, relative to the plugins directory. * * @since 2.7.0 * @since 5.5.0 Added 'auto-update-enabled' and 'auto-update-disabled' * to possible values for `$status`. * * @param string $plugin_file Path to the plugin file relative to the plugins directory. * @param array $plugin_data An array of plugin data. See get_plugin_data() * and the {@see 'plugin_row_meta'} filter for the list * of possible values. * @param string $status Status filter currently applied to the plugin list. * Possible values are: 'all', 'active', 'inactive', * 'recently_activated', 'upgrade', 'mustuse', 'dropins', * 'search', 'paused', 'auto-update-enabled', 'auto-update-disabled'. */ do_action( "after_plugin_row_{$plugin_file}", $plugin_file, $plugin_data, $status ); } /** * Gets the name of the primary column for this specific list table. * * @since 4.3.0 * * @return string Unalterable name for the primary column, in this case, 'name'. */ protected function get_primary_column_name() { return 'name'; } } ``` | Uses | Description | | --- | --- | | [WP\_List\_Table](wp_list_table) wp-admin/includes/class-wp-list-table.php | Base class for displaying a list of items in an ajaxified HTML table. | | Version | Description | | --- | --- | | [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
programming_docs
wordpress class Requests_Exception_HTTP_501 {} class Requests\_Exception\_HTTP\_501 {} ======================================= Exception for 501 Not Implemented responses File: `wp-includes/Requests/Exception/HTTP/501.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/501.php/) ``` class Requests_Exception_HTTP_501 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 501; /** * Reason phrase * * @var string */ protected $reason = 'Not Implemented'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_Upgrader {} class WP\_Upgrader {} ===================== * [\_\_construct](wp_upgrader/__construct) β€” Construct the upgrader with a skin. * [clear\_destination](wp_upgrader/clear_destination) β€” Clears the directory where this item is going to be installed into. * [create\_lock](wp_upgrader/create_lock) β€” Creates a lock using WordPress options. * [download\_package](wp_upgrader/download_package) β€” Download a package. * [flatten\_dirlist](wp_upgrader/flatten_dirlist) β€” Flatten the results of WP\_Filesystem\_Base::dirlist() for iterating over. * [fs\_connect](wp_upgrader/fs_connect) β€” Connect to the filesystem. * [generic\_strings](wp_upgrader/generic_strings) β€” Add the generic strings to WP\_Upgrader::$strings. * [init](wp_upgrader/init) β€” Initialize the upgrader. * [install\_package](wp_upgrader/install_package) β€” Install a package. * [maintenance\_mode](wp_upgrader/maintenance_mode) β€” Toggle maintenance mode for the site. * [release\_lock](wp_upgrader/release_lock) β€” Releases an upgrader lock. * [run](wp_upgrader/run) β€” Run an upgrade/installation. * [unpack\_package](wp_upgrader/unpack_package) β€” Unpack a compressed package file. File: `wp-admin/includes/class-wp-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader.php/) ``` class WP_Upgrader { /** * The error/notification strings used to update the user on the progress. * * @since 2.8.0 * @var array $strings */ public $strings = array(); /** * The upgrader skin being used. * * @since 2.8.0 * @var Automatic_Upgrader_Skin|WP_Upgrader_Skin $skin */ public $skin = null; /** * The result of the installation. * * This is set by WP_Upgrader::install_package(), only when the package is installed * successfully. It will then be an array, unless a WP_Error is returned by the * {@see 'upgrader_post_install'} filter. In that case, the WP_Error will be assigned to * it. * * @since 2.8.0 * * @var array|WP_Error $result { * @type string $source The full path to the source the files were installed from. * @type string $source_files List of all the files in the source directory. * @type string $destination The full path to the installation destination folder. * @type string $destination_name The name of the destination folder, or empty if `$destination` * and `$local_destination` are the same. * @type string $local_destination The full local path to the destination folder. This is usually * the same as `$destination`. * @type string $remote_destination The full remote path to the destination folder * (i.e., from `$wp_filesystem`). * @type bool $clear_destination Whether the destination folder was cleared. * } */ public $result = array(); /** * The total number of updates being performed. * * Set by the bulk update methods. * * @since 3.0.0 * @var int $update_count */ public $update_count = 0; /** * The current update if multiple updates are being performed. * * Used by the bulk update methods, and incremented for each update. * * @since 3.0.0 * @var int */ public $update_current = 0; /** * Construct the upgrader with a skin. * * @since 2.8.0 * * @param WP_Upgrader_Skin $skin The upgrader skin to use. Default is a WP_Upgrader_Skin * instance. */ public function __construct( $skin = null ) { if ( null === $skin ) { $this->skin = new WP_Upgrader_Skin(); } else { $this->skin = $skin; } } /** * 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`. * * @since 2.8.0 */ public function init() { $this->skin->set_upgrader( $this ); $this->generic_strings(); } /** * Add the generic strings to WP_Upgrader::$strings. * * @since 2.8.0 */ 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&#8230;' ); $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&#8230;' ); $this->strings['maintenance_end'] = __( 'Disabling Maintenance mode&#8230;' ); } /** * Connect to the filesystem. * * @since 2.8.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param string[] $directories Optional. Array of directories. If any of these do * not exist, a WP_Error object will be returned. * Default empty array. * @param bool $allow_relaxed_file_ownership Whether to allow relaxed file ownership. * Default false. * @return bool|WP_Error True if able to connect, false or a WP_Error otherwise. */ 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; } /** * Download a package. * * @since 2.8.0 * @since 5.2.0 Added the `$check_signatures` parameter. * @since 5.5.0 Added the `$hook_extra` parameter. * * @param string $package The URI of the package. If this is the full path to an * existing local file, it will be returned untouched. * @param bool $check_signatures Whether to validate file signatures. Default false. * @param array $hook_extra Extra arguments to pass to the filter hooks. Default empty array. * @return string|WP_Error The full path to the downloaded package file, or a WP_Error object. */ 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; } /** * Unpack a compressed package file. * * @since 2.8.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param string $package Full path to the package file. * @param bool $delete_package Optional. Whether to delete the package file after attempting * to unpack it. Default true. * @return string|WP_Error The path to the unpacked contents, or a WP_Error on failure. */ 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; } /** * Flatten the results of WP_Filesystem_Base::dirlist() for iterating over. * * @since 4.9.0 * @access protected * * @param array $nested_files Array of files as returned by WP_Filesystem_Base::dirlist(). * @param string $path Relative path to prepend to child nodes. Optional. * @return array A flattened array of the $nested_files specified. */ 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; } /** * Clears the directory where this item is going to be installed into. * * @since 4.3.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param string $remote_destination The location on the remote filesystem to be cleared. * @return true|WP_Error True upon success, WP_Error on failure. */ 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; } /** * 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. * * @since 2.8.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * @global array $wp_theme_directories * * @param array|string $args { * Optional. Array or string of arguments for installing a package. Default empty array. * * @type string $source Required path to the package source. Default empty. * @type string $destination Required path to a folder to install the package in. * Default empty. * @type bool $clear_destination Whether to delete any files already in the destination * folder. Default false. * @type bool $clear_working Whether to delete the files from the working directory * after copying them to the destination. Default false. * @type bool $abort_if_destination_exists Whether to abort the installation if * the destination folder already exists. Default true. * @type array $hook_extra Extra arguments to pass to the filter hooks called by * WP_Upgrader::install_package(). Default empty array. * } * * @return array|WP_Error The result (also stored in `WP_Upgrader::$result`), or a WP_Error on failure. */ 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; } /** * 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. * * @since 2.8.0 * * @param array $options { * Array or string of arguments for upgrading/installing a package. * * @type string $package The full path or URI of the package to install. * Default empty. * @type string $destination The full path to the destination folder. * Default empty. * @type bool $clear_destination Whether to delete any files already in the * destination folder. Default false. * @type bool $clear_working Whether to delete the files from the working * directory after copying them to the destination. * Default true. * @type bool $abort_if_destination_exists Whether to abort the installation if the destination * folder already exists. When true, `$clear_destination` * should be false. Default true. * @type bool $is_multi Whether 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. * @type array $hook_extra Extra arguments to pass to the filter hooks called by * WP_Upgrader::run(). * } * @return array|false|WP_Error The result from self::install_package() on success, otherwise a WP_Error, * or false if unable to connect to the filesystem. */ 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; } /** * Toggle maintenance mode for the site. * * Creates/deletes the maintenance file to enable/disable maintenance mode. * * @since 2.8.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param bool $enable True to enable maintenance mode, false to disable. */ 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 ); } } /** * Creates a lock using WordPress options. * * @since 4.5.0 * * @param string $lock_name The name of this unique lock. * @param int $release_timeout Optional. The duration in seconds to respect an existing lock. * Default: 1 hour. * @return bool False if a lock couldn't be created or if the lock is still valid. True otherwise. */ 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; } /** * Releases an upgrader lock. * * @since 4.5.0 * * @see WP_Upgrader::create_lock() * * @param string $lock_name The name of this unique lock. * @return bool True if the lock was successfully released. False on failure. */ public static function release_lock( $lock_name ) { return delete_option( $lock_name . '.lock' ); } } ``` | Used By | Description | | --- | --- | | [Core\_Upgrader](core_upgrader) wp-admin/includes/class-core-upgrader.php | Core class used for updating core. | | [Language\_Pack\_Upgrader](language_pack_upgrader) wp-admin/includes/class-language-pack-upgrader.php | Core class used for updating/installing language packs (translations) for plugins, themes, and core. | | [Theme\_Upgrader](theme_upgrader) wp-admin/includes/class-theme-upgrader.php | Core class used for upgrading/installing themes. | | [Plugin\_Upgrader](plugin_upgrader) wp-admin/includes/class-plugin-upgrader.php | Core class used for upgrading/installing plugins. |
programming_docs
wordpress class Requests_Exception_HTTP_405 {} class Requests\_Exception\_HTTP\_405 {} ======================================= Exception for 405 Method Not Allowed responses File: `wp-includes/Requests/Exception/HTTP/405.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/405.php/) ``` class Requests_Exception_HTTP_405 extends Requests_Exception_HTTP { /** * HTTP status code * * @var integer */ protected $code = 405; /** * Reason phrase * * @var string */ protected $reason = 'Method Not Allowed'; } ``` | Uses | Description | | --- | --- | | [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response | wordpress class WP_Block_Editor_Context {} class WP\_Block\_Editor\_Context {} =================================== Contains information about a block editor being rendered. * [\_\_construct](wp_block_editor_context/__construct) β€” Constructor. File: `wp-includes/class-wp-block-editor-context.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-editor-context.php/) ``` final class WP_Block_Editor_Context { /** * String that identifies the block editor being rendered. Can be one of: * * - `'core/edit-post'` - The post editor at `/wp-admin/edit.php`. * - `'core/edit-widgets'` - The widgets editor at `/wp-admin/widgets.php`. * - `'core/customize-widgets'` - The widgets editor at `/wp-admin/customize.php`. * - `'core/edit-site'` - The site editor at `/wp-admin/site-editor.php`. * * Defaults to 'core/edit-post'. * * @since 6.0.0 * * @var string */ public $name = 'core/edit-post'; /** * The post being edited by the block editor. Optional. * * @since 5.8.0 * * @var WP_Post|null */ public $post = null; /** * Constructor. * * Populates optional properties for a given block editor context. * * @since 5.8.0 * * @param array $settings The list of optional settings to expose in a given context. */ public function __construct( array $settings = array() ) { if ( isset( $settings['name'] ) ) { $this->name = $settings['name']; } if ( isset( $settings['post'] ) ) { $this->post = $settings['post']; } } } ``` | Version | Description | | --- | --- | | [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. | wordpress class WP_Network_Query {} class WP\_Network\_Query {} =========================== Core class used for querying networks. * [WP\_Network\_Query::\_\_construct()](wp_network_query/__construct): for accepted arguments. * [\_\_construct](wp_network_query/__construct) β€” Constructor. * [get\_network\_ids](wp_network_query/get_network_ids) β€” Used internally to get a list of network IDs matching the query vars. * [get\_networks](wp_network_query/get_networks) β€” Gets a list of networks matching the query vars. * [get\_search\_sql](wp_network_query/get_search_sql) β€” Used internally to generate an SQL string for searching across multiple columns. * [parse\_order](wp_network_query/parse_order) β€” Parses an 'order' query variable and cast it to 'ASC' or 'DESC' as necessary. * [parse\_orderby](wp_network_query/parse_orderby) β€” Parses and sanitizes 'orderby' keys passed to the network query. * [parse\_query](wp_network_query/parse_query) β€” Parses arguments passed to the network query with default query parameters. * [query](wp_network_query/query) β€” Sets up the WordPress query for retrieving networks. * [set\_found\_networks](wp_network_query/set_found_networks) β€” Populates found\_networks and max\_num\_pages properties for the current query if the limit clause was used. File: `wp-includes/class-wp-network-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-network-query.php/) ``` class WP_Network_Query { /** * SQL for database query. * * @since 4.6.0 * @var string */ public $request; /** * SQL query clauses. * * @since 4.6.0 * @var array */ protected $sql_clauses = array( 'select' => '', 'from' => '', 'where' => array(), 'groupby' => '', 'orderby' => '', 'limits' => '', ); /** * Query vars set by the user. * * @since 4.6.0 * @var array */ public $query_vars; /** * Default values for query vars. * * @since 4.6.0 * @var array */ public $query_var_defaults; /** * List of networks located by the query. * * @since 4.6.0 * @var array */ public $networks; /** * The amount of found networks for the current query. * * @since 4.6.0 * @var int */ public $found_networks = 0; /** * The number of pages. * * @since 4.6.0 * @var int */ public $max_num_pages = 0; /** * Constructor. * * Sets up the network query, based on the query vars passed. * * @since 4.6.0 * * @param string|array $query { * Optional. Array or query string of network query parameters. Default empty. * * @type int[] $network__in Array of network IDs to include. Default empty. * @type int[] $network__not_in Array of network IDs to exclude. Default empty. * @type bool $count Whether to return a network count (true) or array of network objects. * Default false. * @type string $fields Network fields to return. Accepts 'ids' (returns an array of network IDs) * or empty (returns an array of complete network objects). Default empty. * @type int $number Maximum number of networks to retrieve. Default empty (no limit). * @type int $offset Number of networks to offset the query. Used to build LIMIT clause. * Default 0. * @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query. Default true. * @type string|array $orderby Network status or array of statuses. Accepts 'id', 'domain', 'path', * 'domain_length', 'path_length' and 'network__in'. Also accepts false, * an empty array, or 'none' to disable `ORDER BY` clause. Default 'id'. * @type string $order How to order retrieved networks. Accepts 'ASC', 'DESC'. Default 'ASC'. * @type string $domain Limit results to those affiliated with a given domain. Default empty. * @type string[] $domain__in Array of domains to include affiliated networks for. Default empty. * @type string[] $domain__not_in Array of domains to exclude affiliated networks for. Default empty. * @type string $path Limit results to those affiliated with a given path. Default empty. * @type string[] $path__in Array of paths to include affiliated networks for. Default empty. * @type string[] $path__not_in Array of paths to exclude affiliated networks for. Default empty. * @type string $search Search term(s) to retrieve matching networks for. Default empty. * @type bool $update_network_cache Whether to prime the cache for found networks. Default true. * } */ public function __construct( $query = '' ) { $this->query_var_defaults = array( 'network__in' => '', 'network__not_in' => '', 'count' => false, 'fields' => '', 'number' => '', 'offset' => '', 'no_found_rows' => true, 'orderby' => 'id', 'order' => 'ASC', 'domain' => '', 'domain__in' => '', 'domain__not_in' => '', 'path' => '', 'path__in' => '', 'path__not_in' => '', 'search' => '', 'update_network_cache' => true, ); if ( ! empty( $query ) ) { $this->query( $query ); } } /** * Parses arguments passed to the network query with default query parameters. * * @since 4.6.0 * * @param string|array $query WP_Network_Query arguments. See WP_Network_Query::__construct() */ public function parse_query( $query = '' ) { if ( empty( $query ) ) { $query = $this->query_vars; } $this->query_vars = wp_parse_args( $query, $this->query_var_defaults ); /** * Fires after the network query vars have been parsed. * * @since 4.6.0 * * @param WP_Network_Query $query The WP_Network_Query instance (passed by reference). */ do_action_ref_array( 'parse_network_query', array( &$this ) ); } /** * Sets up the WordPress query for retrieving networks. * * @since 4.6.0 * * @param string|array $query Array or URL query string of parameters. * @return array|int List of WP_Network objects, a list of network IDs when 'fields' is set to 'ids', * or the number of networks when 'count' is passed as a query var. */ public function query( $query ) { $this->query_vars = wp_parse_args( $query ); return $this->get_networks(); } /** * Gets a list of networks matching the query vars. * * @since 4.6.0 * * @return array|int List of WP_Network objects, a list of network IDs when 'fields' is set to 'ids', * or the number of networks when 'count' is passed as a query var. */ public function get_networks() { $this->parse_query(); /** * Fires before networks are retrieved. * * @since 4.6.0 * * @param WP_Network_Query $query Current instance of WP_Network_Query (passed by reference). */ do_action_ref_array( 'pre_get_networks', array( &$this ) ); $network_data = null; /** * Filters the network data before the query takes place. * * Return a non-null value to bypass WordPress' default network queries. * * The expected return type from this filter depends on the value passed * in the request query vars: * - When `$this->query_vars['count']` is set, the filter should return * the network count as an integer. * - When `'ids' === $this->query_vars['fields']`, the filter should return * an array of network IDs. * - Otherwise the filter should return an array of WP_Network objects. * * Note that if the filter returns an array of network data, it will be assigned * to the `networks` property of the current WP_Network_Query instance. * * Filtering functions that require pagination information are encouraged to set * the `found_networks` and `max_num_pages` properties of the WP_Network_Query object, * passed to the filter by reference. If WP_Network_Query does not perform a database * query, it will not have enough information to generate these values itself. * * @since 5.2.0 * @since 5.6.0 The returned array of network data is assigned to the `networks` property * of the current WP_Network_Query instance. * * @param array|int|null $network_data Return an array of network data to short-circuit WP's network query, * the network count as an integer if `$this->query_vars['count']` is set, * or null to allow WP to run its normal queries. * @param WP_Network_Query $query The WP_Network_Query instance, passed by reference. */ $network_data = apply_filters_ref_array( 'networks_pre_query', array( $network_data, &$this ) ); if ( null !== $network_data ) { if ( is_array( $network_data ) && ! $this->query_vars['count'] ) { $this->networks = $network_data; } return $network_data; } // $args can include anything. Only use the args defined in the query_var_defaults to compute the key. $_args = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ); // Ignore the $fields, $update_network_cache arguments as the queried result will be the same regardless. unset( $_args['fields'], $_args['update_network_cache'] ); $key = md5( serialize( $_args ) ); $last_changed = wp_cache_get_last_changed( 'networks' ); $cache_key = "get_network_ids:$key:$last_changed"; $cache_value = wp_cache_get( $cache_key, 'networks' ); if ( false === $cache_value ) { $network_ids = $this->get_network_ids(); if ( $network_ids ) { $this->set_found_networks(); } $cache_value = array( 'network_ids' => $network_ids, 'found_networks' => $this->found_networks, ); wp_cache_add( $cache_key, $cache_value, 'networks' ); } else { $network_ids = $cache_value['network_ids']; $this->found_networks = $cache_value['found_networks']; } if ( $this->found_networks && $this->query_vars['number'] ) { $this->max_num_pages = ceil( $this->found_networks / $this->query_vars['number'] ); } // If querying for a count only, there's nothing more to do. if ( $this->query_vars['count'] ) { // $network_ids is actually a count in this case. return (int) $network_ids; } $network_ids = array_map( 'intval', $network_ids ); if ( 'ids' === $this->query_vars['fields'] ) { $this->networks = $network_ids; return $this->networks; } if ( $this->query_vars['update_network_cache'] ) { _prime_network_caches( $network_ids ); } // Fetch full network objects from the primed cache. $_networks = array(); foreach ( $network_ids as $network_id ) { $_network = get_network( $network_id ); if ( $_network ) { $_networks[] = $_network; } } /** * Filters the network query results. * * @since 4.6.0 * * @param WP_Network[] $_networks An array of WP_Network objects. * @param WP_Network_Query $query Current instance of WP_Network_Query (passed by reference). */ $_networks = apply_filters_ref_array( 'the_networks', array( $_networks, &$this ) ); // Convert to WP_Network instances. $this->networks = array_map( 'get_network', $_networks ); return $this->networks; } /** * Used internally to get a list of network IDs matching the query vars. * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @return int|array A single count of network IDs if a count query. An array of network IDs if a full query. */ protected function get_network_ids() { global $wpdb; $order = $this->parse_order( $this->query_vars['order'] ); // Disable ORDER BY with 'none', an empty array, or boolean false. if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) { $orderby = ''; } elseif ( ! empty( $this->query_vars['orderby'] ) ) { $ordersby = is_array( $this->query_vars['orderby'] ) ? $this->query_vars['orderby'] : preg_split( '/[,\s]/', $this->query_vars['orderby'] ); $orderby_array = array(); foreach ( $ordersby as $_key => $_value ) { if ( ! $_value ) { continue; } if ( is_int( $_key ) ) { $_orderby = $_value; $_order = $order; } else { $_orderby = $_key; $_order = $_value; } $parsed = $this->parse_orderby( $_orderby ); if ( ! $parsed ) { continue; } if ( 'network__in' === $_orderby ) { $orderby_array[] = $parsed; continue; } $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order ); } $orderby = implode( ', ', $orderby_array ); } else { $orderby = "$wpdb->site.id $order"; } $number = absint( $this->query_vars['number'] ); $offset = absint( $this->query_vars['offset'] ); $limits = ''; if ( ! empty( $number ) ) { if ( $offset ) { $limits = 'LIMIT ' . $offset . ',' . $number; } else { $limits = 'LIMIT ' . $number; } } if ( $this->query_vars['count'] ) { $fields = 'COUNT(*)'; } else { $fields = "$wpdb->site.id"; } // Parse network IDs for an IN clause. if ( ! empty( $this->query_vars['network__in'] ) ) { $this->sql_clauses['where']['network__in'] = "$wpdb->site.id IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['network__in'] ) ) . ' )'; } // Parse network IDs for a NOT IN clause. if ( ! empty( $this->query_vars['network__not_in'] ) ) { $this->sql_clauses['where']['network__not_in'] = "$wpdb->site.id NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['network__not_in'] ) ) . ' )'; } if ( ! empty( $this->query_vars['domain'] ) ) { $this->sql_clauses['where']['domain'] = $wpdb->prepare( "$wpdb->site.domain = %s", $this->query_vars['domain'] ); } // Parse network domain for an IN clause. if ( is_array( $this->query_vars['domain__in'] ) ) { $this->sql_clauses['where']['domain__in'] = "$wpdb->site.domain IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__in'] ) ) . "' )"; } // Parse network domain for a NOT IN clause. if ( is_array( $this->query_vars['domain__not_in'] ) ) { $this->sql_clauses['where']['domain__not_in'] = "$wpdb->site.domain NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['domain__not_in'] ) ) . "' )"; } if ( ! empty( $this->query_vars['path'] ) ) { $this->sql_clauses['where']['path'] = $wpdb->prepare( "$wpdb->site.path = %s", $this->query_vars['path'] ); } // Parse network path for an IN clause. if ( is_array( $this->query_vars['path__in'] ) ) { $this->sql_clauses['where']['path__in'] = "$wpdb->site.path IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__in'] ) ) . "' )"; } // Parse network path for a NOT IN clause. if ( is_array( $this->query_vars['path__not_in'] ) ) { $this->sql_clauses['where']['path__not_in'] = "$wpdb->site.path NOT IN ( '" . implode( "', '", $wpdb->_escape( $this->query_vars['path__not_in'] ) ) . "' )"; } // Falsey search strings are ignored. if ( strlen( $this->query_vars['search'] ) ) { $this->sql_clauses['where']['search'] = $this->get_search_sql( $this->query_vars['search'], array( "$wpdb->site.domain", "$wpdb->site.path" ) ); } $join = ''; $where = implode( ' AND ', $this->sql_clauses['where'] ); $groupby = ''; $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' ); /** * Filters the network query clauses. * * @since 4.6.0 * * @param string[] $clauses An associative array of network query clauses. * @param WP_Network_Query $query Current instance of WP_Network_Query (passed by reference). */ $clauses = apply_filters_ref_array( 'networks_clauses', array( compact( $pieces ), &$this ) ); $fields = isset( $clauses['fields'] ) ? $clauses['fields'] : ''; $join = isset( $clauses['join'] ) ? $clauses['join'] : ''; $where = isset( $clauses['where'] ) ? $clauses['where'] : ''; $orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : ''; $limits = isset( $clauses['limits'] ) ? $clauses['limits'] : ''; $groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : ''; if ( $where ) { $where = 'WHERE ' . $where; } if ( $groupby ) { $groupby = 'GROUP BY ' . $groupby; } if ( $orderby ) { $orderby = "ORDER BY $orderby"; } $found_rows = ''; if ( ! $this->query_vars['no_found_rows'] ) { $found_rows = 'SQL_CALC_FOUND_ROWS'; } $this->sql_clauses['select'] = "SELECT $found_rows $fields"; $this->sql_clauses['from'] = "FROM $wpdb->site $join"; $this->sql_clauses['groupby'] = $groupby; $this->sql_clauses['orderby'] = $orderby; $this->sql_clauses['limits'] = $limits; $this->request = " {$this->sql_clauses['select']} {$this->sql_clauses['from']} {$where} {$this->sql_clauses['groupby']} {$this->sql_clauses['orderby']} {$this->sql_clauses['limits']} "; if ( $this->query_vars['count'] ) { return (int) $wpdb->get_var( $this->request ); } $network_ids = $wpdb->get_col( $this->request ); return array_map( 'intval', $network_ids ); } /** * Populates found_networks and max_num_pages properties for the current query * if the limit clause was used. * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. */ private function set_found_networks() { global $wpdb; if ( $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) { /** * Filters the query used to retrieve found network count. * * @since 4.6.0 * * @param string $found_networks_query SQL query. Default 'SELECT FOUND_ROWS()'. * @param WP_Network_Query $network_query The `WP_Network_Query` instance. */ $found_networks_query = apply_filters( 'found_networks_query', 'SELECT FOUND_ROWS()', $this ); $this->found_networks = (int) $wpdb->get_var( $found_networks_query ); } } /** * Used internally to generate an SQL string for searching across multiple columns. * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $search Search string. * @param string[] $columns Array of columns to search. * @return string Search SQL. */ protected function get_search_sql( $search, $columns ) { global $wpdb; $like = '%' . $wpdb->esc_like( $search ) . '%'; $searches = array(); foreach ( $columns as $column ) { $searches[] = $wpdb->prepare( "$column LIKE %s", $like ); } return '(' . implode( ' OR ', $searches ) . ')'; } /** * Parses and sanitizes 'orderby' keys passed to the network query. * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $orderby Alias for the field to order by. * @return string|false Value to used in the ORDER clause. False otherwise. */ protected function parse_orderby( $orderby ) { global $wpdb; $allowed_keys = array( 'id', 'domain', 'path', ); $parsed = false; if ( 'network__in' === $orderby ) { $network__in = implode( ',', array_map( 'absint', $this->query_vars['network__in'] ) ); $parsed = "FIELD( {$wpdb->site}.id, $network__in )"; } elseif ( 'domain_length' === $orderby || 'path_length' === $orderby ) { $field = substr( $orderby, 0, -7 ); $parsed = "CHAR_LENGTH($wpdb->site.$field)"; } elseif ( in_array( $orderby, $allowed_keys, true ) ) { $parsed = "$wpdb->site.$orderby"; } return $parsed; } /** * Parses an 'order' query variable and cast it to 'ASC' or 'DESC' as necessary. * * @since 4.6.0 * * @param string $order The 'order' query variable. * @return string The sanitized 'order' query variable. */ protected function parse_order( $order ) { if ( ! is_string( $order ) || empty( $order ) ) { return 'ASC'; } if ( 'ASC' === strtoupper( $order ) ) { return 'ASC'; } else { return 'DESC'; } } } ``` | Version | Description | | --- | --- | | [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
programming_docs
wordpress class MagpieRSS {} class MagpieRSS {} ================== * [\_\_construct](magpierss/__construct) β€” PHP5 constructor. * [append](magpierss/append) * [append\_content](magpierss/append_content) * [concat](magpierss/concat) * [error](magpierss/error) * [feed\_cdata](magpierss/feed_cdata) * [feed\_end\_element](magpierss/feed_end_element) * [feed\_start\_element](magpierss/feed_start_element) * [is\_atom](magpierss/is_atom) * [is\_rss](magpierss/is_rss) * [MagpieRSS](magpierss/magpierss) β€” PHP4 constructor. * [map\_attrs](magpierss/map_attrs) * [normalize](magpierss/normalize) File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/) ``` class MagpieRSS { var $parser; var $current_item = array(); // item currently being parsed var $items = array(); // collection of parsed items var $channel = array(); // hash of channel fields var $textinput = array(); var $image = array(); var $feed_type; var $feed_version; // parser variables var $stack = array(); // parser stack var $inchannel = false; var $initem = false; var $incontent = false; // if in Atom <content mode="xml"> field var $intextinput = false; var $inimage = false; var $current_field = ''; var $current_namespace = false; //var $ERROR = ""; var $_CONTENT_CONSTRUCTS = array('content', 'summary', 'info', 'title', 'tagline', 'copyright'); /** * PHP5 constructor. */ function __construct( $source ) { # Check if PHP xml isn't compiled # if ( ! function_exists('xml_parser_create') ) { return trigger_error( "PHP's XML extension is not available. Please contact your hosting provider to enable PHP's XML extension." ); } $parser = xml_parser_create(); $this->parser = $parser; # pass in parser, and a reference to this object # set up handlers # xml_set_object( $this->parser, $this ); xml_set_element_handler($this->parser, 'feed_start_element', 'feed_end_element' ); xml_set_character_data_handler( $this->parser, 'feed_cdata' ); $status = xml_parse( $this->parser, $source ); if (! $status ) { $errorcode = xml_get_error_code( $this->parser ); if ( $errorcode != XML_ERROR_NONE ) { $xml_error = xml_error_string( $errorcode ); $error_line = xml_get_current_line_number($this->parser); $error_col = xml_get_current_column_number($this->parser); $errormsg = "$xml_error at line $error_line, column $error_col"; $this->error( $errormsg ); } } xml_parser_free( $this->parser ); unset( $this->parser ); $this->normalize(); } /** * PHP4 constructor. */ public function MagpieRSS( $source ) { self::__construct( $source ); } function feed_start_element($p, $element, &$attrs) { $el = $element = strtolower($element); $attrs = array_change_key_case($attrs, CASE_LOWER); // check for a namespace, and split if found $ns = false; if ( strpos( $element, ':' ) ) { list($ns, $el) = explode( ':', $element, 2); } if ( $ns and $ns != 'rdf' ) { $this->current_namespace = $ns; } # if feed type isn't set, then this is first element of feed # identify feed from root element # if (!isset($this->feed_type) ) { if ( $el == 'rdf' ) { $this->feed_type = RSS; $this->feed_version = '1.0'; } elseif ( $el == 'rss' ) { $this->feed_type = RSS; $this->feed_version = $attrs['version']; } elseif ( $el == 'feed' ) { $this->feed_type = ATOM; $this->feed_version = $attrs['version']; $this->inchannel = true; } return; } if ( $el == 'channel' ) { $this->inchannel = true; } elseif ($el == 'item' or $el == 'entry' ) { $this->initem = true; if ( isset($attrs['rdf:about']) ) { $this->current_item['about'] = $attrs['rdf:about']; } } // if we're in the default namespace of an RSS feed, // record textinput or image fields elseif ( $this->feed_type == RSS and $this->current_namespace == '' and $el == 'textinput' ) { $this->intextinput = true; } elseif ( $this->feed_type == RSS and $this->current_namespace == '' and $el == 'image' ) { $this->inimage = true; } # handle atom content constructs elseif ( $this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) ) { // avoid clashing w/ RSS mod_content if ($el == 'content' ) { $el = 'atom_content'; } $this->incontent = $el; } // if inside an Atom content construct (e.g. content or summary) field treat tags as text elseif ($this->feed_type == ATOM and $this->incontent ) { // if tags are inlined, then flatten $attrs_str = join(' ', array_map(array('MagpieRSS', 'map_attrs'), array_keys($attrs), array_values($attrs) ) ); $this->append_content( "<$element $attrs_str>" ); array_unshift( $this->stack, $el ); } // Atom support many links per containging element. // Magpie treats link elements of type rel='alternate' // as being equivalent to RSS's simple link element. // elseif ($this->feed_type == ATOM and $el == 'link' ) { if ( isset($attrs['rel']) and $attrs['rel'] == 'alternate' ) { $link_el = 'link'; } else { $link_el = 'link_' . $attrs['rel']; } $this->append($link_el, $attrs['href']); } // set stack[0] to current element else { array_unshift($this->stack, $el); } } function feed_cdata ($p, $text) { if ($this->feed_type == ATOM and $this->incontent) { $this->append_content( $text ); } else { $current_el = join('_', array_reverse($this->stack)); $this->append($current_el, $text); } } function feed_end_element ($p, $el) { $el = strtolower($el); if ( $el == 'item' or $el == 'entry' ) { $this->items[] = $this->current_item; $this->current_item = array(); $this->initem = false; } elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'textinput' ) { $this->intextinput = false; } elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'image' ) { $this->inimage = false; } elseif ($this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) ) { $this->incontent = false; } elseif ($el == 'channel' or $el == 'feed' ) { $this->inchannel = false; } elseif ($this->feed_type == ATOM and $this->incontent ) { // balance tags properly // note: This may not actually be necessary if ( $this->stack[0] == $el ) { $this->append_content("</$el>"); } else { $this->append_content("<$el />"); } array_shift( $this->stack ); } else { array_shift( $this->stack ); } $this->current_namespace = false; } function concat (&$str1, $str2="") { if (!isset($str1) ) { $str1=""; } $str1 .= $str2; } function append_content($text) { if ( $this->initem ) { $this->concat( $this->current_item[ $this->incontent ], $text ); } elseif ( $this->inchannel ) { $this->concat( $this->channel[ $this->incontent ], $text ); } } // smart append - field and namespace aware function append($el, $text) { if (!$el) { return; } if ( $this->current_namespace ) { if ( $this->initem ) { $this->concat( $this->current_item[ $this->current_namespace ][ $el ], $text); } elseif ($this->inchannel) { $this->concat( $this->channel[ $this->current_namespace][ $el ], $text ); } elseif ($this->intextinput) { $this->concat( $this->textinput[ $this->current_namespace][ $el ], $text ); } elseif ($this->inimage) { $this->concat( $this->image[ $this->current_namespace ][ $el ], $text ); } } else { if ( $this->initem ) { $this->concat( $this->current_item[ $el ], $text); } elseif ($this->intextinput) { $this->concat( $this->textinput[ $el ], $text ); } elseif ($this->inimage) { $this->concat( $this->image[ $el ], $text ); } elseif ($this->inchannel) { $this->concat( $this->channel[ $el ], $text ); } } } function normalize () { // if atom populate rss fields if ( $this->is_atom() ) { $this->channel['descripton'] = $this->channel['tagline']; for ( $i = 0; $i < count($this->items); $i++) { $item = $this->items[$i]; if ( isset($item['summary']) ) $item['description'] = $item['summary']; if ( isset($item['atom_content'])) $item['content']['encoded'] = $item['atom_content']; $this->items[$i] = $item; } } elseif ( $this->is_rss() ) { $this->channel['tagline'] = $this->channel['description']; for ( $i = 0; $i < count($this->items); $i++) { $item = $this->items[$i]; if ( isset($item['description'])) $item['summary'] = $item['description']; if ( isset($item['content']['encoded'] ) ) $item['atom_content'] = $item['content']['encoded']; $this->items[$i] = $item; } } } function is_rss () { if ( $this->feed_type == RSS ) { return $this->feed_version; } else { return false; } } function is_atom() { if ( $this->feed_type == ATOM ) { return $this->feed_version; } else { return false; } } function map_attrs($k, $v) { return "$k=\"$v\""; } function error( $errormsg, $lvl = E_USER_WARNING ) { if ( MAGPIE_DEBUG ) { trigger_error( $errormsg, $lvl); } else { error_log( $errormsg, 0); } } } ``` wordpress class WP_Widget_Media_Gallery {} class WP\_Widget\_Media\_Gallery {} =================================== Core class that implements a gallery widget. * [WP\_Widget\_Media](wp_widget_media) * [WP\_Widget](wp_widget) * [\_\_construct](wp_widget_media_gallery/__construct) β€” Constructor. * [enqueue\_admin\_scripts](wp_widget_media_gallery/enqueue_admin_scripts) β€” Loads the required media files for the media manager and scripts for media widgets. * [get\_instance\_schema](wp_widget_media_gallery/get_instance_schema) β€” Get schema for properties of a widget instance (item). * [has\_content](wp_widget_media_gallery/has_content) β€” Whether the widget has content to show. * [render\_control\_template\_scripts](wp_widget_media_gallery/render_control_template_scripts) β€” Render form template scripts. * [render\_media](wp_widget_media_gallery/render_media) β€” Render the media on the frontend. File: `wp-includes/widgets/class-wp-widget-media-gallery.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-media-gallery.php/) ``` class WP_Widget_Media_Gallery extends WP_Widget_Media { /** * Constructor. * * @since 4.9.0 */ public function __construct() { parent::__construct( 'media_gallery', __( 'Gallery' ), array( 'description' => __( 'Displays an image gallery.' ), 'mime_type' => 'image', ) ); $this->l10n = array_merge( $this->l10n, array( 'no_media_selected' => __( 'No images selected' ), 'add_media' => _x( 'Add Images', 'label for button in the gallery widget; should not be longer than ~13 characters long' ), 'replace_media' => '', 'edit_media' => _x( 'Edit Gallery', 'label for button in the gallery widget; should not be longer than ~13 characters long' ), ) ); } /** * Get schema for properties of a widget instance (item). * * @since 4.9.0 * * @see WP_REST_Controller::get_item_schema() * @see WP_REST_Controller::get_additional_fields() * @link https://core.trac.wordpress.org/ticket/35574 * * @return array Schema for properties. */ public function get_instance_schema() { $schema = array( 'title' => array( 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', 'description' => __( 'Title for the widget' ), 'should_preview_update' => false, ), 'ids' => array( 'type' => 'array', 'items' => array( 'type' => 'integer', ), 'default' => array(), 'sanitize_callback' => 'wp_parse_id_list', ), 'columns' => array( 'type' => 'integer', 'default' => 3, 'minimum' => 1, 'maximum' => 9, ), 'size' => array( 'type' => 'string', 'enum' => array_merge( get_intermediate_image_sizes(), array( 'full', 'custom' ) ), 'default' => 'thumbnail', ), 'link_type' => array( 'type' => 'string', 'enum' => array( 'post', 'file', 'none' ), 'default' => 'post', 'media_prop' => 'link', 'should_preview_update' => false, ), 'orderby_random' => array( 'type' => 'boolean', 'default' => false, 'media_prop' => '_orderbyRandom', 'should_preview_update' => false, ), ); /** This filter is documented in wp-includes/widgets/class-wp-widget-media.php */ $schema = apply_filters( "widget_{$this->id_base}_instance_schema", $schema, $this ); return $schema; } /** * Render the media on the frontend. * * @since 4.9.0 * * @param array $instance Widget instance props. */ public function render_media( $instance ) { $instance = array_merge( wp_list_pluck( $this->get_instance_schema(), 'default' ), $instance ); $shortcode_atts = array_merge( $instance, array( 'link' => $instance['link_type'], ) ); // @codeCoverageIgnoreStart if ( $instance['orderby_random'] ) { $shortcode_atts['orderby'] = 'rand'; } // @codeCoverageIgnoreEnd echo gallery_shortcode( $shortcode_atts ); } /** * Loads the required media files for the media manager and scripts for media widgets. * * @since 4.9.0 */ public function enqueue_admin_scripts() { parent::enqueue_admin_scripts(); $handle = 'media-gallery-widget'; wp_enqueue_script( $handle ); $exported_schema = array(); foreach ( $this->get_instance_schema() as $field => $field_schema ) { $exported_schema[ $field ] = wp_array_slice_assoc( $field_schema, array( 'type', 'default', 'enum', 'minimum', 'format', 'media_prop', 'should_preview_update', 'items' ) ); } wp_add_inline_script( $handle, sprintf( 'wp.mediaWidgets.modelConstructors[ %s ].prototype.schema = %s;', wp_json_encode( $this->id_base ), wp_json_encode( $exported_schema ) ) ); wp_add_inline_script( $handle, sprintf( ' wp.mediaWidgets.controlConstructors[ %1$s ].prototype.mime_type = %2$s; _.extend( wp.mediaWidgets.controlConstructors[ %1$s ].prototype.l10n, %3$s ); ', wp_json_encode( $this->id_base ), wp_json_encode( $this->widget_options['mime_type'] ), wp_json_encode( $this->l10n ) ) ); } /** * Render form template scripts. * * @since 4.9.0 */ public function render_control_template_scripts() { parent::render_control_template_scripts(); ?> <script type="text/html" id="tmpl-wp-media-widget-gallery-preview"> <# var ids = _.filter( data.ids, function( id ) { return ( id in data.attachments ); } ); #> <# if ( ids.length ) { #> <ul class="gallery media-widget-gallery-preview" role="list"> <# _.each( ids, function( id, index ) { #> <# var attachment = data.attachments[ id ]; #> <# if ( index < 6 ) { #> <li class="gallery-item"> <div class="gallery-icon"> <img alt="{{ attachment.alt }}" <# if ( index === 5 && data.ids.length > 6 ) { #> aria-hidden="true" <# } #> <# if ( attachment.sizes.thumbnail ) { #> src="{{ attachment.sizes.thumbnail.url }}" width="{{ attachment.sizes.thumbnail.width }}" height="{{ attachment.sizes.thumbnail.height }}" <# } else { #> src="{{ attachment.url }}" <# } #> <# if ( ! attachment.alt && attachment.filename ) { #> aria-label=" <?php echo esc_attr( sprintf( /* translators: %s: The image file name. */ __( 'The current image has no alternative text. The file name is: %s' ), '{{ attachment.filename }}' ) ); ?> " <# } #> /> <# if ( index === 5 && data.ids.length > 6 ) { #> <div class="gallery-icon-placeholder"> <p class="gallery-icon-placeholder-text" aria-label=" <?php printf( /* translators: %s: The amount of additional, not visible images in the gallery widget preview. */ __( 'Additional images added to this gallery: %s' ), '{{ data.ids.length - 5 }}' ); ?> ">+{{ data.ids.length - 5 }}</p> </div> <# } #> </div> </li> <# } #> <# } ); #> </ul> <# } else { #> <div class="attachment-media-view"> <button type="button" class="placeholder button-add-media"><?php echo esc_html( $this->l10n['add_media'] ); ?></button> </div> <# } #> </script> <?php } /** * Whether the widget has content to show. * * @since 4.9.0 * @access protected * * @param array $instance Widget instance props. * @return bool Whether widget has content. */ protected function has_content( $instance ) { if ( ! empty( $instance['ids'] ) ) { $attachments = wp_parse_id_list( $instance['ids'] ); foreach ( $attachments as $attachment ) { if ( 'attachment' !== get_post_type( $attachment ) ) { return false; } } return true; } return false; } } ``` | Uses | Description | | --- | --- | | [WP\_Widget\_Media](wp_widget_media) wp-includes/widgets/class-wp-widget-media.php | Core class that implements a media widget. | | Version | Description | | --- | --- | | [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. | wordpress class WP_MatchesMapRegex {} class WP\_MatchesMapRegex {} ============================ Helper class to remove the need to use eval to replace $matches[] in query strings. * [\_\_construct](wp_matchesmapregex/__construct) β€” constructor * [\_map](wp_matchesmapregex/_map) β€” do the actual mapping * [apply](wp_matchesmapregex/apply) β€” Substitute substring matches in subject. * [callback](wp_matchesmapregex/callback) β€” preg\_replace\_callback hook File: `wp-includes/class-wp-matchesmapregex.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-matchesmapregex.php/) ``` class WP_MatchesMapRegex { /** * store for matches * * @var array */ private $_matches; /** * store for mapping result * * @var string */ public $output; /** * subject to perform mapping on (query string containing $matches[] references * * @var string */ private $_subject; /** * regexp pattern to match $matches[] references * * @var string */ public $_pattern = '(\$matches\[[1-9]+[0-9]*\])'; // Magic number. /** * constructor * * @param string $subject subject if regex * @param array $matches data to use in map */ public function __construct( $subject, $matches ) { $this->_subject = $subject; $this->_matches = $matches; $this->output = $this->_map(); } /** * Substitute substring matches in subject. * * static helper function to ease use * * @param string $subject subject * @param array $matches data used for substitution * @return string */ public static function apply( $subject, $matches ) { $oSelf = new WP_MatchesMapRegex( $subject, $matches ); return $oSelf->output; } /** * do the actual mapping * * @return string */ private function _map() { $callback = array( $this, 'callback' ); return preg_replace_callback( $this->_pattern, $callback, $this->_subject ); } /** * preg_replace_callback hook * * @param array $matches preg_replace regexp matches * @return string */ public function callback( $matches ) { $index = (int) substr( $matches[0], 9, -1 ); return ( isset( $this->_matches[ $index ] ) ? urlencode( $this->_matches[ $index ] ) : '' ); } } ``` | Version | Description | | --- | --- | | [2.9.0](https://developer.wordpress.org/reference/since/2.9.0/) | Introduced. |
programming_docs
wordpress class WP_REST_URL_Details_Controller {} class WP\_REST\_URL\_Details\_Controller {} =========================================== Controller which provides REST endpoint for retrieving information from a remote site’s HTML response. * [WP\_REST\_Controller](wp_rest_controller) * [\_\_construct](wp_rest_url_details_controller/__construct) β€” Constructs the controller. * [build\_cache\_key\_for\_url](wp_rest_url_details_controller/build_cache_key_for_url) β€” Utility function to build cache key for a given URL. * [get\_cache](wp_rest_url_details_controller/get_cache) β€” Utility function to retrieve a value from the cache at a given key. * [get\_description](wp_rest_url_details_controller/get_description) β€” Parses the meta description from the provided HTML. * [get\_document\_head](wp_rest_url_details_controller/get_document_head) β€” Retrieves the head element section. * [get\_icon](wp_rest_url_details_controller/get_icon) β€” Parses the site icon from the provided HTML. * [get\_image](wp_rest_url_details_controller/get_image) β€” Parses the Open Graph (OG) Image from the provided HTML. * [get\_item\_schema](wp_rest_url_details_controller/get_item_schema) β€” Retrieves the item's schema, conforming to JSON Schema. * [get\_meta\_with\_content\_elements](wp_rest_url_details_controller/get_meta_with_content_elements) β€” Gets all the meta tag elements that have a 'content' attribute. * [get\_metadata\_from\_meta\_element](wp_rest_url_details_controller/get_metadata_from_meta_element) β€” Gets the metadata from a target meta element. * [get\_remote\_url](wp_rest_url_details_controller/get_remote_url) β€” Retrieves the document title from a remote URL. * [get\_title](wp_rest_url_details_controller/get_title) β€” Parses the title tag contents from the provided HTML. * [parse\_url\_details](wp_rest_url_details_controller/parse_url_details) β€” Retrieves the contents of the title tag from the HTML response. * [permissions\_check](wp_rest_url_details_controller/permissions_check) β€” Checks whether a given request has permission to read remote URLs. * [prepare\_metadata\_for\_output](wp_rest_url_details_controller/prepare_metadata_for_output) β€” Prepares the metadata by: - stripping all HTML tags and tag entities. * [register\_routes](wp_rest_url_details_controller/register_routes) β€” Registers the necessary REST API routes. * [set\_cache](wp_rest_url_details_controller/set_cache) β€” Utility function to cache a given data set at a given cache key. File: `wp-includes/rest-api/endpoints/class-wp-rest-url-details-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-url-details-controller.php/) ``` class WP_REST_URL_Details_Controller extends WP_REST_Controller { /** * Constructs the controller. * * @since 5.9.0 */ public function __construct() { $this->namespace = 'wp-block-editor/v1'; $this->rest_base = 'url-details'; } /** * Registers the necessary REST API routes. * * @since 5.9.0 */ public function register_routes() { register_rest_route( $this->namespace, '/' . $this->rest_base, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'parse_url_details' ), 'args' => array( 'url' => array( 'required' => true, 'description' => __( 'The URL to process.' ), 'validate_callback' => 'wp_http_validate_url', 'sanitize_callback' => 'sanitize_url', 'type' => 'string', 'format' => 'uri', ), ), 'permission_callback' => array( $this, 'permissions_check' ), 'schema' => array( $this, 'get_public_item_schema' ), ), ) ); } /** * Retrieves the item's schema, conforming to JSON Schema. * * @since 5.9.0 * * @return array Item schema data. */ 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' => 'url-details', 'type' => 'object', 'properties' => array( 'title' => array( 'description' => sprintf( /* translators: %s: HTML title tag. */ __( 'The contents of the %s element from the URL.' ), '<title>' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'icon' => array( 'description' => sprintf( /* translators: %s: HTML link tag. */ __( 'The favicon image link of the %s element from the URL.' ), '<link rel="icon">' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'description' => array( 'description' => sprintf( /* translators: %s: HTML meta tag. */ __( 'The content of the %s element from the URL.' ), '<meta name="description">' ), 'type' => 'string', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), 'image' => array( 'description' => sprintf( /* translators: 1: HTML meta tag, 2: HTML meta tag. */ __( 'The Open Graph image link of the %1$s or %2$s element from the URL.' ), '<meta property="og:image">', '<meta property="og:image:url">' ), 'type' => 'string', 'format' => 'uri', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true, ), ), ); return $this->add_additional_fields_schema( $this->schema ); } /** * Retrieves the contents of the title tag from the HTML response. * * @since 5.9.0 * * @param WP_REST_REQUEST $request Full details about the request. * @return WP_REST_Response|WP_Error The parsed details as a response object. WP_Error if there are errors. */ public function parse_url_details( $request ) { $url = untrailingslashit( $request['url'] ); if ( empty( $url ) ) { return new WP_Error( 'rest_invalid_url', __( 'Invalid URL' ), array( 'status' => 404 ) ); } // Transient per URL. $cache_key = $this->build_cache_key_for_url( $url ); // Attempt to retrieve cached response. $cached_response = $this->get_cache( $cache_key ); if ( ! empty( $cached_response ) ) { $remote_url_response = $cached_response; } else { $remote_url_response = $this->get_remote_url( $url ); // Exit if we don't have a valid body or it's empty. if ( is_wp_error( $remote_url_response ) || empty( $remote_url_response ) ) { return $remote_url_response; } // Cache the valid response. $this->set_cache( $cache_key, $remote_url_response ); } $html_head = $this->get_document_head( $remote_url_response ); $meta_elements = $this->get_meta_with_content_elements( $html_head ); $data = $this->add_additional_fields_to_object( array( 'title' => $this->get_title( $html_head ), 'icon' => $this->get_icon( $html_head, $url ), 'description' => $this->get_description( $meta_elements ), 'image' => $this->get_image( $meta_elements, $url ), ), $request ); // Wrap the data in a response object. $response = rest_ensure_response( $data ); /** * Filters the URL data for the response. * * @since 5.9.0 * * @param WP_REST_Response $response The response object. * @param string $url The requested URL. * @param WP_REST_Request $request Request object. * @param string $remote_url_response HTTP response body from the remote URL. */ return apply_filters( 'rest_prepare_url_details', $response, $url, $request, $remote_url_response ); } /** * Checks whether a given request has permission to read remote URLs. * * @since 5.9.0 * * @return WP_Error|bool True if the request has permission, else WP_Error. */ public function permissions_check() { 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_url_details', __( 'Sorry, you are not allowed to process remote URLs.' ), array( 'status' => rest_authorization_required_code() ) ); } /** * Retrieves the document title from a remote URL. * * @since 5.9.0 * * @param string $url The website URL whose HTML to access. * @return string|WP_Error The HTTP response from the remote URL on success. * WP_Error if no response or no content. */ private function get_remote_url( $url ) { /* * Provide a modified UA string to workaround web properties which block WordPress "Pingbacks". * Why? The UA string used for pingback requests contains `WordPress/` which is very similar * to that used as the default UA string by the WP HTTP API. Therefore requests from this * REST endpoint are being unintentionally blocked as they are misidentified as pingback requests. * By slightly modifying the UA string, but still retaining the "WordPress" identification (via "WP") * we are able to work around this issue. * Example UA string: `WP-URLDetails/5.9-alpha-51389 (+http://localhost:8888)`. */ $modified_user_agent = 'WP-URLDetails/' . get_bloginfo( 'version' ) . ' (+' . get_bloginfo( 'url' ) . ')'; $args = array( 'limit_response_size' => 150 * KB_IN_BYTES, 'user-agent' => $modified_user_agent, ); /** * Filters the HTTP request args for URL data retrieval. * * Can be used to adjust response size limit and other WP_Http::request() args. * * @since 5.9.0 * * @param array $args Arguments used for the HTTP request. * @param string $url The attempted URL. */ $args = apply_filters( 'rest_url_details_http_request_args', $args, $url ); $response = wp_safe_remote_get( $url, $args ); if ( WP_Http::OK !== wp_remote_retrieve_response_code( $response ) ) { // Not saving the error response to cache since the error might be temporary. return new WP_Error( 'no_response', __( 'URL not found. Response returned a non-200 status code for this URL.' ), array( 'status' => WP_Http::NOT_FOUND ) ); } $remote_body = wp_remote_retrieve_body( $response ); if ( empty( $remote_body ) ) { return new WP_Error( 'no_content', __( 'Unable to retrieve body from response at this URL.' ), array( 'status' => WP_Http::NOT_FOUND ) ); } return $remote_body; } /** * Parses the title tag contents from the provided HTML. * * @since 5.9.0 * * @param string $html The HTML from the remote website at URL. * @return string The title tag contents on success. Empty string if not found. */ private function get_title( $html ) { $pattern = '#<title[^>]*>(.*?)<\s*/\s*title>#is'; preg_match( $pattern, $html, $match_title ); if ( empty( $match_title[1] ) || ! is_string( $match_title[1] ) ) { return ''; } $title = trim( $match_title[1] ); return $this->prepare_metadata_for_output( $title ); } /** * Parses the site icon from the provided HTML. * * @since 5.9.0 * * @param string $html The HTML from the remote website at URL. * @param string $url The target website URL. * @return string The icon URI on success. Empty string if not found. */ private function get_icon( $html, $url ) { // Grab the icon's link element. $pattern = '#<link\s[^>]*rel=(?:[\"\']??)\s*(?:icon|shortcut icon|icon shortcut)\s*(?:[\"\']??)[^>]*\/?>#isU'; preg_match( $pattern, $html, $element ); if ( empty( $element[0] ) || ! is_string( $element[0] ) ) { return ''; } $element = trim( $element[0] ); // Get the icon's href value. $pattern = '#href=([\"\']??)([^\" >]*?)\\1[^>]*#isU'; preg_match( $pattern, $element, $icon ); if ( empty( $icon[2] ) || ! is_string( $icon[2] ) ) { return ''; } $icon = trim( $icon[2] ); // If the icon is a data URL, return it. $parsed_icon = parse_url( $icon ); if ( isset( $parsed_icon['scheme'] ) && 'data' === $parsed_icon['scheme'] ) { return $icon; } // Attempt to convert relative URLs to absolute. if ( ! is_string( $url ) || '' === $url ) { return $icon; } $parsed_url = parse_url( $url ); if ( isset( $parsed_url['scheme'] ) && isset( $parsed_url['host'] ) ) { $root_url = $parsed_url['scheme'] . '://' . $parsed_url['host'] . '/'; $icon = WP_Http::make_absolute_url( $icon, $root_url ); } return $icon; } /** * Parses the meta description from the provided HTML. * * @since 5.9.0 * * @param array $meta_elements { * A multi-dimensional indexed array on success, else empty array. * * @type string[] $0 Meta elements with a content attribute. * @type string[] $1 Content attribute's opening quotation mark. * @type string[] $2 Content attribute's value for each meta element. * } * @return string The meta description contents on success. Empty string if not found. */ private function get_description( $meta_elements ) { // Bail out if there are no meta elements. if ( empty( $meta_elements[0] ) ) { return ''; } $description = $this->get_metadata_from_meta_element( $meta_elements, 'name', '(?:description|og:description)' ); // Bail out if description not found. if ( '' === $description ) { return ''; } return $this->prepare_metadata_for_output( $description ); } /** * Parses the Open Graph (OG) Image from the provided HTML. * * See: https://ogp.me/. * * @since 5.9.0 * * @param array $meta_elements { * A multi-dimensional indexed array on success, else empty array. * * @type string[] $0 Meta elements with a content attribute. * @type string[] $1 Content attribute's opening quotation mark. * @type string[] $2 Content attribute's value for each meta element. * } * @param string $url The target website URL. * @return string The OG image on success. Empty string if not found. */ private function get_image( $meta_elements, $url ) { $image = $this->get_metadata_from_meta_element( $meta_elements, 'property', '(?:og:image|og:image:url)' ); // Bail out if image not found. if ( '' === $image ) { return ''; } // Attempt to convert relative URLs to absolute. $parsed_url = parse_url( $url ); if ( isset( $parsed_url['scheme'] ) && isset( $parsed_url['host'] ) ) { $root_url = $parsed_url['scheme'] . '://' . $parsed_url['host'] . '/'; $image = WP_Http::make_absolute_url( $image, $root_url ); } return $image; } /** * Prepares the metadata by: * - stripping all HTML tags and tag entities. * - converting non-tag entities into characters. * * @since 5.9.0 * * @param string $metadata The metadata content to prepare. * @return string The prepared metadata. */ private function prepare_metadata_for_output( $metadata ) { $metadata = html_entity_decode( $metadata, ENT_QUOTES, get_bloginfo( 'charset' ) ); $metadata = wp_strip_all_tags( $metadata ); return $metadata; } /** * Utility function to build cache key for a given URL. * * @since 5.9.0 * * @param string $url The URL for which to build a cache key. * @return string The cache key. */ private function build_cache_key_for_url( $url ) { return 'g_url_details_response_' . md5( $url ); } /** * Utility function to retrieve a value from the cache at a given key. * * @since 5.9.0 * * @param string $key The cache key. * @return mixed The value from the cache. */ private function get_cache( $key ) { return get_site_transient( $key ); } /** * Utility function to cache a given data set at a given cache key. * * @since 5.9.0 * * @param string $key The cache key under which to store the value. * @param string $data The data to be stored at the given cache key. * @return bool True when transient set. False if not set. */ private function set_cache( $key, $data = '' ) { $ttl = HOUR_IN_SECONDS; /** * Filters the cache expiration. * * Can be used to adjust the time until expiration in seconds for the cache * of the data retrieved for the given URL. * * @since 5.9.0 * * @param int $ttl The time until cache expiration in seconds. */ $cache_expiration = apply_filters( 'rest_url_details_cache_expiration', $ttl ); return set_site_transient( $key, $data, $cache_expiration ); } /** * Retrieves the head element section. * * @since 5.9.0 * * @param string $html The string of HTML to parse. * @return string The `<head>..</head>` section on success. Given `$html` if not found. */ private function get_document_head( $html ) { $head_html = $html; // Find the opening `<head>` tag. $head_start = strpos( $html, '<head' ); if ( false === $head_start ) { // Didn't find it. Return the original HTML. return $html; } // Find the closing `</head>` tag. $head_end = strpos( $head_html, '</head>' ); if ( false === $head_end ) { // Didn't find it. Find the opening `<body>` tag. $head_end = strpos( $head_html, '<body' ); // Didn't find it. Return the original HTML. if ( false === $head_end ) { return $html; } } // Extract the HTML from opening tag to the closing tag. Then add the closing tag. $head_html = substr( $head_html, $head_start, $head_end ); $head_html .= '</head>'; return $head_html; } /** * Gets all the meta tag elements that have a 'content' attribute. * * @since 5.9.0 * * @param string $html The string of HTML to be parsed. * @return array { * A multi-dimensional indexed array on success, else empty array. * * @type string[] $0 Meta elements with a content attribute. * @type string[] $1 Content attribute's opening quotation mark. * @type string[] $2 Content attribute's value for each meta element. * } */ private function get_meta_with_content_elements( $html ) { /* * Parse all meta elements with a content attribute. * * Why first search for the content attribute rather than directly searching for name=description element? * tl;dr The content attribute's value will be truncated when it contains a > symbol. * * The content attribute's value (i.e. the description to get) can have HTML in it and be well-formed as * it's a string to the browser. Imagine what happens when attempting to match for the name=description * first. Hmm, if a > or /> symbol is in the content attribute's value, then it terminates the match * as the element's closing symbol. But wait, it's in the content attribute and is not the end of the * element. This is a limitation of using regex. It can't determine "wait a minute this is inside of quotation". * If this happens, what gets matched is not the entire element or all of the content. * * Why not search for the name=description and then content="(.*)"? * The attribute order could be opposite. Plus, additional attributes may exist including being between * the name and content attributes. * * Why not lookahead? * Lookahead is not constrained to stay within the element. The first <meta it finds may not include * the name or content, but rather could be from a different element downstream. */ $pattern = '#<meta\s' . /* * Allows for additional attributes before the content attribute. * Searches for anything other than > symbol. */ '[^>]*' . /* * Find the content attribute. When found, capture its value (.*). * * Allows for (a) single or double quotes and (b) whitespace in the value. * * Why capture the opening quotation mark, i.e. (["\']), and then backreference, * i.e \1, for the closing quotation mark? * To ensure the closing quotation mark matches the opening one. Why? Attribute values * can contain quotation marks, such as an apostrophe in the content. */ 'content=(["\']??)(.*)\1' . /* * Allows for additional attributes after the content attribute. * Searches for anything other than > symbol. */ '[^>]*' . /* * \/?> searches for the closing > symbol, which can be in either /> or > format. * # ends the pattern. */ '\/?>#' . /* * These are the options: * - i : case insensitive * - s : allows newline characters for the . match (needed for multiline elements) * - U means non-greedy matching */ 'isU'; preg_match_all( $pattern, $html, $elements ); return $elements; } /** * Gets the metadata from a target meta element. * * @since 5.9.0 * * @param array $meta_elements { * A multi-dimensional indexed array on success, else empty array. * * @type string[] $0 Meta elements with a content attribute. * @type string[] $1 Content attribute's opening quotation mark. * @type string[] $2 Content attribute's value for each meta element. * } * @param string $attr Attribute that identifies the element with the target metadata. * @param string $attr_value The attribute's value that identifies the element with the target metadata. * @return string The metadata on success. Empty string if not found. */ private function get_metadata_from_meta_element( $meta_elements, $attr, $attr_value ) { // Bail out if there are no meta elements. if ( empty( $meta_elements[0] ) ) { return ''; } $metadata = ''; $pattern = '#' . /* * Target this attribute and value to find the metadata element. * * Allows for (a) no, single, double quotes and (b) whitespace in the value. * * Why capture the opening quotation mark, i.e. (["\']), and then backreference, * i.e \1, for the closing quotation mark? * To ensure the closing quotation mark matches the opening one. Why? Attribute values * can contain quotation marks, such as an apostrophe in the content. */ $attr . '=([\"\']??)\s*' . $attr_value . '\s*\1' . /* * These are the options: * - i : case insensitive * - s : allows newline characters for the . match (needed for multiline elements) * - U means non-greedy matching */ '#isU'; // Find the metadata element. foreach ( $meta_elements[0] as $index => $element ) { preg_match( $pattern, $element, $match ); // This is not the metadata element. Skip it. if ( empty( $match ) ) { continue; } /* * Found the metadata element. * Get the metadata from its matching content array. */ if ( isset( $meta_elements[2][ $index ] ) && is_string( $meta_elements[2][ $index ] ) ) { $metadata = trim( $meta_elements[2][ $index ] ); } break; } return $metadata; } } ``` | Uses | Description | | --- | --- | | [WP\_REST\_Controller](wp_rest_controller) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Core base controller for managing and interacting with REST API items. | | Version | Description | | --- | --- | | [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
programming_docs