code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
wordpress class Requests_Exception_HTTP_429 {} class Requests\_Exception\_HTTP\_429 {}
=======================================
Exception for 429 Too Many Requests responses
* <https://tools.ietf.org/html/draft-nottingham-http-new-status-04>
File: `wp-includes/Requests/Exception/HTTP/429.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/429.php/)
```
class Requests_Exception_HTTP_429 extends Requests_Exception_HTTP {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 429;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Too Many Requests';
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response |
wordpress class WP_Customize_Background_Position_Control {} class WP\_Customize\_Background\_Position\_Control {}
=====================================================
Customize Background Position Control class.
* [WP\_Customize\_Control](wp_customize_control)
* [content\_template](wp_customize_background_position_control/content_template) — Render a JS template for the content of the position control.
* [render\_content](wp_customize_background_position_control/render_content) — Don't render the control content from PHP, as it's rendered via JS on load.
File: `wp-includes/customize/class-wp-customize-background-position-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-background-position-control.php/)
```
class WP_Customize_Background_Position_Control extends WP_Customize_Control {
/**
* Type.
*
* @since 4.7.0
* @var string
*/
public $type = 'background_position';
/**
* Don't render the control content from PHP, as it's rendered via JS on load.
*
* @since 4.7.0
*/
public function render_content() {}
/**
* Render a JS template for the content of the position control.
*
* @since 4.7.0
*/
public function content_template() {
$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',
),
),
);
?>
<# 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">
<fieldset>
<legend class="screen-reader-text"><span><?php _e( 'Image Position' ); ?></span></legend>
<div class="background-position-control">
<?php foreach ( $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 ); ?>">
<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>
</div>
<?php
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control](wp_customize_control) wp-includes/class-wp-customize-control.php | Customize Control class. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress class WP_Customize_Date_Time_Control {} class WP\_Customize\_Date\_Time\_Control {}
===========================================
Customize Date Time Control class.
* [WP\_Customize\_Control](wp_customize_control)
* [content\_template](wp_customize_date_time_control/content_template) — Renders a JS template for the content of date time control.
* [format\_gmt\_offset](wp_customize_date_time_control/format_gmt_offset) — Format GMT Offset.
* [get\_month\_choices](wp_customize_date_time_control/get_month_choices) — Generate options for the month Select.
* [get\_timezone\_info](wp_customize_date_time_control/get_timezone_info) — Get timezone info.
* [json](wp_customize_date_time_control/json) — Export data to JS.
* [render\_content](wp_customize_date_time_control/render_content) — Don't render the control's content - it's rendered with a JS template.
File: `wp-includes/customize/class-wp-customize-date-time-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-date-time-control.php/)
```
class WP_Customize_Date_Time_Control extends WP_Customize_Control {
/**
* Customize control type.
*
* @since 4.9.0
* @var string
*/
public $type = 'date_time';
/**
* Minimum Year.
*
* @since 4.9.0
* @var int
*/
public $min_year = 1000;
/**
* Maximum Year.
*
* @since 4.9.0
* @var int
*/
public $max_year = 9999;
/**
* Allow past date, if set to false user can only select future date.
*
* @since 4.9.0
* @var bool
*/
public $allow_past_date = true;
/**
* Whether hours, minutes, and meridian should be shown.
*
* @since 4.9.0
* @var bool
*/
public $include_time = true;
/**
* If set to false the control will appear in 24 hour format,
* the value will still be saved in Y-m-d H:i:s format.
*
* @since 4.9.0
* @var bool
*/
public $twelve_hour_format = true;
/**
* Don't render the control's content - it's rendered with a JS template.
*
* @since 4.9.0
*/
public function render_content() {}
/**
* Export data to JS.
*
* @since 4.9.0
* @return array
*/
public function json() {
$data = parent::json();
$data['maxYear'] = (int) $this->max_year;
$data['minYear'] = (int) $this->min_year;
$data['allowPastDate'] = (bool) $this->allow_past_date;
$data['twelveHourFormat'] = (bool) $this->twelve_hour_format;
$data['includeTime'] = (bool) $this->include_time;
return $data;
}
/**
* Renders a JS template for the content of date time control.
*
* @since 4.9.0
*/
public function content_template() {
$data = array_merge( $this->json(), $this->get_month_choices() );
$timezone_info = $this->get_timezone_info();
$date_format = get_option( 'date_format' );
$date_format = preg_replace( '/(?<!\\\\)[Yyo]/', '%1$s', $date_format );
$date_format = preg_replace( '/(?<!\\\\)[FmMn]/', '%2$s', $date_format );
$date_format = preg_replace( '/(?<!\\\\)[jd]/', '%3$s', $date_format );
// Fallback to ISO date format if year, month, or day are missing from the date format.
if ( 1 !== substr_count( $date_format, '%1$s' ) || 1 !== substr_count( $date_format, '%2$s' ) || 1 !== substr_count( $date_format, '%3$s' ) ) {
$date_format = '%1$s-%2$s-%3$s';
}
?>
<# _.defaults( data, <?php echo wp_json_encode( $data ); ?> ); #>
<# var idPrefix = _.uniqueId( 'el' ) + '-'; #>
<# if ( data.label ) { #>
<span class="customize-control-title">
{{ data.label }}
</span>
<# } #>
<div class="customize-control-notifications-container"></div>
<# if ( data.description ) { #>
<span class="description customize-control-description">{{ data.description }}</span>
<# } #>
<div class="date-time-fields {{ data.includeTime ? 'includes-time' : '' }}">
<fieldset class="day-row">
<legend class="title-day {{ ! data.includeTime ? 'screen-reader-text' : '' }}"><?php esc_html_e( 'Date' ); ?></legend>
<div class="day-fields clear">
<?php ob_start(); ?>
<label for="{{ idPrefix }}date-time-month" class="screen-reader-text"><?php esc_html_e( 'Month' ); ?></label>
<select id="{{ idPrefix }}date-time-month" class="date-input month" data-component="month">
<# _.each( data.month_choices, function( choice ) {
if ( _.isObject( choice ) && ! _.isUndefined( choice.text ) && ! _.isUndefined( choice.value ) ) {
text = choice.text;
value = choice.value;
}
#>
<option value="{{ value }}" >
{{ text }}
</option>
<# } ); #>
</select>
<?php $month_field = trim( ob_get_clean() ); ?>
<?php ob_start(); ?>
<label for="{{ idPrefix }}date-time-day" class="screen-reader-text"><?php esc_html_e( 'Day' ); ?></label>
<input id="{{ idPrefix }}date-time-day" type="number" size="2" autocomplete="off" class="date-input day" data-component="day" min="1" max="31" />
<?php $day_field = trim( ob_get_clean() ); ?>
<?php ob_start(); ?>
<label for="{{ idPrefix }}date-time-year" class="screen-reader-text"><?php esc_html_e( 'Year' ); ?></label>
<input id="{{ idPrefix }}date-time-year" type="number" size="4" autocomplete="off" class="date-input year" data-component="year" min="{{ data.minYear }}" max="{{ data.maxYear }}">
<?php $year_field = trim( ob_get_clean() ); ?>
<?php printf( $date_format, $year_field, $month_field, $day_field ); ?>
</div>
</fieldset>
<# if ( data.includeTime ) { #>
<fieldset class="time-row clear">
<legend class="title-time"><?php esc_html_e( 'Time' ); ?></legend>
<div class="time-fields clear">
<label for="{{ idPrefix }}date-time-hour" class="screen-reader-text"><?php esc_html_e( 'Hour' ); ?></label>
<# var maxHour = data.twelveHourFormat ? 12 : 23; #>
<# var minHour = data.twelveHourFormat ? 1 : 0; #>
<input id="{{ idPrefix }}date-time-hour" type="number" size="2" autocomplete="off" class="date-input hour" data-component="hour" min="{{ minHour }}" max="{{ maxHour }}">
:
<label for="{{ idPrefix }}date-time-minute" class="screen-reader-text"><?php esc_html_e( 'Minute' ); ?></label>
<input id="{{ idPrefix }}date-time-minute" type="number" size="2" autocomplete="off" class="date-input minute" data-component="minute" min="0" max="59">
<# if ( data.twelveHourFormat ) { #>
<label for="{{ idPrefix }}date-time-meridian" class="screen-reader-text"><?php esc_html_e( 'Meridian' ); ?></label>
<select id="{{ idPrefix }}date-time-meridian" class="date-input meridian" data-component="meridian">
<option value="am"><?php esc_html_e( 'AM' ); ?></option>
<option value="pm"><?php esc_html_e( 'PM' ); ?></option>
</select>
<# } #>
<p><?php echo $timezone_info['description']; ?></p>
</div>
</fieldset>
<# } #>
</div>
<?php
}
/**
* Generate options for the month Select.
*
* Based on touch_time().
*
* @since 4.9.0
*
* @see touch_time()
*
* @global WP_Locale $wp_locale WordPress date and time locale object.
*
* @return array
*/
public function get_month_choices() {
global $wp_locale;
$months = array();
for ( $i = 1; $i < 13; $i++ ) {
$month_text = $wp_locale->get_month_abbrev( $wp_locale->get_month( $i ) );
/* translators: 1: Month number (01, 02, etc.), 2: Month abbreviation. */
$months[ $i ]['text'] = sprintf( __( '%1$s-%2$s' ), $i, $month_text );
$months[ $i ]['value'] = $i;
}
return array(
'month_choices' => $months,
);
}
/**
* Get timezone info.
*
* @since 4.9.0
*
* @return array {
* Timezone info. All properties are optional.
*
* @type string $abbr Timezone abbreviation. Examples: PST or CEST.
* @type string $description Human-readable timezone description as HTML.
* }
*/
public function get_timezone_info() {
$tz_string = get_option( 'timezone_string' );
$timezone_info = array();
if ( $tz_string ) {
try {
$tz = new DateTimeZone( $tz_string );
} catch ( Exception $e ) {
$tz = '';
}
if ( $tz ) {
$now = new DateTime( 'now', $tz );
$formatted_gmt_offset = $this->format_gmt_offset( $tz->getOffset( $now ) / 3600 );
$tz_name = str_replace( '_', ' ', $tz->getName() );
$timezone_info['abbr'] = $now->format( 'T' );
$timezone_info['description'] = sprintf(
/* translators: 1: Timezone name, 2: Timezone abbreviation, 3: UTC abbreviation and offset, 4: UTC offset. */
__( 'Your timezone is set to %1$s (%2$s), currently %3$s (Coordinated Universal Time %4$s).' ),
$tz_name,
'<abbr>' . $timezone_info['abbr'] . '</abbr>',
'<abbr>UTC</abbr>' . $formatted_gmt_offset,
$formatted_gmt_offset
);
} else {
$timezone_info['description'] = '';
}
} else {
$formatted_gmt_offset = $this->format_gmt_offset( (int) get_option( 'gmt_offset', 0 ) );
$timezone_info['description'] = sprintf(
/* translators: 1: UTC abbreviation and offset, 2: UTC offset. */
__( 'Your timezone is set to %1$s (Coordinated Universal Time %2$s).' ),
'<abbr>UTC</abbr>' . $formatted_gmt_offset,
$formatted_gmt_offset
);
}
return $timezone_info;
}
/**
* Format GMT Offset.
*
* @since 4.9.0
*
* @see wp_timezone_choice()
*
* @param float $offset Offset in hours.
* @return string Formatted offset.
*/
public function format_gmt_offset( $offset ) {
if ( 0 <= $offset ) {
$formatted_offset = '+' . (string) $offset;
} else {
$formatted_offset = (string) $offset;
}
$formatted_offset = str_replace(
array( '.25', '.5', '.75' ),
array( ':15', ':30', ':45' ),
$formatted_offset
);
return $formatted_offset;
}
}
```
| 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_Panel {} class WP\_Customize\_Panel {}
=============================
Customize Panel class.
A UI container for sections, managed by the [WP\_Customize\_Manager](wp_customize_manager).
* [WP\_Customize\_Manager](wp_customize_manager)
* [\_\_construct](wp_customize_panel/__construct) — Constructor.
* [active](wp_customize_panel/active) — Check whether panel is active to current Customizer preview.
* [active\_callback](wp_customize_panel/active_callback) — Default callback used when invoking WP\_Customize\_Panel::active().
* [check\_capabilities](wp_customize_panel/check_capabilities) — Checks required user capabilities and whether the theme has the feature support required by the panel.
* [content\_template](wp_customize_panel/content_template) — An Underscore (JS) template for this panel's content (but not its container).
* [get\_content](wp_customize_panel/get_content) — Get the panel's content template for insertion into the Customizer pane.
* [json](wp_customize_panel/json) — Gather the parameters passed to client JavaScript via JSON.
* [maybe\_render](wp_customize_panel/maybe_render) — Check capabilities and render the panel.
* [print\_template](wp_customize_panel/print_template) — Render the panel's JS templates.
* [render](wp_customize_panel/render) — Render the panel container, and then its contents (via `this->render\_content()`) in a subclass.
* [render\_content](wp_customize_panel/render_content) — Render the panel UI in a subclass.
* [render\_template](wp_customize_panel/render_template) — An Underscore (JS) template for rendering this panel's container.
File: `wp-includes/class-wp-customize-panel.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-panel.php/)
```
class WP_Customize_Panel {
/**
* 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;
/**
* WP_Customize_Manager instance.
*
* @since 4.0.0
* @var WP_Customize_Manager
*/
public $manager;
/**
* Unique identifier.
*
* @since 4.0.0
* @var string
*/
public $id;
/**
* Priority of the panel, defining the display order of panels and sections.
*
* @since 4.0.0
* @var int
*/
public $priority = 160;
/**
* Capability required for the panel.
*
* @since 4.0.0
* @var string
*/
public $capability = 'edit_theme_options';
/**
* Theme features required to support the panel.
*
* @since 4.0.0
* @var mixed[]
*/
public $theme_supports = '';
/**
* Title of the panel to show in UI.
*
* @since 4.0.0
* @var string
*/
public $title = '';
/**
* Description to show in the UI.
*
* @since 4.0.0
* @var string
*/
public $description = '';
/**
* Auto-expand a section in a panel when the panel is expanded when the panel only has the one section.
*
* @since 4.7.4
* @var bool
*/
public $auto_expand_sole_section = false;
/**
* Customizer sections for this panel.
*
* @since 4.0.0
* @var array
*/
public $sections;
/**
* Type of this panel.
*
* @since 4.1.0
* @var string
*/
public $type = 'default';
/**
* Active callback.
*
* @since 4.1.0
*
* @see WP_Customize_Section::active()
*
* @var callable Callback is called with one argument, the instance of
* WP_Customize_Section, and returns bool to indicate whether
* the section is active (such as it relates to the URL currently
* being previewed).
*/
public $active_callback = '';
/**
* Constructor.
*
* Any supplied $args override class property defaults.
*
* @since 4.0.0
*
* @param WP_Customize_Manager $manager Customizer bootstrap instance.
* @param string $id A specific ID for the panel.
* @param array $args {
* Optional. Array of properties for the new Panel object. Default empty array.
*
* @type int $priority Priority of the panel, defining the display order
* of panels and sections. Default 160.
* @type string $capability Capability required for the panel.
* Default `edit_theme_options`.
* @type mixed[] $theme_supports Theme features required to support the panel.
* @type string $title Title of the panel to show in UI.
* @type string $description Description to show in the UI.
* @type string $type Type of the panel.
* @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;
$this->sections = array(); // Users cannot customize the $sections array.
}
/**
* Check whether panel is active to current Customizer preview.
*
* @since 4.1.0
*
* @return bool Whether the panel is active to the current preview.
*/
final public function active() {
$panel = $this;
$active = call_user_func( $this->active_callback, $this );
/**
* Filters response of WP_Customize_Panel::active().
*
* @since 4.1.0
*
* @param bool $active Whether the Customizer panel is active.
* @param WP_Customize_Panel $panel WP_Customize_Panel instance.
*/
$active = apply_filters( 'customize_panel_active', $active, $panel );
return $active;
}
/**
* Default callback used when invoking WP_Customize_Panel::active().
*
* Subclasses can override this with their specific logic, or they may
* provide an 'active_callback' argument to the constructor.
*
* @since 4.1.0
*
* @return bool Always true.
*/
public function active_callback() {
return true;
}
/**
* Gather the parameters passed to client JavaScript via JSON.
*
* @since 4.1.0
*
* @return array The array to be exported to the client as JSON.
*/
public function json() {
$array = wp_array_slice_assoc( (array) $this, array( 'id', 'description', 'priority', 'type' ) );
$array['title'] = html_entity_decode( $this->title, ENT_QUOTES, get_bloginfo( 'charset' ) );
$array['content'] = $this->get_content();
$array['active'] = $this->active();
$array['instanceNumber'] = $this->instance_number;
$array['autoExpandSoleSection'] = $this->auto_expand_sole_section;
return $array;
}
/**
* Checks required user capabilities and whether the theme has the
* feature support required by the panel.
*
* @since 4.0.0
* @since 5.9.0 Method was marked non-final.
*
* @return bool False if theme doesn't support the panel or the user doesn't have the capability.
*/
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;
}
/**
* Get the panel's content template for insertion into the Customizer pane.
*
* @since 4.1.0
*
* @return string Content for the panel.
*/
final public function get_content() {
ob_start();
$this->maybe_render();
return trim( ob_get_clean() );
}
/**
* Check capabilities and render the panel.
*
* @since 4.0.0
*/
final public function maybe_render() {
if ( ! $this->check_capabilities() ) {
return;
}
/**
* Fires before rendering a Customizer panel.
*
* @since 4.0.0
*
* @param WP_Customize_Panel $panel WP_Customize_Panel instance.
*/
do_action( 'customize_render_panel', $this );
/**
* Fires before rendering a specific Customizer panel.
*
* The dynamic portion of the hook name, `$this->id`, refers to
* the ID of the specific Customizer panel to be rendered.
*
* @since 4.0.0
*/
do_action( "customize_render_panel_{$this->id}" );
$this->render();
}
/**
* Render the panel container, and then its contents (via `this->render_content()`) in a subclass.
*
* Panel containers are now rendered in JS by default, see WP_Customize_Panel::print_template().
*
* @since 4.0.0
*/
protected function render() {}
/**
* Render the panel UI in a subclass.
*
* Panel contents are now rendered in JS by default, see WP_Customize_Panel::print_template().
*
* @since 4.1.0
*/
protected function render_content() {}
/**
* Render the panel's JS templates.
*
* This function is only run for panel types that have been registered with
* WP_Customize_Manager::register_panel_type().
*
* @since 4.3.0
*
* @see WP_Customize_Manager::register_panel_type()
*/
public function print_template() {
?>
<script type="text/html" id="tmpl-customize-panel-<?php echo esc_attr( $this->type ); ?>-content">
<?php $this->content_template(); ?>
</script>
<script type="text/html" id="tmpl-customize-panel-<?php echo esc_attr( $this->type ); ?>">
<?php $this->render_template(); ?>
</script>
<?php
}
/**
* An Underscore (JS) template for rendering this panel's container.
*
* Class variables for this panel class are available in the `data` JS object;
* export custom variables by overriding WP_Customize_Panel::json().
*
* @see WP_Customize_Panel::print_template()
*
* @since 4.3.0
*/
protected function render_template() {
?>
<li id="accordion-panel-{{ data.id }}" class="accordion-section control-section control-panel control-panel-{{ data.type }}">
<h3 class="accordion-section-title" tabindex="0">
{{ data.title }}
<span class="screen-reader-text"><?php _e( 'Press return or enter to open this panel' ); ?></span>
</h3>
<ul class="accordion-sub-container control-panel-content"></ul>
</li>
<?php
}
/**
* 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().
*
* @see WP_Customize_Panel::print_template()
*
* @since 4.3.0
*/
protected function content_template() {
?>
<li class="panel-meta customize-info accordion-section <# if ( ! data.description ) { #> cannot-expand<# } #>">
<button class="customize-panel-back" tabindex="-1"><span class="screen-reader-text"><?php _e( 'Back' ); ?></span></button>
<div class="accordion-section-title">
<span class="preview-notice">
<?php
/* translators: %s: The site/panel title in the Customizer. */
printf( __( 'You are customizing %s' ), '<strong class="panel-title">{{ data.title }}</strong>' );
?>
</span>
<# if ( data.description ) { #>
<button type="button" class="customize-help-toggle dashicons dashicons-editor-help" aria-expanded="false"><span class="screen-reader-text"><?php _e( 'Help' ); ?></span></button>
<# } #>
</div>
<# if ( data.description ) { #>
<div class="description customize-panel-description">
{{{ data.description }}}
</div>
<# } #>
<div class="customize-control-notifications-container"></div>
</li>
<?php
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Themes\_Panel](wp_customize_themes_panel) wp-includes/customize/class-wp-customize-themes-panel.php | Customize Themes Panel Class |
| [WP\_Customize\_Nav\_Menus\_Panel](wp_customize_nav_menus_panel) wp-includes/customize/class-wp-customize-nav-menus-panel.php | Customize Nav Menus Panel Class |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
| programming_docs |
wordpress class Requests_Transport_fsockopen {} class Requests\_Transport\_fsockopen {}
=======================================
fsockopen HTTP transport
* [accept\_encoding](requests_transport_fsockopen/accept_encoding) — Retrieve the encodings we can accept
* [connect\_error\_handler](requests_transport_fsockopen/connect_error_handler) — Error handler for stream\_socket\_client()
* [format\_get](requests_transport_fsockopen/format_get) — Format a URL given GET data
* [request](requests_transport_fsockopen/request) — Perform a request
* [request\_multiple](requests_transport_fsockopen/request_multiple) — Send multiple requests simultaneously
* [test](requests_transport_fsockopen/test) — Whether this transport is valid
* [verify\_certificate\_from\_context](requests_transport_fsockopen/verify_certificate_from_context) — Verify the certificate against common name and subject alternative names
File: `wp-includes/Requests/Transport/fsockopen.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/transport/fsockopen.php/)
```
class Requests_Transport_fsockopen implements Requests_Transport {
/**
* Second to microsecond conversion
*
* @var integer
*/
const SECOND_IN_MICROSECONDS = 1000000;
/**
* Raw HTTP data
*
* @var string
*/
public $headers = '';
/**
* Stream metadata
*
* @var array Associative array of properties, see {@see https://secure.php.net/stream_get_meta_data}
*/
public $info;
/**
* What's the maximum number of bytes we should keep?
*
* @var int|bool Byte count, or false if no limit.
*/
protected $max_bytes = false;
protected $connect_error = '';
/**
* Perform a request
*
* @throws Requests_Exception On failure to connect to socket (`fsockopenerror`)
* @throws Requests_Exception On socket timeout (`timeout`)
*
* @param string $url URL to request
* @param array $headers Associative array of request headers
* @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
* @param array $options Request options, see {@see Requests::response()} for documentation
* @return string Raw HTTP result
*/
public function request($url, $headers = array(), $data = array(), $options = array()) {
$options['hooks']->dispatch('fsockopen.before_request');
$url_parts = parse_url($url);
if (empty($url_parts)) {
throw new Requests_Exception('Invalid URL.', 'invalidurl', $url);
}
$host = $url_parts['host'];
$context = stream_context_create();
$verifyname = false;
$case_insensitive_headers = new Requests_Utility_CaseInsensitiveDictionary($headers);
// HTTPS support
if (isset($url_parts['scheme']) && strtolower($url_parts['scheme']) === 'https') {
$remote_socket = 'ssl://' . $host;
if (!isset($url_parts['port'])) {
$url_parts['port'] = 443;
}
$context_options = array(
'verify_peer' => true,
'capture_peer_cert' => true,
);
$verifyname = true;
// SNI, if enabled (OpenSSL >=0.9.8j)
// phpcs:ignore PHPCompatibility.Constants.NewConstants.openssl_tlsext_server_nameFound
if (defined('OPENSSL_TLSEXT_SERVER_NAME') && OPENSSL_TLSEXT_SERVER_NAME) {
$context_options['SNI_enabled'] = true;
if (isset($options['verifyname']) && $options['verifyname'] === false) {
$context_options['SNI_enabled'] = false;
}
}
if (isset($options['verify'])) {
if ($options['verify'] === false) {
$context_options['verify_peer'] = false;
$context_options['verify_peer_name'] = false;
$verifyname = false;
}
elseif (is_string($options['verify'])) {
$context_options['cafile'] = $options['verify'];
}
}
if (isset($options['verifyname']) && $options['verifyname'] === false) {
$context_options['verify_peer_name'] = false;
$verifyname = false;
}
stream_context_set_option($context, array('ssl' => $context_options));
}
else {
$remote_socket = 'tcp://' . $host;
}
$this->max_bytes = $options['max_bytes'];
if (!isset($url_parts['port'])) {
$url_parts['port'] = 80;
}
$remote_socket .= ':' . $url_parts['port'];
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_set_error_handler
set_error_handler(array($this, 'connect_error_handler'), E_WARNING | E_NOTICE);
$options['hooks']->dispatch('fsockopen.remote_socket', array(&$remote_socket));
$socket = stream_socket_client($remote_socket, $errno, $errstr, ceil($options['connect_timeout']), STREAM_CLIENT_CONNECT, $context);
restore_error_handler();
if ($verifyname && !$this->verify_certificate_from_context($host, $context)) {
throw new Requests_Exception('SSL certificate did not match the requested domain name', 'ssl.no_match');
}
if (!$socket) {
if ($errno === 0) {
// Connection issue
throw new Requests_Exception(rtrim($this->connect_error), 'fsockopen.connect_error');
}
throw new Requests_Exception($errstr, 'fsockopenerror', null, $errno);
}
$data_format = $options['data_format'];
if ($data_format === 'query') {
$path = self::format_get($url_parts, $data);
$data = '';
}
else {
$path = self::format_get($url_parts, array());
}
$options['hooks']->dispatch('fsockopen.remote_host_path', array(&$path, $url));
$request_body = '';
$out = sprintf("%s %s HTTP/%.1F\r\n", $options['type'], $path, $options['protocol_version']);
if ($options['type'] !== Requests::TRACE) {
if (is_array($data)) {
$request_body = http_build_query($data, '', '&');
}
else {
$request_body = $data;
}
// Always include Content-length on POST requests to prevent
// 411 errors from some servers when the body is empty.
if (!empty($data) || $options['type'] === Requests::POST) {
if (!isset($case_insensitive_headers['Content-Length'])) {
$headers['Content-Length'] = strlen($request_body);
}
if (!isset($case_insensitive_headers['Content-Type'])) {
$headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
}
}
}
if (!isset($case_insensitive_headers['Host'])) {
$out .= sprintf('Host: %s', $url_parts['host']);
if ((strtolower($url_parts['scheme']) === 'http' && $url_parts['port'] !== 80) || (strtolower($url_parts['scheme']) === 'https' && $url_parts['port'] !== 443)) {
$out .= ':' . $url_parts['port'];
}
$out .= "\r\n";
}
if (!isset($case_insensitive_headers['User-Agent'])) {
$out .= sprintf("User-Agent: %s\r\n", $options['useragent']);
}
$accept_encoding = $this->accept_encoding();
if (!isset($case_insensitive_headers['Accept-Encoding']) && !empty($accept_encoding)) {
$out .= sprintf("Accept-Encoding: %s\r\n", $accept_encoding);
}
$headers = Requests::flatten($headers);
if (!empty($headers)) {
$out .= implode("\r\n", $headers) . "\r\n";
}
$options['hooks']->dispatch('fsockopen.after_headers', array(&$out));
if (substr($out, -2) !== "\r\n") {
$out .= "\r\n";
}
if (!isset($case_insensitive_headers['Connection'])) {
$out .= "Connection: Close\r\n";
}
$out .= "\r\n" . $request_body;
$options['hooks']->dispatch('fsockopen.before_send', array(&$out));
fwrite($socket, $out);
$options['hooks']->dispatch('fsockopen.after_send', array($out));
if (!$options['blocking']) {
fclose($socket);
$fake_headers = '';
$options['hooks']->dispatch('fsockopen.after_request', array(&$fake_headers));
return '';
}
$timeout_sec = (int) floor($options['timeout']);
if ($timeout_sec === $options['timeout']) {
$timeout_msec = 0;
}
else {
$timeout_msec = self::SECOND_IN_MICROSECONDS * $options['timeout'] % self::SECOND_IN_MICROSECONDS;
}
stream_set_timeout($socket, $timeout_sec, $timeout_msec);
$response = '';
$body = '';
$headers = '';
$this->info = stream_get_meta_data($socket);
$size = 0;
$doingbody = false;
$download = false;
if ($options['filename']) {
$download = fopen($options['filename'], 'wb');
}
while (!feof($socket)) {
$this->info = stream_get_meta_data($socket);
if ($this->info['timed_out']) {
throw new Requests_Exception('fsocket timed out', 'timeout');
}
$block = fread($socket, Requests::BUFFER_SIZE);
if (!$doingbody) {
$response .= $block;
if (strpos($response, "\r\n\r\n")) {
list($headers, $block) = explode("\r\n\r\n", $response, 2);
$doingbody = true;
}
}
// Are we in body mode now?
if ($doingbody) {
$options['hooks']->dispatch('request.progress', array($block, $size, $this->max_bytes));
$data_length = strlen($block);
if ($this->max_bytes) {
// Have we already hit a limit?
if ($size === $this->max_bytes) {
continue;
}
if (($size + $data_length) > $this->max_bytes) {
// Limit the length
$limited_length = ($this->max_bytes - $size);
$block = substr($block, 0, $limited_length);
}
}
$size += strlen($block);
if ($download) {
fwrite($download, $block);
}
else {
$body .= $block;
}
}
}
$this->headers = $headers;
if ($download) {
fclose($download);
}
else {
$this->headers .= "\r\n\r\n" . $body;
}
fclose($socket);
$options['hooks']->dispatch('fsockopen.after_request', array(&$this->headers, &$this->info));
return $this->headers;
}
/**
* Send multiple requests simultaneously
*
* @param array $requests Request data (array of 'url', 'headers', 'data', 'options') as per {@see Requests_Transport::request}
* @param array $options Global options, see {@see Requests::response()} for documentation
* @return array Array of Requests_Response objects (may contain Requests_Exception or string responses as well)
*/
public function request_multiple($requests, $options) {
$responses = array();
$class = get_class($this);
foreach ($requests as $id => $request) {
try {
$handler = new $class();
$responses[$id] = $handler->request($request['url'], $request['headers'], $request['data'], $request['options']);
$request['options']['hooks']->dispatch('transport.internal.parse_response', array(&$responses[$id], $request));
}
catch (Requests_Exception $e) {
$responses[$id] = $e;
}
if (!is_string($responses[$id])) {
$request['options']['hooks']->dispatch('multiple.request.complete', array(&$responses[$id], $id));
}
}
return $responses;
}
/**
* Retrieve the encodings we can accept
*
* @return string Accept-Encoding header value
*/
protected static function accept_encoding() {
$type = array();
if (function_exists('gzinflate')) {
$type[] = 'deflate;q=1.0';
}
if (function_exists('gzuncompress')) {
$type[] = 'compress;q=0.5';
}
$type[] = 'gzip;q=0.5';
return implode(', ', $type);
}
/**
* Format a URL given GET data
*
* @param array $url_parts
* @param array|object $data Data to build query using, see {@see https://secure.php.net/http_build_query}
* @return string URL with data
*/
protected static function format_get($url_parts, $data) {
if (!empty($data)) {
if (empty($url_parts['query'])) {
$url_parts['query'] = '';
}
$url_parts['query'] .= '&' . http_build_query($data, '', '&');
$url_parts['query'] = trim($url_parts['query'], '&');
}
if (isset($url_parts['path'])) {
if (isset($url_parts['query'])) {
$get = $url_parts['path'] . '?' . $url_parts['query'];
}
else {
$get = $url_parts['path'];
}
}
else {
$get = '/';
}
return $get;
}
/**
* Error handler for stream_socket_client()
*
* @param int $errno Error number (e.g. E_WARNING)
* @param string $errstr Error message
*/
public function connect_error_handler($errno, $errstr) {
// Double-check we can handle it
if (($errno & E_WARNING) === 0 && ($errno & E_NOTICE) === 0) {
// Return false to indicate the default error handler should engage
return false;
}
$this->connect_error .= $errstr . "\n";
return true;
}
/**
* 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.
* Instead
*
* @see https://tools.ietf.org/html/rfc2818#section-3.1 RFC2818, Section 3.1
*
* @throws Requests_Exception On failure to connect via TLS (`fsockopen.ssl.connect_error`)
* @throws Requests_Exception On not obtaining a match for the host (`fsockopen.ssl.no_match`)
* @param string $host Host name to verify against
* @param resource $context Stream context
* @return bool
*/
public function verify_certificate_from_context($host, $context) {
$meta = stream_context_get_options($context);
// If we don't have SSL options, then we couldn't make the connection at
// all
if (empty($meta) || empty($meta['ssl']) || empty($meta['ssl']['peer_certificate'])) {
throw new Requests_Exception(rtrim($this->connect_error), 'ssl.connect_error');
}
$cert = openssl_x509_parse($meta['ssl']['peer_certificate']);
return Requests_SSL::verify_certificate($host, $cert);
}
/**
* Whether this transport is valid
*
* @codeCoverageIgnore
* @return boolean True if the transport is valid, false otherwise.
*/
public static function test($capabilities = array()) {
if (!function_exists('fsockopen')) {
return false;
}
// If needed, check that streams support SSL
if (isset($capabilities['ssl']) && $capabilities['ssl']) {
if (!extension_loaded('openssl') || !function_exists('openssl_x509_parse')) {
return false;
}
// Currently broken, thanks to https://github.com/facebook/hhvm/issues/2156
if (defined('HHVM_VERSION')) {
return false;
}
}
return true;
}
}
```
wordpress class WP_Theme_JSON_Data {} class WP\_Theme\_JSON\_Data {}
==============================
Class to provide access to update a theme.json structure.
* [\_\_construct](wp_theme_json_data/__construct) — Constructor.
* [get\_data](wp_theme_json_data/get_data) — Returns an array containing the underlying data following the theme.json specification.
* [update\_with](wp_theme_json_data/update_with) — Updates the theme.json with the the given data.
File: `wp-includes/class-wp-theme-json-data.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme-json-data.php/)
```
class WP_Theme_JSON_Data {
/**
* Container of the data to update.
*
* @since 6.1.0
* @var WP_Theme_JSON
*/
private $theme_json = null;
/**
* The origin of the data: default, theme, user, etc.
*
* @since 6.1.0
* @var string
*/
private $origin = '';
/**
* Constructor.
*
* @since 6.1.0
*
* @link https://developer.wordpress.org/block-editor/reference-guides/theme-json-reference/
*
* @param array $data Array following the theme.json specification.
* @param string $origin The origin of the data: default, theme, user.
*/
public function __construct( $data = array(), $origin = 'theme' ) {
$this->origin = $origin;
$this->theme_json = new WP_Theme_JSON( $data, $this->origin );
}
/**
* Updates the theme.json with the the given data.
*
* @since 6.1.0
*
* @param array $new_data Array following the theme.json specification.
*
* @return WP_Theme_JSON_Data The own instance with access to the modified data.
*/
public function update_with( $new_data ) {
$this->theme_json->merge( new WP_Theme_JSON( $new_data, $this->origin ) );
return $this;
}
/**
* Returns an array containing the underlying data
* following the theme.json specification.
*
* @since 6.1.0
*
* @return array
*/
public function get_data() {
return $this->theme_json->get_raw_data();
}
}
```
wordpress class Plural_Forms {} class Plural\_Forms {}
======================
* [\_\_construct](plural_forms/__construct) — Constructor.
* [execute](plural_forms/execute) — Execute the plural form function.
* [get](plural_forms/get) — Get the plural form for a number.
* [parse](plural_forms/parse) — Parse a Plural-Forms string into tokens.
File: `wp-includes/pomo/plural-forms.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/plural-forms.php/)
```
class Plural_Forms {
/**
* Operator characters.
*
* @since 4.9.0
* @var string OP_CHARS Operator characters.
*/
const OP_CHARS = '|&><!=%?:';
/**
* Valid number characters.
*
* @since 4.9.0
* @var string NUM_CHARS Valid number characters.
*/
const NUM_CHARS = '0123456789';
/**
* Operator precedence.
*
* Operator precedence from highest to lowest. Higher numbers indicate
* higher precedence, and are executed first.
*
* @see https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
*
* @since 4.9.0
* @var array $op_precedence Operator precedence from highest to lowest.
*/
protected static $op_precedence = array(
'%' => 6,
'<' => 5,
'<=' => 5,
'>' => 5,
'>=' => 5,
'==' => 4,
'!=' => 4,
'&&' => 3,
'||' => 2,
'?:' => 1,
'?' => 1,
'(' => 0,
')' => 0,
);
/**
* Tokens generated from the string.
*
* @since 4.9.0
* @var array $tokens List of tokens.
*/
protected $tokens = array();
/**
* Cache for repeated calls to the function.
*
* @since 4.9.0
* @var array $cache Map of $n => $result
*/
protected $cache = array();
/**
* Constructor.
*
* @since 4.9.0
*
* @param string $str Plural function (just the bit after `plural=` from Plural-Forms)
*/
public function __construct( $str ) {
$this->parse( $str );
}
/**
* Parse a Plural-Forms string into tokens.
*
* Uses the shunting-yard algorithm to convert the string to Reverse Polish
* Notation tokens.
*
* @since 4.9.0
*
* @throws Exception If there is a syntax or parsing error with the string.
*
* @param string $str String to parse.
*/
protected function parse( $str ) {
$pos = 0;
$len = strlen( $str );
// Convert infix operators to postfix using the shunting-yard algorithm.
$output = array();
$stack = array();
while ( $pos < $len ) {
$next = substr( $str, $pos, 1 );
switch ( $next ) {
// Ignore whitespace.
case ' ':
case "\t":
$pos++;
break;
// Variable (n).
case 'n':
$output[] = array( 'var' );
$pos++;
break;
// Parentheses.
case '(':
$stack[] = $next;
$pos++;
break;
case ')':
$found = false;
while ( ! empty( $stack ) ) {
$o2 = $stack[ count( $stack ) - 1 ];
if ( '(' !== $o2 ) {
$output[] = array( 'op', array_pop( $stack ) );
continue;
}
// Discard open paren.
array_pop( $stack );
$found = true;
break;
}
if ( ! $found ) {
throw new Exception( 'Mismatched parentheses' );
}
$pos++;
break;
// Operators.
case '|':
case '&':
case '>':
case '<':
case '!':
case '=':
case '%':
case '?':
$end_operator = strspn( $str, self::OP_CHARS, $pos );
$operator = substr( $str, $pos, $end_operator );
if ( ! array_key_exists( $operator, self::$op_precedence ) ) {
throw new Exception( sprintf( 'Unknown operator "%s"', $operator ) );
}
while ( ! empty( $stack ) ) {
$o2 = $stack[ count( $stack ) - 1 ];
// Ternary is right-associative in C.
if ( '?:' === $operator || '?' === $operator ) {
if ( self::$op_precedence[ $operator ] >= self::$op_precedence[ $o2 ] ) {
break;
}
} elseif ( self::$op_precedence[ $operator ] > self::$op_precedence[ $o2 ] ) {
break;
}
$output[] = array( 'op', array_pop( $stack ) );
}
$stack[] = $operator;
$pos += $end_operator;
break;
// Ternary "else".
case ':':
$found = false;
$s_pos = count( $stack ) - 1;
while ( $s_pos >= 0 ) {
$o2 = $stack[ $s_pos ];
if ( '?' !== $o2 ) {
$output[] = array( 'op', array_pop( $stack ) );
$s_pos--;
continue;
}
// Replace.
$stack[ $s_pos ] = '?:';
$found = true;
break;
}
if ( ! $found ) {
throw new Exception( 'Missing starting "?" ternary operator' );
}
$pos++;
break;
// Default - number or invalid.
default:
if ( $next >= '0' && $next <= '9' ) {
$span = strspn( $str, self::NUM_CHARS, $pos );
$output[] = array( 'value', intval( substr( $str, $pos, $span ) ) );
$pos += $span;
break;
}
throw new Exception( sprintf( 'Unknown symbol "%s"', $next ) );
}
}
while ( ! empty( $stack ) ) {
$o2 = array_pop( $stack );
if ( '(' === $o2 || ')' === $o2 ) {
throw new Exception( 'Mismatched parentheses' );
}
$output[] = array( 'op', $o2 );
}
$this->tokens = $output;
}
/**
* Get the plural form for a number.
*
* Caches the value for repeated calls.
*
* @since 4.9.0
*
* @param int $num Number to get plural form for.
* @return int Plural form value.
*/
public function get( $num ) {
if ( isset( $this->cache[ $num ] ) ) {
return $this->cache[ $num ];
}
$this->cache[ $num ] = $this->execute( $num );
return $this->cache[ $num ];
}
/**
* Execute the plural form function.
*
* @since 4.9.0
*
* @throws Exception If the plural form value cannot be calculated.
*
* @param int $n Variable "n" to substitute.
* @return int Plural form value.
*/
public function execute( $n ) {
$stack = array();
$i = 0;
$total = count( $this->tokens );
while ( $i < $total ) {
$next = $this->tokens[ $i ];
$i++;
if ( 'var' === $next[0] ) {
$stack[] = $n;
continue;
} elseif ( 'value' === $next[0] ) {
$stack[] = $next[1];
continue;
}
// Only operators left.
switch ( $next[1] ) {
case '%':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 % $v2;
break;
case '||':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 || $v2;
break;
case '&&':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 && $v2;
break;
case '<':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 < $v2;
break;
case '<=':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 <= $v2;
break;
case '>':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 > $v2;
break;
case '>=':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 >= $v2;
break;
case '!=':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 != $v2;
break;
case '==':
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 == $v2;
break;
case '?:':
$v3 = array_pop( $stack );
$v2 = array_pop( $stack );
$v1 = array_pop( $stack );
$stack[] = $v1 ? $v2 : $v3;
break;
default:
throw new Exception( sprintf( 'Unknown operator "%s"', $next[1] ) );
}
}
if ( count( $stack ) !== 1 ) {
throw new Exception( 'Too many values remaining on the stack' );
}
return (int) $stack[0];
}
}
```
| programming_docs |
wordpress class WP_Debug_Data {} class WP\_Debug\_Data {}
========================
Class for providing debug data based on a users WordPress environment.
* [check\_for\_updates](wp_debug_data/check_for_updates) — Calls all core functions to check for updates.
* [debug\_data](wp_debug_data/debug_data) — Static function for generating site debug data when required.
* [format](wp_debug_data/format) — Formats the information gathered for debugging, in a manner suitable for copying to a forum or support ticket.
* [get\_database\_size](wp_debug_data/get_database_size) — Fetches the total size of all the database tables for the active database user.
* [get\_mysql\_var](wp_debug_data/get_mysql_var) — Returns the value of a MySQL system variable.
* [get\_sizes](wp_debug_data/get_sizes) — Fetches the sizes of the WordPress directories: `wordpress` (ABSPATH), `plugins`, `themes`, and `uploads`.
File: `wp-admin/includes/class-wp-debug-data.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-debug-data.php/)
```
class WP_Debug_Data {
/**
* Calls all core functions to check for updates.
*
* @since 5.2.0
*/
public static function check_for_updates() {
wp_version_check();
wp_update_plugins();
wp_update_themes();
}
/**
* Static function for generating site debug data when required.
*
* @since 5.2.0
* @since 5.3.0 Added database charset, database collation,
* and timezone information.
* @since 5.5.0 Added pretty permalinks support information.
*
* @throws ImagickException
* @global wpdb $wpdb WordPress database abstraction object.
*
* @return array The debug data for the site.
*/
public static function debug_data() {
global $wpdb;
// Save few function calls.
$upload_dir = wp_upload_dir();
$permalink_structure = get_option( 'permalink_structure' );
$is_ssl = is_ssl();
$is_multisite = is_multisite();
$users_can_register = get_option( 'users_can_register' );
$blog_public = get_option( 'blog_public' );
$default_comment_status = get_option( 'default_comment_status' );
$environment_type = wp_get_environment_type();
$core_version = get_bloginfo( 'version' );
$core_updates = get_core_updates();
$core_update_needed = '';
if ( is_array( $core_updates ) ) {
foreach ( $core_updates as $core => $update ) {
if ( 'upgrade' === $update->response ) {
/* translators: %s: Latest WordPress version number. */
$core_update_needed = ' ' . sprintf( __( '(Latest version: %s)' ), $update->version );
} else {
$core_update_needed = '';
}
}
}
// Set up the array that holds all debug information.
$info = array();
$info['wp-core'] = array(
'label' => __( 'WordPress' ),
'fields' => array(
'version' => array(
'label' => __( 'Version' ),
'value' => $core_version . $core_update_needed,
'debug' => $core_version,
),
'site_language' => array(
'label' => __( 'Site Language' ),
'value' => get_locale(),
),
'user_language' => array(
'label' => __( 'User Language' ),
'value' => get_user_locale(),
),
'timezone' => array(
'label' => __( 'Timezone' ),
'value' => wp_timezone_string(),
),
'home_url' => array(
'label' => __( 'Home URL' ),
'value' => get_bloginfo( 'url' ),
'private' => true,
),
'site_url' => array(
'label' => __( 'Site URL' ),
'value' => get_bloginfo( 'wpurl' ),
'private' => true,
),
'permalink' => array(
'label' => __( 'Permalink structure' ),
'value' => $permalink_structure ? $permalink_structure : __( 'No permalink structure set' ),
'debug' => $permalink_structure,
),
'https_status' => array(
'label' => __( 'Is this site using HTTPS?' ),
'value' => $is_ssl ? __( 'Yes' ) : __( 'No' ),
'debug' => $is_ssl,
),
'multisite' => array(
'label' => __( 'Is this a multisite?' ),
'value' => $is_multisite ? __( 'Yes' ) : __( 'No' ),
'debug' => $is_multisite,
),
'user_registration' => array(
'label' => __( 'Can anyone register on this site?' ),
'value' => $users_can_register ? __( 'Yes' ) : __( 'No' ),
'debug' => $users_can_register,
),
'blog_public' => array(
'label' => __( 'Is this site discouraging search engines?' ),
'value' => $blog_public ? __( 'No' ) : __( 'Yes' ),
'debug' => $blog_public,
),
'default_comment_status' => array(
'label' => __( 'Default comment status' ),
'value' => 'open' === $default_comment_status ? _x( 'Open', 'comment status' ) : _x( 'Closed', 'comment status' ),
'debug' => $default_comment_status,
),
'environment_type' => array(
'label' => __( 'Environment type' ),
'value' => $environment_type,
'debug' => $environment_type,
),
),
);
if ( ! $is_multisite ) {
$info['wp-paths-sizes'] = array(
'label' => __( 'Directories and Sizes' ),
'fields' => array(),
);
}
$info['wp-dropins'] = array(
'label' => __( 'Drop-ins' ),
'show_count' => true,
'description' => 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>'
),
'fields' => array(),
);
$info['wp-active-theme'] = array(
'label' => __( 'Active Theme' ),
'fields' => array(),
);
$info['wp-parent-theme'] = array(
'label' => __( 'Parent Theme' ),
'fields' => array(),
);
$info['wp-themes-inactive'] = array(
'label' => __( 'Inactive Themes' ),
'show_count' => true,
'fields' => array(),
);
$info['wp-mu-plugins'] = array(
'label' => __( 'Must Use Plugins' ),
'show_count' => true,
'fields' => array(),
);
$info['wp-plugins-active'] = array(
'label' => __( 'Active Plugins' ),
'show_count' => true,
'fields' => array(),
);
$info['wp-plugins-inactive'] = array(
'label' => __( 'Inactive Plugins' ),
'show_count' => true,
'fields' => array(),
);
$info['wp-media'] = array(
'label' => __( 'Media Handling' ),
'fields' => array(),
);
$info['wp-server'] = array(
'label' => __( 'Server' ),
'description' => __( 'The options shown below relate to your server setup. If changes are required, you may need your web host’s assistance.' ),
'fields' => array(),
);
$info['wp-database'] = array(
'label' => __( 'Database' ),
'fields' => array(),
);
// Check if WP_DEBUG_LOG is set.
$wp_debug_log_value = __( 'Disabled' );
if ( is_string( WP_DEBUG_LOG ) ) {
$wp_debug_log_value = WP_DEBUG_LOG;
} elseif ( WP_DEBUG_LOG ) {
$wp_debug_log_value = __( 'Enabled' );
}
// Check CONCATENATE_SCRIPTS.
if ( defined( 'CONCATENATE_SCRIPTS' ) ) {
$concatenate_scripts = CONCATENATE_SCRIPTS ? __( 'Enabled' ) : __( 'Disabled' );
$concatenate_scripts_debug = CONCATENATE_SCRIPTS ? 'true' : 'false';
} else {
$concatenate_scripts = __( 'Undefined' );
$concatenate_scripts_debug = 'undefined';
}
// Check COMPRESS_SCRIPTS.
if ( defined( 'COMPRESS_SCRIPTS' ) ) {
$compress_scripts = COMPRESS_SCRIPTS ? __( 'Enabled' ) : __( 'Disabled' );
$compress_scripts_debug = COMPRESS_SCRIPTS ? 'true' : 'false';
} else {
$compress_scripts = __( 'Undefined' );
$compress_scripts_debug = 'undefined';
}
// Check COMPRESS_CSS.
if ( defined( 'COMPRESS_CSS' ) ) {
$compress_css = COMPRESS_CSS ? __( 'Enabled' ) : __( 'Disabled' );
$compress_css_debug = COMPRESS_CSS ? 'true' : 'false';
} else {
$compress_css = __( 'Undefined' );
$compress_css_debug = 'undefined';
}
// Check WP_ENVIRONMENT_TYPE.
if ( defined( 'WP_ENVIRONMENT_TYPE' ) && WP_ENVIRONMENT_TYPE ) {
$wp_environment_type = WP_ENVIRONMENT_TYPE;
} else {
$wp_environment_type = __( 'Undefined' );
}
$info['wp-constants'] = array(
'label' => __( 'WordPress Constants' ),
'description' => __( 'These settings alter where and how parts of WordPress are loaded.' ),
'fields' => array(
'ABSPATH' => array(
'label' => 'ABSPATH',
'value' => ABSPATH,
'private' => true,
),
'WP_HOME' => array(
'label' => 'WP_HOME',
'value' => ( defined( 'WP_HOME' ) ? WP_HOME : __( 'Undefined' ) ),
'debug' => ( defined( 'WP_HOME' ) ? WP_HOME : 'undefined' ),
),
'WP_SITEURL' => array(
'label' => 'WP_SITEURL',
'value' => ( defined( 'WP_SITEURL' ) ? WP_SITEURL : __( 'Undefined' ) ),
'debug' => ( defined( 'WP_SITEURL' ) ? WP_SITEURL : 'undefined' ),
),
'WP_CONTENT_DIR' => array(
'label' => 'WP_CONTENT_DIR',
'value' => WP_CONTENT_DIR,
),
'WP_PLUGIN_DIR' => array(
'label' => 'WP_PLUGIN_DIR',
'value' => WP_PLUGIN_DIR,
),
'WP_MEMORY_LIMIT' => array(
'label' => 'WP_MEMORY_LIMIT',
'value' => WP_MEMORY_LIMIT,
),
'WP_MAX_MEMORY_LIMIT' => array(
'label' => 'WP_MAX_MEMORY_LIMIT',
'value' => WP_MAX_MEMORY_LIMIT,
),
'WP_DEBUG' => array(
'label' => 'WP_DEBUG',
'value' => WP_DEBUG ? __( 'Enabled' ) : __( 'Disabled' ),
'debug' => WP_DEBUG,
),
'WP_DEBUG_DISPLAY' => array(
'label' => 'WP_DEBUG_DISPLAY',
'value' => WP_DEBUG_DISPLAY ? __( 'Enabled' ) : __( 'Disabled' ),
'debug' => WP_DEBUG_DISPLAY,
),
'WP_DEBUG_LOG' => array(
'label' => 'WP_DEBUG_LOG',
'value' => $wp_debug_log_value,
'debug' => WP_DEBUG_LOG,
),
'SCRIPT_DEBUG' => array(
'label' => 'SCRIPT_DEBUG',
'value' => SCRIPT_DEBUG ? __( 'Enabled' ) : __( 'Disabled' ),
'debug' => SCRIPT_DEBUG,
),
'WP_CACHE' => array(
'label' => 'WP_CACHE',
'value' => WP_CACHE ? __( 'Enabled' ) : __( 'Disabled' ),
'debug' => WP_CACHE,
),
'CONCATENATE_SCRIPTS' => array(
'label' => 'CONCATENATE_SCRIPTS',
'value' => $concatenate_scripts,
'debug' => $concatenate_scripts_debug,
),
'COMPRESS_SCRIPTS' => array(
'label' => 'COMPRESS_SCRIPTS',
'value' => $compress_scripts,
'debug' => $compress_scripts_debug,
),
'COMPRESS_CSS' => array(
'label' => 'COMPRESS_CSS',
'value' => $compress_css,
'debug' => $compress_css_debug,
),
'WP_ENVIRONMENT_TYPE' => array(
'label' => 'WP_ENVIRONMENT_TYPE',
'value' => $wp_environment_type,
'debug' => $wp_environment_type,
),
'DB_CHARSET' => array(
'label' => 'DB_CHARSET',
'value' => ( defined( 'DB_CHARSET' ) ? DB_CHARSET : __( 'Undefined' ) ),
'debug' => ( defined( 'DB_CHARSET' ) ? DB_CHARSET : 'undefined' ),
),
'DB_COLLATE' => array(
'label' => 'DB_COLLATE',
'value' => ( defined( 'DB_COLLATE' ) ? DB_COLLATE : __( 'Undefined' ) ),
'debug' => ( defined( 'DB_COLLATE' ) ? DB_COLLATE : 'undefined' ),
),
),
);
$is_writable_abspath = wp_is_writable( ABSPATH );
$is_writable_wp_content_dir = wp_is_writable( WP_CONTENT_DIR );
$is_writable_upload_dir = wp_is_writable( $upload_dir['basedir'] );
$is_writable_wp_plugin_dir = wp_is_writable( WP_PLUGIN_DIR );
$is_writable_template_directory = wp_is_writable( get_theme_root( get_template() ) );
$info['wp-filesystem'] = array(
'label' => __( 'Filesystem Permissions' ),
'description' => __( 'Shows whether WordPress is able to write to the directories it needs access to.' ),
'fields' => array(
'wordpress' => array(
'label' => __( 'The main WordPress directory' ),
'value' => ( $is_writable_abspath ? __( 'Writable' ) : __( 'Not writable' ) ),
'debug' => ( $is_writable_abspath ? 'writable' : 'not writable' ),
),
'wp-content' => array(
'label' => __( 'The wp-content directory' ),
'value' => ( $is_writable_wp_content_dir ? __( 'Writable' ) : __( 'Not writable' ) ),
'debug' => ( $is_writable_wp_content_dir ? 'writable' : 'not writable' ),
),
'uploads' => array(
'label' => __( 'The uploads directory' ),
'value' => ( $is_writable_upload_dir ? __( 'Writable' ) : __( 'Not writable' ) ),
'debug' => ( $is_writable_upload_dir ? 'writable' : 'not writable' ),
),
'plugins' => array(
'label' => __( 'The plugins directory' ),
'value' => ( $is_writable_wp_plugin_dir ? __( 'Writable' ) : __( 'Not writable' ) ),
'debug' => ( $is_writable_wp_plugin_dir ? 'writable' : 'not writable' ),
),
'themes' => array(
'label' => __( 'The themes directory' ),
'value' => ( $is_writable_template_directory ? __( 'Writable' ) : __( 'Not writable' ) ),
'debug' => ( $is_writable_template_directory ? 'writable' : 'not writable' ),
),
),
);
// Conditionally add debug information for multisite setups.
if ( is_multisite() ) {
$network_query = new WP_Network_Query();
$network_ids = $network_query->query(
array(
'fields' => 'ids',
'number' => 100,
'no_found_rows' => false,
)
);
$site_count = 0;
foreach ( $network_ids as $network_id ) {
$site_count += get_blog_count( $network_id );
}
$info['wp-core']['fields']['site_count'] = array(
'label' => __( 'Site count' ),
'value' => $site_count,
);
$info['wp-core']['fields']['network_count'] = array(
'label' => __( 'Network count' ),
'value' => $network_query->found_networks,
);
}
$info['wp-core']['fields']['user_count'] = array(
'label' => __( 'User count' ),
'value' => get_user_count(),
);
// WordPress features requiring processing.
$wp_dotorg = wp_remote_get( 'https://wordpress.org', array( 'timeout' => 10 ) );
if ( ! is_wp_error( $wp_dotorg ) ) {
$info['wp-core']['fields']['dotorg_communication'] = array(
'label' => __( 'Communication with WordPress.org' ),
'value' => __( 'WordPress.org is reachable' ),
'debug' => 'true',
);
} else {
$info['wp-core']['fields']['dotorg_communication'] = array(
'label' => __( 'Communication with WordPress.org' ),
'value' => sprintf(
/* translators: 1: The IP address WordPress.org resolves to. 2: The error returned by the lookup. */
__( 'Unable to reach WordPress.org at %1$s: %2$s' ),
gethostbyname( 'wordpress.org' ),
$wp_dotorg->get_error_message()
),
'debug' => $wp_dotorg->get_error_message(),
);
}
// Remove accordion for Directories and Sizes if in Multisite.
if ( ! $is_multisite ) {
$loading = __( 'Loading…' );
$info['wp-paths-sizes']['fields'] = array(
'wordpress_path' => array(
'label' => __( 'WordPress directory location' ),
'value' => untrailingslashit( ABSPATH ),
),
'wordpress_size' => array(
'label' => __( 'WordPress directory size' ),
'value' => $loading,
'debug' => 'loading...',
),
'uploads_path' => array(
'label' => __( 'Uploads directory location' ),
'value' => $upload_dir['basedir'],
),
'uploads_size' => array(
'label' => __( 'Uploads directory size' ),
'value' => $loading,
'debug' => 'loading...',
),
'themes_path' => array(
'label' => __( 'Themes directory location' ),
'value' => get_theme_root(),
),
'themes_size' => array(
'label' => __( 'Themes directory size' ),
'value' => $loading,
'debug' => 'loading...',
),
'plugins_path' => array(
'label' => __( 'Plugins directory location' ),
'value' => WP_PLUGIN_DIR,
),
'plugins_size' => array(
'label' => __( 'Plugins directory size' ),
'value' => $loading,
'debug' => 'loading...',
),
'database_size' => array(
'label' => __( 'Database size' ),
'value' => $loading,
'debug' => 'loading...',
),
'total_size' => array(
'label' => __( 'Total installation size' ),
'value' => $loading,
'debug' => 'loading...',
),
);
}
// Get a list of all drop-in replacements.
$dropins = get_dropins();
// Get dropins descriptions.
$dropin_descriptions = _get_dropins();
// Spare few function calls.
$not_available = __( 'Not available' );
foreach ( $dropins as $dropin_key => $dropin ) {
$info['wp-dropins']['fields'][ sanitize_text_field( $dropin_key ) ] = array(
'label' => $dropin_key,
'value' => $dropin_descriptions[ $dropin_key ][0],
'debug' => 'true',
);
}
// Populate the media fields.
$info['wp-media']['fields']['image_editor'] = array(
'label' => __( 'Active editor' ),
'value' => _wp_image_editor_choose(),
);
// Get ImageMagic information, if available.
if ( class_exists( 'Imagick' ) ) {
// Save the Imagick instance for later use.
$imagick = new Imagick();
$imagemagick_version = $imagick->getVersion();
} else {
$imagemagick_version = __( 'Not available' );
}
$info['wp-media']['fields']['imagick_module_version'] = array(
'label' => __( 'ImageMagick version number' ),
'value' => ( is_array( $imagemagick_version ) ? $imagemagick_version['versionNumber'] : $imagemagick_version ),
);
$info['wp-media']['fields']['imagemagick_version'] = array(
'label' => __( 'ImageMagick version string' ),
'value' => ( is_array( $imagemagick_version ) ? $imagemagick_version['versionString'] : $imagemagick_version ),
);
$imagick_version = phpversion( 'imagick' );
$info['wp-media']['fields']['imagick_version'] = array(
'label' => __( 'Imagick version' ),
'value' => ( $imagick_version ) ? $imagick_version : __( 'Not available' ),
);
if ( ! function_exists( 'ini_get' ) ) {
$info['wp-media']['fields']['ini_get'] = array(
'label' => __( 'File upload settings' ),
'value' => sprintf(
/* translators: %s: ini_get() */
__( 'Unable to determine some settings, as the %s function has been disabled.' ),
'ini_get()'
),
'debug' => 'ini_get() is disabled',
);
} else {
// Get the PHP ini directive values.
$post_max_size = ini_get( 'post_max_size' );
$upload_max_filesize = ini_get( 'upload_max_filesize' );
$max_file_uploads = ini_get( 'max_file_uploads' );
$effective = min( wp_convert_hr_to_bytes( $post_max_size ), wp_convert_hr_to_bytes( $upload_max_filesize ) );
// Add info in Media section.
$info['wp-media']['fields']['file_uploads'] = array(
'label' => __( 'File uploads' ),
'value' => empty( ini_get( 'file_uploads' ) ) ? __( 'Disabled' ) : __( 'Enabled' ),
'debug' => 'File uploads is turned off',
);
$info['wp-media']['fields']['post_max_size'] = array(
'label' => __( 'Max size of post data allowed' ),
'value' => $post_max_size,
);
$info['wp-media']['fields']['upload_max_filesize'] = array(
'label' => __( 'Max size of an uploaded file' ),
'value' => $upload_max_filesize,
);
$info['wp-media']['fields']['max_effective_size'] = array(
'label' => __( 'Max effective file size' ),
'value' => size_format( $effective ),
);
$info['wp-media']['fields']['max_file_uploads'] = array(
'label' => __( 'Max number of files allowed' ),
'value' => number_format( $max_file_uploads ),
);
}
// If Imagick is used as our editor, provide some more information about its limitations.
if ( 'WP_Image_Editor_Imagick' === _wp_image_editor_choose() && isset( $imagick ) && $imagick instanceof Imagick ) {
$limits = array(
'area' => ( defined( 'imagick::RESOURCETYPE_AREA' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_AREA ) ) : $not_available ),
'disk' => ( defined( 'imagick::RESOURCETYPE_DISK' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_DISK ) : $not_available ),
'file' => ( defined( 'imagick::RESOURCETYPE_FILE' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_FILE ) : $not_available ),
'map' => ( defined( 'imagick::RESOURCETYPE_MAP' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_MAP ) ) : $not_available ),
'memory' => ( defined( 'imagick::RESOURCETYPE_MEMORY' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_MEMORY ) ) : $not_available ),
'thread' => ( defined( 'imagick::RESOURCETYPE_THREAD' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_THREAD ) : $not_available ),
);
$limits_debug = array(
'imagick::RESOURCETYPE_AREA' => ( defined( 'imagick::RESOURCETYPE_AREA' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_AREA ) ) : 'not available' ),
'imagick::RESOURCETYPE_DISK' => ( defined( 'imagick::RESOURCETYPE_DISK' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_DISK ) : 'not available' ),
'imagick::RESOURCETYPE_FILE' => ( defined( 'imagick::RESOURCETYPE_FILE' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_FILE ) : 'not available' ),
'imagick::RESOURCETYPE_MAP' => ( defined( 'imagick::RESOURCETYPE_MAP' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_MAP ) ) : 'not available' ),
'imagick::RESOURCETYPE_MEMORY' => ( defined( 'imagick::RESOURCETYPE_MEMORY' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_MEMORY ) ) : 'not available' ),
'imagick::RESOURCETYPE_THREAD' => ( defined( 'imagick::RESOURCETYPE_THREAD' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_THREAD ) : 'not available' ),
);
$info['wp-media']['fields']['imagick_limits'] = array(
'label' => __( 'Imagick Resource Limits' ),
'value' => $limits,
'debug' => $limits_debug,
);
try {
$formats = Imagick::queryFormats( '*' );
} catch ( Exception $e ) {
$formats = array();
}
$info['wp-media']['fields']['imagemagick_file_formats'] = array(
'label' => __( 'ImageMagick supported file formats' ),
'value' => ( empty( $formats ) ) ? __( 'Unable to determine' ) : implode( ', ', $formats ),
'debug' => ( empty( $formats ) ) ? 'Unable to determine' : implode( ', ', $formats ),
);
}
// Get GD information, if available.
if ( function_exists( 'gd_info' ) ) {
$gd = gd_info();
} else {
$gd = false;
}
$info['wp-media']['fields']['gd_version'] = array(
'label' => __( 'GD version' ),
'value' => ( is_array( $gd ) ? $gd['GD Version'] : $not_available ),
'debug' => ( is_array( $gd ) ? $gd['GD Version'] : 'not available' ),
);
$gd_image_formats = array();
$gd_supported_formats = array(
'GIF Create' => 'GIF',
'JPEG' => 'JPEG',
'PNG' => 'PNG',
'WebP' => 'WebP',
'BMP' => 'BMP',
'AVIF' => 'AVIF',
'HEIF' => 'HEIF',
'TIFF' => 'TIFF',
'XPM' => 'XPM',
);
foreach ( $gd_supported_formats as $format_key => $format ) {
$index = $format_key . ' Support';
if ( isset( $gd[ $index ] ) && $gd[ $index ] ) {
array_push( $gd_image_formats, $format );
}
}
if ( ! empty( $gd_image_formats ) ) {
$info['wp-media']['fields']['gd_formats'] = array(
'label' => __( 'GD supported file formats' ),
'value' => implode( ', ', $gd_image_formats ),
);
}
// Get Ghostscript information, if available.
if ( function_exists( 'exec' ) ) {
$gs = exec( 'gs --version' );
if ( empty( $gs ) ) {
$gs = $not_available;
$gs_debug = 'not available';
} else {
$gs_debug = $gs;
}
} else {
$gs = __( 'Unable to determine if Ghostscript is installed' );
$gs_debug = 'unknown';
}
$info['wp-media']['fields']['ghostscript_version'] = array(
'label' => __( 'Ghostscript version' ),
'value' => $gs,
'debug' => $gs_debug,
);
// Populate the server debug fields.
if ( function_exists( 'php_uname' ) ) {
$server_architecture = sprintf( '%s %s %s', php_uname( 's' ), php_uname( 'r' ), php_uname( 'm' ) );
} else {
$server_architecture = 'unknown';
}
$php_version_debug = PHP_VERSION;
// Whether PHP supports 64-bit.
$php64bit = ( PHP_INT_SIZE * 8 === 64 );
$php_version = sprintf(
'%s %s',
$php_version_debug,
( $php64bit ? __( '(Supports 64bit values)' ) : __( '(Does not support 64bit values)' ) )
);
if ( $php64bit ) {
$php_version_debug .= ' 64bit';
}
if ( function_exists( 'php_sapi_name' ) ) {
$php_sapi = php_sapi_name();
} else {
$php_sapi = 'unknown';
}
$info['wp-server']['fields']['server_architecture'] = array(
'label' => __( 'Server architecture' ),
'value' => ( 'unknown' !== $server_architecture ? $server_architecture : __( 'Unable to determine server architecture' ) ),
'debug' => $server_architecture,
);
$info['wp-server']['fields']['httpd_software'] = array(
'label' => __( 'Web server' ),
'value' => ( isset( $_SERVER['SERVER_SOFTWARE'] ) ? $_SERVER['SERVER_SOFTWARE'] : __( 'Unable to determine what web server software is used' ) ),
'debug' => ( isset( $_SERVER['SERVER_SOFTWARE'] ) ? $_SERVER['SERVER_SOFTWARE'] : 'unknown' ),
);
$info['wp-server']['fields']['php_version'] = array(
'label' => __( 'PHP version' ),
'value' => $php_version,
'debug' => $php_version_debug,
);
$info['wp-server']['fields']['php_sapi'] = array(
'label' => __( 'PHP SAPI' ),
'value' => ( 'unknown' !== $php_sapi ? $php_sapi : __( 'Unable to determine PHP SAPI' ) ),
'debug' => $php_sapi,
);
// Some servers disable `ini_set()` and `ini_get()`, we check this before trying to get configuration values.
if ( ! function_exists( 'ini_get' ) ) {
$info['wp-server']['fields']['ini_get'] = array(
'label' => __( 'Server settings' ),
'value' => sprintf(
/* translators: %s: ini_get() */
__( 'Unable to determine some settings, as the %s function has been disabled.' ),
'ini_get()'
),
'debug' => 'ini_get() is disabled',
);
} else {
$info['wp-server']['fields']['max_input_variables'] = array(
'label' => __( 'PHP max input variables' ),
'value' => ini_get( 'max_input_vars' ),
);
$info['wp-server']['fields']['time_limit'] = array(
'label' => __( 'PHP time limit' ),
'value' => ini_get( 'max_execution_time' ),
);
if ( WP_Site_Health::get_instance()->php_memory_limit !== ini_get( 'memory_limit' ) ) {
$info['wp-server']['fields']['memory_limit'] = array(
'label' => __( 'PHP memory limit' ),
'value' => WP_Site_Health::get_instance()->php_memory_limit,
);
$info['wp-server']['fields']['admin_memory_limit'] = array(
'label' => __( 'PHP memory limit (only for admin screens)' ),
'value' => ini_get( 'memory_limit' ),
);
} else {
$info['wp-server']['fields']['memory_limit'] = array(
'label' => __( 'PHP memory limit' ),
'value' => ini_get( 'memory_limit' ),
);
}
$info['wp-server']['fields']['max_input_time'] = array(
'label' => __( 'Max input time' ),
'value' => ini_get( 'max_input_time' ),
);
$info['wp-server']['fields']['upload_max_filesize'] = array(
'label' => __( 'Upload max filesize' ),
'value' => ini_get( 'upload_max_filesize' ),
);
$info['wp-server']['fields']['php_post_max_size'] = array(
'label' => __( 'PHP post max size' ),
'value' => ini_get( 'post_max_size' ),
);
}
if ( function_exists( 'curl_version' ) ) {
$curl = curl_version();
$info['wp-server']['fields']['curl_version'] = array(
'label' => __( 'cURL version' ),
'value' => sprintf( '%s %s', $curl['version'], $curl['ssl_version'] ),
);
} else {
$info['wp-server']['fields']['curl_version'] = array(
'label' => __( 'cURL version' ),
'value' => $not_available,
'debug' => 'not available',
);
}
// SUHOSIN.
$suhosin_loaded = ( extension_loaded( 'suhosin' ) || ( defined( 'SUHOSIN_PATCH' ) && constant( 'SUHOSIN_PATCH' ) ) );
$info['wp-server']['fields']['suhosin'] = array(
'label' => __( 'Is SUHOSIN installed?' ),
'value' => ( $suhosin_loaded ? __( 'Yes' ) : __( 'No' ) ),
'debug' => $suhosin_loaded,
);
// Imagick.
$imagick_loaded = extension_loaded( 'imagick' );
$info['wp-server']['fields']['imagick_availability'] = array(
'label' => __( 'Is the Imagick library available?' ),
'value' => ( $imagick_loaded ? __( 'Yes' ) : __( 'No' ) ),
'debug' => $imagick_loaded,
);
// Pretty permalinks.
$pretty_permalinks_supported = got_url_rewrite();
$info['wp-server']['fields']['pretty_permalinks'] = array(
'label' => __( 'Are pretty permalinks supported?' ),
'value' => ( $pretty_permalinks_supported ? __( 'Yes' ) : __( 'No' ) ),
'debug' => $pretty_permalinks_supported,
);
// Check if a .htaccess file exists.
if ( is_file( ABSPATH . '.htaccess' ) ) {
// If the file exists, grab the content of it.
$htaccess_content = file_get_contents( ABSPATH . '.htaccess' );
// Filter away the core WordPress rules.
$filtered_htaccess_content = trim( preg_replace( '/\# BEGIN WordPress[\s\S]+?# END WordPress/si', '', $htaccess_content ) );
$filtered_htaccess_content = ! empty( $filtered_htaccess_content );
if ( $filtered_htaccess_content ) {
/* translators: %s: .htaccess */
$htaccess_rules_string = sprintf( __( 'Custom rules have been added to your %s file.' ), '.htaccess' );
} else {
/* translators: %s: .htaccess */
$htaccess_rules_string = sprintf( __( 'Your %s file contains only core WordPress features.' ), '.htaccess' );
}
$info['wp-server']['fields']['htaccess_extra_rules'] = array(
'label' => __( '.htaccess rules' ),
'value' => $htaccess_rules_string,
'debug' => $filtered_htaccess_content,
);
}
// Populate the database debug fields.
if ( is_resource( $wpdb->dbh ) ) {
// Old mysql extension.
$extension = 'mysql';
} elseif ( is_object( $wpdb->dbh ) ) {
// mysqli or PDO.
$extension = get_class( $wpdb->dbh );
} else {
// Unknown sql extension.
$extension = null;
}
$server = $wpdb->get_var( 'SELECT VERSION()' );
if ( isset( $wpdb->use_mysqli ) && $wpdb->use_mysqli ) {
$client_version = $wpdb->dbh->client_info;
} else {
// phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysql_get_client_info,PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved
if ( preg_match( '|[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}|', mysql_get_client_info(), $matches ) ) {
$client_version = $matches[0];
} else {
$client_version = null;
}
}
$info['wp-database']['fields']['extension'] = array(
'label' => __( 'Extension' ),
'value' => $extension,
);
$info['wp-database']['fields']['server_version'] = array(
'label' => __( 'Server version' ),
'value' => $server,
);
$info['wp-database']['fields']['client_version'] = array(
'label' => __( 'Client version' ),
'value' => $client_version,
);
$info['wp-database']['fields']['database_user'] = array(
'label' => __( 'Database username' ),
'value' => $wpdb->dbuser,
'private' => true,
);
$info['wp-database']['fields']['database_host'] = array(
'label' => __( 'Database host' ),
'value' => $wpdb->dbhost,
'private' => true,
);
$info['wp-database']['fields']['database_name'] = array(
'label' => __( 'Database name' ),
'value' => $wpdb->dbname,
'private' => true,
);
$info['wp-database']['fields']['database_prefix'] = array(
'label' => __( 'Table prefix' ),
'value' => $wpdb->prefix,
'private' => true,
);
$info['wp-database']['fields']['database_charset'] = array(
'label' => __( 'Database charset' ),
'value' => $wpdb->charset,
'private' => true,
);
$info['wp-database']['fields']['database_collate'] = array(
'label' => __( 'Database collation' ),
'value' => $wpdb->collate,
'private' => true,
);
$info['wp-database']['fields']['max_allowed_packet'] = array(
'label' => __( 'Max allowed packet size' ),
'value' => self::get_mysql_var( 'max_allowed_packet' ),
);
$info['wp-database']['fields']['max_connections'] = array(
'label' => __( 'Max connections number' ),
'value' => self::get_mysql_var( 'max_connections' ),
);
// List must use plugins if there are any.
$mu_plugins = get_mu_plugins();
foreach ( $mu_plugins as $plugin_path => $plugin ) {
$plugin_version = $plugin['Version'];
$plugin_author = $plugin['Author'];
$plugin_version_string = __( 'No version or author information is available.' );
$plugin_version_string_debug = 'author: (undefined), version: (undefined)';
if ( ! empty( $plugin_version ) && ! empty( $plugin_author ) ) {
/* translators: 1: Plugin version number. 2: Plugin author name. */
$plugin_version_string = sprintf( __( 'Version %1$s by %2$s' ), $plugin_version, $plugin_author );
$plugin_version_string_debug = sprintf( 'version: %s, author: %s', $plugin_version, $plugin_author );
} else {
if ( ! empty( $plugin_author ) ) {
/* translators: %s: Plugin author name. */
$plugin_version_string = sprintf( __( 'By %s' ), $plugin_author );
$plugin_version_string_debug = sprintf( 'author: %s, version: (undefined)', $plugin_author );
}
if ( ! empty( $plugin_version ) ) {
/* translators: %s: Plugin version number. */
$plugin_version_string = sprintf( __( 'Version %s' ), $plugin_version );
$plugin_version_string_debug = sprintf( 'author: (undefined), version: %s', $plugin_version );
}
}
$info['wp-mu-plugins']['fields'][ sanitize_text_field( $plugin['Name'] ) ] = array(
'label' => $plugin['Name'],
'value' => $plugin_version_string,
'debug' => $plugin_version_string_debug,
);
}
// List all available plugins.
$plugins = get_plugins();
$plugin_updates = get_plugin_updates();
$transient = get_site_transient( 'update_plugins' );
$auto_updates = array();
$auto_updates_enabled = wp_is_auto_update_enabled_for_type( 'plugin' );
if ( $auto_updates_enabled ) {
$auto_updates = (array) get_site_option( 'auto_update_plugins', array() );
}
foreach ( $plugins as $plugin_path => $plugin ) {
$plugin_part = ( is_plugin_active( $plugin_path ) ) ? 'wp-plugins-active' : 'wp-plugins-inactive';
$plugin_version = $plugin['Version'];
$plugin_author = $plugin['Author'];
$plugin_version_string = __( 'No version or author information is available.' );
$plugin_version_string_debug = 'author: (undefined), version: (undefined)';
if ( ! empty( $plugin_version ) && ! empty( $plugin_author ) ) {
/* translators: 1: Plugin version number. 2: Plugin author name. */
$plugin_version_string = sprintf( __( 'Version %1$s by %2$s' ), $plugin_version, $plugin_author );
$plugin_version_string_debug = sprintf( 'version: %s, author: %s', $plugin_version, $plugin_author );
} else {
if ( ! empty( $plugin_author ) ) {
/* translators: %s: Plugin author name. */
$plugin_version_string = sprintf( __( 'By %s' ), $plugin_author );
$plugin_version_string_debug = sprintf( 'author: %s, version: (undefined)', $plugin_author );
}
if ( ! empty( $plugin_version ) ) {
/* translators: %s: Plugin version number. */
$plugin_version_string = sprintf( __( 'Version %s' ), $plugin_version );
$plugin_version_string_debug = sprintf( 'author: (undefined), version: %s', $plugin_version );
}
}
if ( array_key_exists( $plugin_path, $plugin_updates ) ) {
/* translators: %s: Latest plugin version number. */
$plugin_version_string .= ' ' . sprintf( __( '(Latest version: %s)' ), $plugin_updates[ $plugin_path ]->update->new_version );
$plugin_version_string_debug .= sprintf( ' (latest version: %s)', $plugin_updates[ $plugin_path ]->update->new_version );
}
if ( $auto_updates_enabled ) {
if ( isset( $transient->response[ $plugin_path ] ) ) {
$item = $transient->response[ $plugin_path ];
} elseif ( isset( $transient->no_update[ $plugin_path ] ) ) {
$item = $transient->no_update[ $plugin_path ];
} else {
$item = array(
'id' => $plugin_path,
'slug' => '',
'plugin' => $plugin_path,
'new_version' => '',
'url' => '',
'package' => '',
'icons' => array(),
'banners' => array(),
'banners_rtl' => array(),
'tested' => '',
'requires_php' => '',
'compatibility' => new stdClass(),
);
$item = wp_parse_args( $plugin, $item );
}
$auto_update_forced = wp_is_auto_update_forced_for_item( 'plugin', null, (object) $item );
if ( ! is_null( $auto_update_forced ) ) {
$enabled = $auto_update_forced;
} else {
$enabled = in_array( $plugin_path, $auto_updates, true );
}
if ( $enabled ) {
$auto_updates_string = __( 'Auto-updates enabled' );
} else {
$auto_updates_string = __( 'Auto-updates disabled' );
}
/**
* Filters the text string of the auto-updates setting for each plugin in the Site Health debug data.
*
* @since 5.5.0
*
* @param string $auto_updates_string The string output for the auto-updates column.
* @param string $plugin_path The path to the plugin file.
* @param array $plugin An array of plugin data.
* @param bool $enabled Whether auto-updates are enabled for this item.
*/
$auto_updates_string = apply_filters( 'plugin_auto_update_debug_string', $auto_updates_string, $plugin_path, $plugin, $enabled );
$plugin_version_string .= ' | ' . $auto_updates_string;
$plugin_version_string_debug .= ', ' . $auto_updates_string;
}
$info[ $plugin_part ]['fields'][ sanitize_text_field( $plugin['Name'] ) ] = array(
'label' => $plugin['Name'],
'value' => $plugin_version_string,
'debug' => $plugin_version_string_debug,
);
}
// Populate the section for the currently active theme.
global $_wp_theme_features;
$theme_features = array();
if ( ! empty( $_wp_theme_features ) ) {
foreach ( $_wp_theme_features as $feature => $options ) {
$theme_features[] = $feature;
}
}
$active_theme = wp_get_theme();
$theme_updates = get_theme_updates();
$transient = get_site_transient( 'update_themes' );
$active_theme_version = $active_theme->version;
$active_theme_version_debug = $active_theme_version;
$auto_updates = array();
$auto_updates_enabled = wp_is_auto_update_enabled_for_type( 'theme' );
if ( $auto_updates_enabled ) {
$auto_updates = (array) get_site_option( 'auto_update_themes', array() );
}
if ( array_key_exists( $active_theme->stylesheet, $theme_updates ) ) {
$theme_update_new_version = $theme_updates[ $active_theme->stylesheet ]->update['new_version'];
/* translators: %s: Latest theme version number. */
$active_theme_version .= ' ' . sprintf( __( '(Latest version: %s)' ), $theme_update_new_version );
$active_theme_version_debug .= sprintf( ' (latest version: %s)', $theme_update_new_version );
}
$active_theme_author_uri = $active_theme->display( 'AuthorURI' );
if ( $active_theme->parent_theme ) {
$active_theme_parent_theme = sprintf(
/* translators: 1: Theme name. 2: Theme slug. */
__( '%1$s (%2$s)' ),
$active_theme->parent_theme,
$active_theme->template
);
$active_theme_parent_theme_debug = sprintf(
'%s (%s)',
$active_theme->parent_theme,
$active_theme->template
);
} else {
$active_theme_parent_theme = __( 'None' );
$active_theme_parent_theme_debug = 'none';
}
$info['wp-active-theme']['fields'] = array(
'name' => array(
'label' => __( 'Name' ),
'value' => sprintf(
/* translators: 1: Theme name. 2: Theme slug. */
__( '%1$s (%2$s)' ),
$active_theme->name,
$active_theme->stylesheet
),
),
'version' => array(
'label' => __( 'Version' ),
'value' => $active_theme_version,
'debug' => $active_theme_version_debug,
),
'author' => array(
'label' => __( 'Author' ),
'value' => wp_kses( $active_theme->author, array() ),
),
'author_website' => array(
'label' => __( 'Author website' ),
'value' => ( $active_theme_author_uri ? $active_theme_author_uri : __( 'Undefined' ) ),
'debug' => ( $active_theme_author_uri ? $active_theme_author_uri : '(undefined)' ),
),
'parent_theme' => array(
'label' => __( 'Parent theme' ),
'value' => $active_theme_parent_theme,
'debug' => $active_theme_parent_theme_debug,
),
'theme_features' => array(
'label' => __( 'Theme features' ),
'value' => implode( ', ', $theme_features ),
),
'theme_path' => array(
'label' => __( 'Theme directory location' ),
'value' => get_stylesheet_directory(),
),
);
if ( $auto_updates_enabled ) {
if ( isset( $transient->response[ $active_theme->stylesheet ] ) ) {
$item = $transient->response[ $active_theme->stylesheet ];
} elseif ( isset( $transient->no_update[ $active_theme->stylesheet ] ) ) {
$item = $transient->no_update[ $active_theme->stylesheet ];
} else {
$item = array(
'theme' => $active_theme->stylesheet,
'new_version' => $active_theme->version,
'url' => '',
'package' => '',
'requires' => '',
'requires_php' => '',
);
}
$auto_update_forced = wp_is_auto_update_forced_for_item( 'theme', null, (object) $item );
if ( ! is_null( $auto_update_forced ) ) {
$enabled = $auto_update_forced;
} else {
$enabled = in_array( $active_theme->stylesheet, $auto_updates, true );
}
if ( $enabled ) {
$auto_updates_string = __( 'Enabled' );
} else {
$auto_updates_string = __( 'Disabled' );
}
/** This filter is documented in wp-admin/includes/class-wp-debug-data.php */
$auto_updates_string = apply_filters( 'theme_auto_update_debug_string', $auto_updates_string, $active_theme, $enabled );
$info['wp-active-theme']['fields']['auto_update'] = array(
'label' => __( 'Auto-updates' ),
'value' => $auto_updates_string,
'debug' => $auto_updates_string,
);
}
$parent_theme = $active_theme->parent();
if ( $parent_theme ) {
$parent_theme_version = $parent_theme->version;
$parent_theme_version_debug = $parent_theme_version;
if ( array_key_exists( $parent_theme->stylesheet, $theme_updates ) ) {
$parent_theme_update_new_version = $theme_updates[ $parent_theme->stylesheet ]->update['new_version'];
/* translators: %s: Latest theme version number. */
$parent_theme_version .= ' ' . sprintf( __( '(Latest version: %s)' ), $parent_theme_update_new_version );
$parent_theme_version_debug .= sprintf( ' (latest version: %s)', $parent_theme_update_new_version );
}
$parent_theme_author_uri = $parent_theme->display( 'AuthorURI' );
$info['wp-parent-theme']['fields'] = array(
'name' => array(
'label' => __( 'Name' ),
'value' => sprintf(
/* translators: 1: Theme name. 2: Theme slug. */
__( '%1$s (%2$s)' ),
$parent_theme->name,
$parent_theme->stylesheet
),
),
'version' => array(
'label' => __( 'Version' ),
'value' => $parent_theme_version,
'debug' => $parent_theme_version_debug,
),
'author' => array(
'label' => __( 'Author' ),
'value' => wp_kses( $parent_theme->author, array() ),
),
'author_website' => array(
'label' => __( 'Author website' ),
'value' => ( $parent_theme_author_uri ? $parent_theme_author_uri : __( 'Undefined' ) ),
'debug' => ( $parent_theme_author_uri ? $parent_theme_author_uri : '(undefined)' ),
),
'theme_path' => array(
'label' => __( 'Theme directory location' ),
'value' => get_template_directory(),
),
);
if ( $auto_updates_enabled ) {
if ( isset( $transient->response[ $parent_theme->stylesheet ] ) ) {
$item = $transient->response[ $parent_theme->stylesheet ];
} elseif ( isset( $transient->no_update[ $parent_theme->stylesheet ] ) ) {
$item = $transient->no_update[ $parent_theme->stylesheet ];
} else {
$item = array(
'theme' => $parent_theme->stylesheet,
'new_version' => $parent_theme->version,
'url' => '',
'package' => '',
'requires' => '',
'requires_php' => '',
);
}
$auto_update_forced = wp_is_auto_update_forced_for_item( 'theme', null, (object) $item );
if ( ! is_null( $auto_update_forced ) ) {
$enabled = $auto_update_forced;
} else {
$enabled = in_array( $parent_theme->stylesheet, $auto_updates, true );
}
if ( $enabled ) {
$parent_theme_auto_update_string = __( 'Enabled' );
} else {
$parent_theme_auto_update_string = __( 'Disabled' );
}
/** This filter is documented in wp-admin/includes/class-wp-debug-data.php */
$parent_theme_auto_update_string = apply_filters( 'theme_auto_update_debug_string', $auto_updates_string, $parent_theme, $enabled );
$info['wp-parent-theme']['fields']['auto_update'] = array(
'label' => __( 'Auto-update' ),
'value' => $parent_theme_auto_update_string,
'debug' => $parent_theme_auto_update_string,
);
}
}
// Populate a list of all themes available in the install.
$all_themes = wp_get_themes();
foreach ( $all_themes as $theme_slug => $theme ) {
// Exclude the currently active theme from the list of all themes.
if ( $active_theme->stylesheet === $theme_slug ) {
continue;
}
// Exclude the currently active parent theme from the list of all themes.
if ( ! empty( $parent_theme ) && $parent_theme->stylesheet === $theme_slug ) {
continue;
}
$theme_version = $theme->version;
$theme_author = $theme->author;
// Sanitize.
$theme_author = wp_kses( $theme_author, array() );
$theme_version_string = __( 'No version or author information is available.' );
$theme_version_string_debug = 'undefined';
if ( ! empty( $theme_version ) && ! empty( $theme_author ) ) {
/* translators: 1: Theme version number. 2: Theme author name. */
$theme_version_string = sprintf( __( 'Version %1$s by %2$s' ), $theme_version, $theme_author );
$theme_version_string_debug = sprintf( 'version: %s, author: %s', $theme_version, $theme_author );
} else {
if ( ! empty( $theme_author ) ) {
/* translators: %s: Theme author name. */
$theme_version_string = sprintf( __( 'By %s' ), $theme_author );
$theme_version_string_debug = sprintf( 'author: %s, version: (undefined)', $theme_author );
}
if ( ! empty( $theme_version ) ) {
/* translators: %s: Theme version number. */
$theme_version_string = sprintf( __( 'Version %s' ), $theme_version );
$theme_version_string_debug = sprintf( 'author: (undefined), version: %s', $theme_version );
}
}
if ( array_key_exists( $theme_slug, $theme_updates ) ) {
/* translators: %s: Latest theme version number. */
$theme_version_string .= ' ' . sprintf( __( '(Latest version: %s)' ), $theme_updates[ $theme_slug ]->update['new_version'] );
$theme_version_string_debug .= sprintf( ' (latest version: %s)', $theme_updates[ $theme_slug ]->update['new_version'] );
}
if ( $auto_updates_enabled ) {
if ( isset( $transient->response[ $theme_slug ] ) ) {
$item = $transient->response[ $theme_slug ];
} elseif ( isset( $transient->no_update[ $theme_slug ] ) ) {
$item = $transient->no_update[ $theme_slug ];
} else {
$item = array(
'theme' => $theme_slug,
'new_version' => $theme->version,
'url' => '',
'package' => '',
'requires' => '',
'requires_php' => '',
);
}
$auto_update_forced = wp_is_auto_update_forced_for_item( 'theme', null, (object) $item );
if ( ! is_null( $auto_update_forced ) ) {
$enabled = $auto_update_forced;
} else {
$enabled = in_array( $theme_slug, $auto_updates, true );
}
if ( $enabled ) {
$auto_updates_string = __( 'Auto-updates enabled' );
} else {
$auto_updates_string = __( 'Auto-updates disabled' );
}
/**
* Filters the text string of the auto-updates setting for each theme in the Site Health debug data.
*
* @since 5.5.0
*
* @param string $auto_updates_string The string output for the auto-updates column.
* @param WP_Theme $theme An object of theme data.
* @param bool $enabled Whether auto-updates are enabled for this item.
*/
$auto_updates_string = apply_filters( 'theme_auto_update_debug_string', $auto_updates_string, $theme, $enabled );
$theme_version_string .= ' | ' . $auto_updates_string;
$theme_version_string_debug .= ', ' . $auto_updates_string;
}
$info['wp-themes-inactive']['fields'][ sanitize_text_field( $theme->name ) ] = array(
'label' => sprintf(
/* translators: 1: Theme name. 2: Theme slug. */
__( '%1$s (%2$s)' ),
$theme->name,
$theme_slug
),
'value' => $theme_version_string,
'debug' => $theme_version_string_debug,
);
}
// Add more filesystem checks.
if ( defined( 'WPMU_PLUGIN_DIR' ) && is_dir( WPMU_PLUGIN_DIR ) ) {
$is_writable_wpmu_plugin_dir = wp_is_writable( WPMU_PLUGIN_DIR );
$info['wp-filesystem']['fields']['mu-plugins'] = array(
'label' => __( 'The must use plugins directory' ),
'value' => ( $is_writable_wpmu_plugin_dir ? __( 'Writable' ) : __( 'Not writable' ) ),
'debug' => ( $is_writable_wpmu_plugin_dir ? 'writable' : 'not writable' ),
);
}
/**
* Filters the debug information shown on the Tools -> Site Health -> Info screen.
*
* Plugin or themes may wish to introduce their own debug information without creating
* additional admin pages. They can utilize this filter to introduce their own sections
* or add more data to existing sections.
*
* Array keys for sections added by core are all prefixed with `wp-`. Plugins and themes
* should use their own slug as a prefix, both for consistency as well as avoiding
* key collisions. Note that the array keys are used as labels for the copied data.
*
* All strings are expected to be plain text except `$description` that can contain
* inline HTML tags (see below).
*
* @since 5.2.0
*
* @param array $args {
* The debug information to be added to the core information page.
*
* This is an associative multi-dimensional array, up to three levels deep.
* The topmost array holds the sections, keyed by section ID.
*
* @type array ...$0 {
* Each section has a `$fields` associative array (see below), and each `$value` in `$fields`
* can be another associative array of name/value pairs when there is more structured data
* to display.
*
* @type string $label Required. The title for this section of the debug output.
* @type string $description Optional. A description for your information section which
* may contain basic HTML markup, inline tags only as it is
* outputted in a paragraph.
* @type bool $show_count Optional. If set to `true`, the amount of fields will be included
* in the title for this section. Default false.
* @type bool $private Optional. If set to `true`, the section and all associated fields
* will be excluded from the copied data. Default false.
* @type array $fields {
* Required. An associative array containing the fields to be displayed in the section,
* keyed by field ID.
*
* @type array ...$0 {
* An associative array containing the data to be displayed for the field.
*
* @type string $label Required. The label for this piece of information.
* @type mixed $value Required. The output that is displayed for this field.
* Text should be translated. Can be an associative array
* that is displayed as name/value pairs.
* Accepted types: `string|int|float|(string|int|float)[]`.
* @type string $debug Optional. The output that is used for this field when
* the user copies the data. It should be more concise and
* not translated. If not set, the content of `$value`
* is used. Note that the array keys are used as labels
* for the copied data.
* @type bool $private Optional. If set to `true`, the field will be excluded
* from the copied data, allowing you to show, for example,
* API keys here. Default false.
* }
* }
* }
* }
*/
$info = apply_filters( 'debug_information', $info );
return $info;
}
/**
* Returns the value of a MySQL system variable.
*
* @since 5.9.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $mysql_var Name of the MySQL system variable.
* @return string|null The variable value on success. Null if the variable does not exist.
*/
public static function get_mysql_var( $mysql_var ) {
global $wpdb;
$result = $wpdb->get_row(
$wpdb->prepare( 'SHOW VARIABLES LIKE %s', $mysql_var ),
ARRAY_A
);
if ( ! empty( $result ) && array_key_exists( 'Value', $result ) ) {
return $result['Value'];
}
return null;
}
/**
* Formats the information gathered for debugging, in a manner suitable for copying to a forum or support ticket.
*
* @since 5.2.0
*
* @param array $info_array Information gathered from the `WP_Debug_Data::debug_data()` function.
* @param string $data_type The data type to return, either 'info' or 'debug'.
* @return string The formatted data.
*/
public static function format( $info_array, $data_type ) {
$return = "`\n";
foreach ( $info_array as $section => $details ) {
// Skip this section if there are no fields, or the section has been declared as private.
if ( empty( $details['fields'] ) || ( isset( $details['private'] ) && $details['private'] ) ) {
continue;
}
$section_label = 'debug' === $data_type ? $section : $details['label'];
$return .= sprintf(
"### %s%s ###\n\n",
$section_label,
( isset( $details['show_count'] ) && $details['show_count'] ? sprintf( ' (%d)', count( $details['fields'] ) ) : '' )
);
foreach ( $details['fields'] as $field_name => $field ) {
if ( isset( $field['private'] ) && true === $field['private'] ) {
continue;
}
if ( 'debug' === $data_type && isset( $field['debug'] ) ) {
$debug_data = $field['debug'];
} else {
$debug_data = $field['value'];
}
// Can be array, one level deep only.
if ( is_array( $debug_data ) ) {
$value = '';
foreach ( $debug_data as $sub_field_name => $sub_field_value ) {
$value .= sprintf( "\n\t%s: %s", $sub_field_name, $sub_field_value );
}
} elseif ( is_bool( $debug_data ) ) {
$value = $debug_data ? 'true' : 'false';
} elseif ( empty( $debug_data ) && '0' !== $debug_data ) {
$value = 'undefined';
} else {
$value = $debug_data;
}
if ( 'debug' === $data_type ) {
$label = $field_name;
} else {
$label = $field['label'];
}
$return .= sprintf( "%s: %s\n", $label, $value );
}
$return .= "\n";
}
$return .= '`';
return $return;
}
/**
* Fetches the total size of all the database tables for the active database user.
*
* @since 5.2.0
*
* @return int The size of the database, in bytes.
*/
public static function get_database_size() {
global $wpdb;
$size = 0;
$rows = $wpdb->get_results( 'SHOW TABLE STATUS', ARRAY_A );
if ( $wpdb->num_rows > 0 ) {
foreach ( $rows as $row ) {
$size += $row['Data_length'] + $row['Index_length'];
}
}
return (int) $size;
}
/**
* Fetches the sizes of the WordPress directories: `wordpress` (ABSPATH), `plugins`, `themes`, and `uploads`.
* Intended to supplement the array returned by `WP_Debug_Data::debug_data()`.
*
* @since 5.2.0
*
* @return array The sizes of the directories, also the database size and total installation size.
*/
public static function get_sizes() {
$size_db = self::get_database_size();
$upload_dir = wp_get_upload_dir();
/*
* We will be using the PHP max execution time to prevent the size calculations
* from causing a timeout. The default value is 30 seconds, and some
* hosts do not allow you to read configuration values.
*/
if ( function_exists( 'ini_get' ) ) {
$max_execution_time = ini_get( 'max_execution_time' );
}
// The max_execution_time defaults to 0 when PHP runs from cli.
// We still want to limit it below.
if ( empty( $max_execution_time ) ) {
$max_execution_time = 30; // 30 seconds.
}
if ( $max_execution_time > 20 ) {
// If the max_execution_time is set to lower than 20 seconds, reduce it a bit to prevent
// edge-case timeouts that may happen after the size loop has finished running.
$max_execution_time -= 2;
}
// Go through the various installation directories and calculate their sizes.
// No trailing slashes.
$paths = array(
'wordpress_size' => untrailingslashit( ABSPATH ),
'themes_size' => get_theme_root(),
'plugins_size' => WP_PLUGIN_DIR,
'uploads_size' => $upload_dir['basedir'],
);
$exclude = $paths;
unset( $exclude['wordpress_size'] );
$exclude = array_values( $exclude );
$size_total = 0;
$all_sizes = array();
// Loop over all the directories we want to gather the sizes for.
foreach ( $paths as $name => $path ) {
$dir_size = null; // Default to timeout.
$results = array(
'path' => $path,
'raw' => 0,
);
if ( microtime( true ) - WP_START_TIMESTAMP < $max_execution_time ) {
if ( 'wordpress_size' === $name ) {
$dir_size = recurse_dirsize( $path, $exclude, $max_execution_time );
} else {
$dir_size = recurse_dirsize( $path, null, $max_execution_time );
}
}
if ( false === $dir_size ) {
// Error reading.
$results['size'] = __( 'The size cannot be calculated. The directory is not accessible. Usually caused by invalid permissions.' );
$results['debug'] = 'not accessible';
// Stop total size calculation.
$size_total = null;
} elseif ( null === $dir_size ) {
// Timeout.
$results['size'] = __( 'The directory size calculation has timed out. Usually caused by a very large number of sub-directories and files.' );
$results['debug'] = 'timeout while calculating size';
// Stop total size calculation.
$size_total = null;
} else {
if ( null !== $size_total ) {
$size_total += $dir_size;
}
$results['raw'] = $dir_size;
$results['size'] = size_format( $dir_size, 2 );
$results['debug'] = $results['size'] . " ({$dir_size} bytes)";
}
$all_sizes[ $name ] = $results;
}
if ( $size_db > 0 ) {
$database_size = size_format( $size_db, 2 );
$all_sizes['database_size'] = array(
'raw' => $size_db,
'size' => $database_size,
'debug' => $database_size . " ({$size_db} bytes)",
);
} else {
$all_sizes['database_size'] = array(
'size' => __( 'Not available' ),
'debug' => 'not available',
);
}
if ( null !== $size_total && $size_db > 0 ) {
$total_size = $size_total + $size_db;
$total_size_mb = size_format( $total_size, 2 );
$all_sizes['total_size'] = array(
'raw' => $total_size,
'size' => $total_size_mb,
'debug' => $total_size_mb . " ({$total_size} bytes)",
);
} else {
$all_sizes['total_size'] = array(
'size' => __( 'Total size is not available. Some errors were encountered when determining the size of your installation.' ),
'debug' => 'not available',
);
}
return $all_sizes;
}
}
```
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
| programming_docs |
wordpress class IXR_Value {} class IXR\_Value {}
===================
[IXR\_Value](ixr_value)
* [\_\_construct](ixr_value/__construct) — PHP5 constructor.
* [calculateType](ixr_value/calculatetype)
* [getXml](ixr_value/getxml)
* [isStruct](ixr_value/isstruct) — Checks whether or not the supplied array is a struct or not
* [IXR\_Value](ixr_value/ixr_value) — PHP4 constructor.
File: `wp-includes/IXR/class-IXR-value.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-value.php/)
```
class IXR_Value {
var $data;
var $type;
/**
* PHP5 constructor.
*/
function __construct( $data, $type = false )
{
$this->data = $data;
if (!$type) {
$type = $this->calculateType();
}
$this->type = $type;
if ($type == 'struct') {
// Turn all the values in the array in to new IXR_Value objects
foreach ($this->data as $key => $value) {
$this->data[$key] = new IXR_Value($value);
}
}
if ($type == 'array') {
for ($i = 0, $j = count($this->data); $i < $j; $i++) {
$this->data[$i] = new IXR_Value($this->data[$i]);
}
}
}
/**
* PHP4 constructor.
*/
public function IXR_Value( $data, $type = false ) {
self::__construct( $data, $type );
}
function calculateType()
{
if ($this->data === true || $this->data === false) {
return 'boolean';
}
if (is_integer($this->data)) {
return 'int';
}
if (is_double($this->data)) {
return 'double';
}
// Deal with IXR object types base64 and date
if (is_object($this->data) && is_a($this->data, 'IXR_Date')) {
return 'date';
}
if (is_object($this->data) && is_a($this->data, 'IXR_Base64')) {
return 'base64';
}
// If it is a normal PHP object convert it in to a struct
if (is_object($this->data)) {
$this->data = get_object_vars($this->data);
return 'struct';
}
if (!is_array($this->data)) {
return 'string';
}
// We have an array - is it an array or a struct?
if ($this->isStruct($this->data)) {
return 'struct';
} else {
return 'array';
}
}
function getXml()
{
// Return XML for this value
switch ($this->type) {
case 'boolean':
return '<boolean>'.(($this->data) ? '1' : '0').'</boolean>';
break;
case 'int':
return '<int>'.$this->data.'</int>';
break;
case 'double':
return '<double>'.$this->data.'</double>';
break;
case 'string':
return '<string>'.htmlspecialchars($this->data).'</string>';
break;
case 'array':
$return = '<array><data>'."\n";
foreach ($this->data as $item) {
$return .= ' <value>'.$item->getXml()."</value>\n";
}
$return .= '</data></array>';
return $return;
break;
case 'struct':
$return = '<struct>'."\n";
foreach ($this->data as $name => $value) {
$name = htmlspecialchars($name);
$return .= " <member><name>$name</name><value>";
$return .= $value->getXml()."</value></member>\n";
}
$return .= '</struct>';
return $return;
break;
case 'date':
case 'base64':
return $this->data->getXml();
break;
}
return false;
}
/**
* Checks whether or not the supplied array is a struct or not
*
* @param array $array
* @return bool
*/
function isStruct($array)
{
$expected = 0;
foreach ($array as $key => $value) {
if ((string)$key !== (string)$expected) {
return true;
}
$expected++;
}
return false;
}
}
```
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress class WP_Block_Patterns_Registry {} class WP\_Block\_Patterns\_Registry {}
======================================
Class used for interacting with block patterns.
* [get\_all\_registered](wp_block_patterns_registry/get_all_registered) — Retrieves all registered block patterns.
* [get\_instance](wp_block_patterns_registry/get_instance) — Utility method to retrieve the main instance of the class.
* [get\_registered](wp_block_patterns_registry/get_registered) — Retrieves an array containing the properties of a registered block pattern.
* [is\_registered](wp_block_patterns_registry/is_registered) — Checks if a block pattern is registered.
* [register](wp_block_patterns_registry/register) — Registers a block pattern.
* [unregister](wp_block_patterns_registry/unregister) — Unregisters a block pattern.
File: `wp-includes/class-wp-block-patterns-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-patterns-registry.php/)
```
final class WP_Block_Patterns_Registry {
/**
* Registered block patterns array.
*
* @since 5.5.0
* @var array[]
*/
private $registered_patterns = array();
/**
* Patterns registered outside the `init` action.
*
* @since 6.0.0
* @var array[]
*/
private $registered_patterns_outside_init = array();
/**
* Container for the main instance of the class.
*
* @since 5.5.0
* @var WP_Block_Patterns_Registry|null
*/
private static $instance = null;
/**
* Registers a block pattern.
*
* @since 5.5.0
* @since 5.8.0 Added support for the `blockTypes` property.
*
* @param string $pattern_name Block pattern name including namespace.
* @param array $pattern_properties {
* List of properties for the block pattern.
*
* @type string $title Required. A human-readable title for the pattern.
* @type string $content Required. Block HTML markup for the pattern.
* @type string $description Optional. Visually hidden text used to describe the pattern in the
* inserter. A description is optional, but is strongly
* encouraged when the title does not fully describe what the
* pattern does. The description will help users discover the
* pattern while searching.
* @type int $viewportWidth Optional. The intended width of the pattern to allow for a scaled
* preview within the pattern inserter.
* @type array $categories Optional. A list of registered pattern categories used to group block
* patterns. Block patterns can be shown on multiple categories.
* A category must be registered separately in order to be used
* here.
* @type array $blockTypes Optional. A list of block names including namespace that could use
* the block pattern in certain contexts (placeholder, transforms).
* The block pattern is available in the block editor inserter
* regardless of this list of block names.
* Certain blocks support further specificity besides the block name
* (e.g. for `core/template-part` you can specify areas
* like `core/template-part/header` or `core/template-part/footer`).
* @type array $keywords Optional. A list of aliases or keywords that help users discover the
* pattern while searching.
* }
* @return bool True if the pattern was registered with success and false otherwise.
*/
public function register( $pattern_name, $pattern_properties ) {
if ( ! isset( $pattern_name ) || ! is_string( $pattern_name ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Pattern name must be a string.' ),
'5.5.0'
);
return false;
}
if ( ! isset( $pattern_properties['title'] ) || ! is_string( $pattern_properties['title'] ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Pattern title must be a string.' ),
'5.5.0'
);
return false;
}
if ( ! isset( $pattern_properties['content'] ) || ! is_string( $pattern_properties['content'] ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Pattern content must be a string.' ),
'5.5.0'
);
return false;
}
$pattern = array_merge(
$pattern_properties,
array( 'name' => $pattern_name )
);
$this->registered_patterns[ $pattern_name ] = $pattern;
// If the pattern 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_patterns_outside_init[ $pattern_name ] = $pattern;
}
return true;
}
/**
* Unregisters a block pattern.
*
* @since 5.5.0
*
* @param string $pattern_name Block pattern name including namespace.
* @return bool True if the pattern was unregistered with success and false otherwise.
*/
public function unregister( $pattern_name ) {
if ( ! $this->is_registered( $pattern_name ) ) {
_doing_it_wrong(
__METHOD__,
/* translators: %s: Pattern name. */
sprintf( __( 'Pattern "%s" not found.' ), $pattern_name ),
'5.5.0'
);
return false;
}
unset( $this->registered_patterns[ $pattern_name ] );
unset( $this->registered_patterns_outside_init[ $pattern_name ] );
return true;
}
/**
* Retrieves an array containing the properties of a registered block pattern.
*
* @since 5.5.0
*
* @param string $pattern_name Block pattern name including namespace.
* @return array Registered pattern properties.
*/
public function get_registered( $pattern_name ) {
if ( ! $this->is_registered( $pattern_name ) ) {
return null;
}
return $this->registered_patterns[ $pattern_name ];
}
/**
* Retrieves all registered block patterns.
*
* @since 5.5.0
*
* @param bool $outside_init_only Return only patterns registered outside the `init` action.
* @return array[] Array of arrays containing the registered block patterns properties,
* and per style.
*/
public function get_all_registered( $outside_init_only = false ) {
return array_values(
$outside_init_only
? $this->registered_patterns_outside_init
: $this->registered_patterns
);
}
/**
* Checks if a block pattern is registered.
*
* @since 5.5.0
*
* @param string $pattern_name Block pattern name including namespace.
* @return bool True if the pattern is registered, false otherwise.
*/
public function is_registered( $pattern_name ) {
return isset( $this->registered_patterns[ $pattern_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_Patterns_Registry The main instance.
*/
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
}
```
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress class WP_REST_Request {} class WP\_REST\_Request {}
==========================
Core class used to implement a REST request object.
Contains data from the request, to be passed to the callback.
Note: This implements ArrayAccess, and acts as an array of parameters when used in that manner. It does not use ArrayObject (as we cannot rely on SPL), so be aware it may have non-array behaviour in some cases.
Note: When using features provided by ArrayAccess, be aware that WordPress deliberately does not distinguish between arguments of the same name for different request methods.
For instance, in a request with `GET id=1` and `POST id=2`, `$request['id']` will equal 2 (`POST`) not 1 (`GET`). For more precision between request methods, use [WP\_REST\_Request::get\_body\_params()](wp_rest_request/get_body_params), [WP\_REST\_Request::get\_url\_params()](wp_rest_request/get_url_params), etc.
* [\_\_construct](wp_rest_request/__construct) — Constructor.
* [add\_header](wp_rest_request/add_header) — Appends a header value for the given header.
* [canonicalize\_header\_name](wp_rest_request/canonicalize_header_name) — Canonicalizes the header name.
* [from\_url](wp_rest_request/from_url) — Retrieves a WP\_REST\_Request object from a full URL.
* [get\_attributes](wp_rest_request/get_attributes) — Retrieves the attributes for the request.
* [get\_body](wp_rest_request/get_body) — Retrieves the request body content.
* [get\_body\_params](wp_rest_request/get_body_params) — Retrieves parameters from the body.
* [get\_content\_type](wp_rest_request/get_content_type) — Retrieves the content-type of the request.
* [get\_default\_params](wp_rest_request/get_default_params) — Retrieves the default parameters.
* [get\_file\_params](wp_rest_request/get_file_params) — Retrieves multipart file parameters from the body.
* [get\_header](wp_rest_request/get_header) — Retrieves the given header from the request.
* [get\_header\_as\_array](wp_rest_request/get_header_as_array) — Retrieves header values from the request.
* [get\_headers](wp_rest_request/get_headers) — Retrieves all headers from the request.
* [get\_json\_params](wp_rest_request/get_json_params) — Retrieves the parameters from a JSON-formatted body.
* [get\_method](wp_rest_request/get_method) — Retrieves the HTTP method for the request.
* [get\_param](wp_rest_request/get_param) — Retrieves a parameter from the request.
* [get\_parameter\_order](wp_rest_request/get_parameter_order) — Retrieves the parameter priority order.
* [get\_params](wp_rest_request/get_params) — Retrieves merged parameters from the request.
* [get\_query\_params](wp_rest_request/get_query_params) — Retrieves parameters from the query string.
* [get\_route](wp_rest_request/get_route) — Retrieves the route that matched the request.
* [get\_url\_params](wp_rest_request/get_url_params) — Retrieves parameters from the route itself.
* [has\_param](wp_rest_request/has_param) — Checks if a parameter exists in the request.
* [has\_valid\_params](wp_rest_request/has_valid_params) — Checks whether this request is valid according to its attributes.
* [is\_json\_content\_type](wp_rest_request/is_json_content_type) — Checks if the request has specified a JSON content-type.
* [offsetExists](wp_rest_request/offsetexists)
* [offsetGet](wp_rest_request/offsetget)
* [offsetSet](wp_rest_request/offsetset)
* [offsetUnset](wp_rest_request/offsetunset)
* [parse\_body\_params](wp_rest_request/parse_body_params) — Parses the request body parameters.
* [parse\_json\_params](wp_rest_request/parse_json_params) — Parses the JSON parameters.
* [remove\_header](wp_rest_request/remove_header) — Removes all values for a header.
* [sanitize\_params](wp_rest_request/sanitize_params) — Sanitizes (where possible) the params on the request.
* [set\_attributes](wp_rest_request/set_attributes) — Sets the attributes for the request.
* [set\_body](wp_rest_request/set_body) — Sets body content.
* [set\_body\_params](wp_rest_request/set_body_params) — Sets parameters from the body.
* [set\_default\_params](wp_rest_request/set_default_params) — Sets default parameters.
* [set\_file\_params](wp_rest_request/set_file_params) — Sets multipart file parameters from the body.
* [set\_header](wp_rest_request/set_header) — Sets the header on request.
* [set\_headers](wp_rest_request/set_headers) — Sets headers on the request.
* [set\_method](wp_rest_request/set_method) — Sets HTTP method for the request.
* [set\_param](wp_rest_request/set_param) — Sets a parameter on the request.
* [set\_query\_params](wp_rest_request/set_query_params) — Sets parameters from the query string.
* [set\_route](wp_rest_request/set_route) — Sets the route that matched the request.
* [set\_url\_params](wp_rest_request/set_url_params) — Sets parameters from the route.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
class WP_REST_Request implements ArrayAccess {
/**
* HTTP method.
*
* @since 4.4.0
* @var string
*/
protected $method = '';
/**
* Parameters passed to the request.
*
* These typically come from the `$_GET`, `$_POST` and `$_FILES`
* superglobals when being created from the global scope.
*
* @since 4.4.0
* @var array Contains GET, POST and FILES keys mapping to arrays of data.
*/
protected $params;
/**
* HTTP headers for the request.
*
* @since 4.4.0
* @var array Map of key to value. Key is always lowercase, as per HTTP specification.
*/
protected $headers = array();
/**
* Body data.
*
* @since 4.4.0
* @var string Binary data from the request.
*/
protected $body = null;
/**
* Route matched for the request.
*
* @since 4.4.0
* @var string
*/
protected $route;
/**
* Attributes (options) for the route that was matched.
*
* This is the options array used when the route was registered, typically
* containing the callback as well as the valid methods for the route.
*
* @since 4.4.0
* @var array Attributes for the request.
*/
protected $attributes = array();
/**
* Used to determine if the JSON data has been parsed yet.
*
* Allows lazy-parsing of JSON data where possible.
*
* @since 4.4.0
* @var bool
*/
protected $parsed_json = false;
/**
* Used to determine if the body data has been parsed yet.
*
* @since 4.4.0
* @var bool
*/
protected $parsed_body = false;
/**
* Constructor.
*
* @since 4.4.0
*
* @param string $method Optional. Request method. Default empty.
* @param string $route Optional. Request route. Default empty.
* @param array $attributes Optional. Request attributes. Default empty array.
*/
public function __construct( $method = '', $route = '', $attributes = array() ) {
$this->params = array(
'URL' => array(),
'GET' => array(),
'POST' => array(),
'FILES' => array(),
// See parse_json_params.
'JSON' => null,
'defaults' => array(),
);
$this->set_method( $method );
$this->set_route( $route );
$this->set_attributes( $attributes );
}
/**
* Retrieves the HTTP method for the request.
*
* @since 4.4.0
*
* @return string HTTP method.
*/
public function get_method() {
return $this->method;
}
/**
* Sets HTTP method for the request.
*
* @since 4.4.0
*
* @param string $method HTTP method.
*/
public function set_method( $method ) {
$this->method = strtoupper( $method );
}
/**
* Retrieves all headers from the request.
*
* @since 4.4.0
*
* @return array Map of key to value. Key is always lowercase, as per HTTP specification.
*/
public function get_headers() {
return $this->headers;
}
/**
* Canonicalizes the header name.
*
* Ensures that header names are always treated the same regardless of
* source. Header names are always case insensitive.
*
* Note that we treat `-` (dashes) and `_` (underscores) as the same
* character, as per header parsing rules in both Apache and nginx.
*
* @link https://stackoverflow.com/q/18185366
* @link https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#missing-disappearing-http-headers
* @link https://nginx.org/en/docs/http/ngx_http_core_module.html#underscores_in_headers
*
* @since 4.4.0
*
* @param string $key Header name.
* @return string Canonicalized name.
*/
public static function canonicalize_header_name( $key ) {
$key = strtolower( $key );
$key = str_replace( '-', '_', $key );
return $key;
}
/**
* Retrieves the given header from the request.
*
* If the header has multiple values, they will be concatenated with a comma
* as per the HTTP specification. Be aware that some non-compliant headers
* (notably cookie headers) cannot be joined this way.
*
* @since 4.4.0
*
* @param string $key Header name, will be canonicalized to lowercase.
* @return string|null String value if set, null otherwise.
*/
public function get_header( $key ) {
$key = $this->canonicalize_header_name( $key );
if ( ! isset( $this->headers[ $key ] ) ) {
return null;
}
return implode( ',', $this->headers[ $key ] );
}
/**
* Retrieves header values from the request.
*
* @since 4.4.0
*
* @param string $key Header name, will be canonicalized to lowercase.
* @return array|null List of string values if set, null otherwise.
*/
public function get_header_as_array( $key ) {
$key = $this->canonicalize_header_name( $key );
if ( ! isset( $this->headers[ $key ] ) ) {
return null;
}
return $this->headers[ $key ];
}
/**
* Sets the header on request.
*
* @since 4.4.0
*
* @param string $key Header name.
* @param string $value Header value, or list of values.
*/
public function set_header( $key, $value ) {
$key = $this->canonicalize_header_name( $key );
$value = (array) $value;
$this->headers[ $key ] = $value;
}
/**
* Appends a header value for the given header.
*
* @since 4.4.0
*
* @param string $key Header name.
* @param string $value Header value, or list of values.
*/
public function add_header( $key, $value ) {
$key = $this->canonicalize_header_name( $key );
$value = (array) $value;
if ( ! isset( $this->headers[ $key ] ) ) {
$this->headers[ $key ] = array();
}
$this->headers[ $key ] = array_merge( $this->headers[ $key ], $value );
}
/**
* Removes all values for a header.
*
* @since 4.4.0
*
* @param string $key Header name.
*/
public function remove_header( $key ) {
$key = $this->canonicalize_header_name( $key );
unset( $this->headers[ $key ] );
}
/**
* Sets headers on the request.
*
* @since 4.4.0
*
* @param array $headers Map of header name to value.
* @param bool $override If true, replace the request's headers. Otherwise, merge with existing.
*/
public function set_headers( $headers, $override = true ) {
if ( true === $override ) {
$this->headers = array();
}
foreach ( $headers as $key => $value ) {
$this->set_header( $key, $value );
}
}
/**
* Retrieves the content-type of the request.
*
* @since 4.4.0
*
* @return array|null Map containing 'value' and 'parameters' keys
* or null when no valid content-type header was
* available.
*/
public function get_content_type() {
$value = $this->get_header( 'content-type' );
if ( empty( $value ) ) {
return null;
}
$parameters = '';
if ( strpos( $value, ';' ) ) {
list( $value, $parameters ) = explode( ';', $value, 2 );
}
$value = strtolower( $value );
if ( false === strpos( $value, '/' ) ) {
return null;
}
// Parse type and subtype out.
list( $type, $subtype ) = explode( '/', $value, 2 );
$data = compact( 'value', 'type', 'subtype', 'parameters' );
$data = array_map( 'trim', $data );
return $data;
}
/**
* Checks if the request has specified a JSON content-type.
*
* @since 5.6.0
*
* @return bool True if the content-type header is JSON.
*/
public function is_json_content_type() {
$content_type = $this->get_content_type();
return isset( $content_type['value'] ) && wp_is_json_media_type( $content_type['value'] );
}
/**
* Retrieves the parameter priority order.
*
* Used when checking parameters in WP_REST_Request::get_param().
*
* @since 4.4.0
*
* @return string[] Array of types to check, in order of priority.
*/
protected function get_parameter_order() {
$order = array();
if ( $this->is_json_content_type() ) {
$order[] = 'JSON';
}
$this->parse_json_params();
// Ensure we parse the body data.
$body = $this->get_body();
if ( 'POST' !== $this->method && ! empty( $body ) ) {
$this->parse_body_params();
}
$accepts_body_data = array( 'POST', 'PUT', 'PATCH', 'DELETE' );
if ( in_array( $this->method, $accepts_body_data, true ) ) {
$order[] = 'POST';
}
$order[] = 'GET';
$order[] = 'URL';
$order[] = 'defaults';
/**
* Filters the parameter priority order for a REST API request.
*
* The order affects which parameters are checked when using WP_REST_Request::get_param()
* and family. This acts similarly to PHP's `request_order` setting.
*
* @since 4.4.0
*
* @param string[] $order Array of types to check, in order of priority.
* @param WP_REST_Request $request The request object.
*/
return apply_filters( 'rest_request_parameter_order', $order, $this );
}
/**
* Retrieves a parameter from the request.
*
* @since 4.4.0
*
* @param string $key Parameter name.
* @return mixed|null Value if set, null otherwise.
*/
public function get_param( $key ) {
$order = $this->get_parameter_order();
foreach ( $order as $type ) {
// Determine if we have the parameter for this type.
if ( isset( $this->params[ $type ][ $key ] ) ) {
return $this->params[ $type ][ $key ];
}
}
return null;
}
/**
* Checks if a parameter exists in the request.
*
* This allows distinguishing between an omitted parameter,
* and a parameter specifically set to null.
*
* @since 5.3.0
*
* @param string $key Parameter name.
* @return bool True if a param exists for the given key.
*/
public function has_param( $key ) {
$order = $this->get_parameter_order();
foreach ( $order as $type ) {
if ( is_array( $this->params[ $type ] ) && array_key_exists( $key, $this->params[ $type ] ) ) {
return true;
}
}
return false;
}
/**
* Sets a parameter on the request.
*
* If the given parameter key exists in any parameter type an update will take place,
* otherwise a new param will be created in the first parameter type (respecting
* get_parameter_order()).
*
* @since 4.4.0
*
* @param string $key Parameter name.
* @param mixed $value Parameter value.
*/
public function set_param( $key, $value ) {
$order = $this->get_parameter_order();
$found_key = false;
foreach ( $order as $type ) {
if ( 'defaults' !== $type && is_array( $this->params[ $type ] ) && array_key_exists( $key, $this->params[ $type ] ) ) {
$this->params[ $type ][ $key ] = $value;
$found_key = true;
}
}
if ( ! $found_key ) {
$this->params[ $order[0] ][ $key ] = $value;
}
}
/**
* Retrieves merged parameters from the request.
*
* The equivalent of get_param(), but returns all parameters for the request.
* Handles merging all the available values into a single array.
*
* @since 4.4.0
*
* @return array Map of key to value.
*/
public function get_params() {
$order = $this->get_parameter_order();
$order = array_reverse( $order, true );
$params = array();
foreach ( $order as $type ) {
// array_merge() / the "+" operator will mess up
// numeric keys, so instead do a manual foreach.
foreach ( (array) $this->params[ $type ] as $key => $value ) {
$params[ $key ] = $value;
}
}
return $params;
}
/**
* Retrieves parameters from the route itself.
*
* These are parsed from the URL using the regex.
*
* @since 4.4.0
*
* @return array Parameter map of key to value.
*/
public function get_url_params() {
return $this->params['URL'];
}
/**
* Sets parameters from the route.
*
* Typically, this is set after parsing the URL.
*
* @since 4.4.0
*
* @param array $params Parameter map of key to value.
*/
public function set_url_params( $params ) {
$this->params['URL'] = $params;
}
/**
* Retrieves parameters from the query string.
*
* These are the parameters you'd typically find in `$_GET`.
*
* @since 4.4.0
*
* @return array Parameter map of key to value
*/
public function get_query_params() {
return $this->params['GET'];
}
/**
* Sets parameters from the query string.
*
* Typically, this is set from `$_GET`.
*
* @since 4.4.0
*
* @param array $params Parameter map of key to value.
*/
public function set_query_params( $params ) {
$this->params['GET'] = $params;
}
/**
* Retrieves parameters from the body.
*
* These are the parameters you'd typically find in `$_POST`.
*
* @since 4.4.0
*
* @return array Parameter map of key to value.
*/
public function get_body_params() {
return $this->params['POST'];
}
/**
* Sets parameters from the body.
*
* Typically, this is set from `$_POST`.
*
* @since 4.4.0
*
* @param array $params Parameter map of key to value.
*/
public function set_body_params( $params ) {
$this->params['POST'] = $params;
}
/**
* Retrieves multipart file parameters from the body.
*
* These are the parameters you'd typically find in `$_FILES`.
*
* @since 4.4.0
*
* @return array Parameter map of key to value
*/
public function get_file_params() {
return $this->params['FILES'];
}
/**
* Sets multipart file parameters from the body.
*
* Typically, this is set from `$_FILES`.
*
* @since 4.4.0
*
* @param array $params Parameter map of key to value.
*/
public function set_file_params( $params ) {
$this->params['FILES'] = $params;
}
/**
* Retrieves the default parameters.
*
* These are the parameters set in the route registration.
*
* @since 4.4.0
*
* @return array Parameter map of key to value
*/
public function get_default_params() {
return $this->params['defaults'];
}
/**
* Sets default parameters.
*
* These are the parameters set in the route registration.
*
* @since 4.4.0
*
* @param array $params Parameter map of key to value.
*/
public function set_default_params( $params ) {
$this->params['defaults'] = $params;
}
/**
* Retrieves the request body content.
*
* @since 4.4.0
*
* @return string Binary data from the request body.
*/
public function get_body() {
return $this->body;
}
/**
* Sets body content.
*
* @since 4.4.0
*
* @param string $data Binary data from the request body.
*/
public function set_body( $data ) {
$this->body = $data;
// Enable lazy parsing.
$this->parsed_json = false;
$this->parsed_body = false;
$this->params['JSON'] = null;
}
/**
* Retrieves the parameters from a JSON-formatted body.
*
* @since 4.4.0
*
* @return array Parameter map of key to value.
*/
public function get_json_params() {
// Ensure the parameters have been parsed out.
$this->parse_json_params();
return $this->params['JSON'];
}
/**
* Parses the JSON parameters.
*
* Avoids parsing the JSON data until we need to access it.
*
* @since 4.4.0
* @since 4.7.0 Returns error instance if value cannot be decoded.
* @return true|WP_Error True if the JSON data was passed or no JSON data was provided, WP_Error if invalid JSON was passed.
*/
protected function parse_json_params() {
if ( $this->parsed_json ) {
return true;
}
$this->parsed_json = true;
// Check that we actually got JSON.
if ( ! $this->is_json_content_type() ) {
return true;
}
$body = $this->get_body();
if ( empty( $body ) ) {
return true;
}
$params = json_decode( $body, true );
/*
* Check for a parsing error.
*/
if ( null === $params && JSON_ERROR_NONE !== json_last_error() ) {
// Ensure subsequent calls receive error instance.
$this->parsed_json = false;
$error_data = array(
'status' => WP_Http::BAD_REQUEST,
'json_error_code' => json_last_error(),
'json_error_message' => json_last_error_msg(),
);
return new WP_Error( 'rest_invalid_json', __( 'Invalid JSON body passed.' ), $error_data );
}
$this->params['JSON'] = $params;
return true;
}
/**
* Parses the request body parameters.
*
* Parses out URL-encoded bodies for request methods that aren't supported
* natively by PHP. In PHP 5.x, only POST has these parsed automatically.
*
* @since 4.4.0
*/
protected function parse_body_params() {
if ( $this->parsed_body ) {
return;
}
$this->parsed_body = true;
/*
* Check that we got URL-encoded. Treat a missing content-type as
* URL-encoded for maximum compatibility.
*/
$content_type = $this->get_content_type();
if ( ! empty( $content_type ) && 'application/x-www-form-urlencoded' !== $content_type['value'] ) {
return;
}
parse_str( $this->get_body(), $params );
/*
* Add to the POST parameters stored internally. If a user has already
* set these manually (via `set_body_params`), don't override them.
*/
$this->params['POST'] = array_merge( $params, $this->params['POST'] );
}
/**
* Retrieves the route that matched the request.
*
* @since 4.4.0
*
* @return string Route matching regex.
*/
public function get_route() {
return $this->route;
}
/**
* Sets the route that matched the request.
*
* @since 4.4.0
*
* @param string $route Route matching regex.
*/
public function set_route( $route ) {
$this->route = $route;
}
/**
* Retrieves the attributes for the request.
*
* These are the options for the route that was matched.
*
* @since 4.4.0
*
* @return array Attributes for the request.
*/
public function get_attributes() {
return $this->attributes;
}
/**
* Sets the attributes for the request.
*
* @since 4.4.0
*
* @param array $attributes Attributes for the request.
*/
public function set_attributes( $attributes ) {
$this->attributes = $attributes;
}
/**
* Sanitizes (where possible) the params on the request.
*
* This is primarily based off the sanitize_callback param on each registered
* argument.
*
* @since 4.4.0
*
* @return true|WP_Error True if parameters were sanitized, WP_Error if an error occurred during sanitization.
*/
public function sanitize_params() {
$attributes = $this->get_attributes();
// No arguments set, skip sanitizing.
if ( empty( $attributes['args'] ) ) {
return true;
}
$order = $this->get_parameter_order();
$invalid_params = array();
$invalid_details = array();
foreach ( $order as $type ) {
if ( empty( $this->params[ $type ] ) ) {
continue;
}
foreach ( $this->params[ $type ] as $key => $value ) {
if ( ! isset( $attributes['args'][ $key ] ) ) {
continue;
}
$param_args = $attributes['args'][ $key ];
// If the arg has a type but no sanitize_callback attribute, default to rest_parse_request_arg.
if ( ! array_key_exists( 'sanitize_callback', $param_args ) && ! empty( $param_args['type'] ) ) {
$param_args['sanitize_callback'] = 'rest_parse_request_arg';
}
// If there's still no sanitize_callback, nothing to do here.
if ( empty( $param_args['sanitize_callback'] ) ) {
continue;
}
/** @var mixed|WP_Error $sanitized_value */
$sanitized_value = call_user_func( $param_args['sanitize_callback'], $value, $this, $key );
if ( is_wp_error( $sanitized_value ) ) {
$invalid_params[ $key ] = implode( ' ', $sanitized_value->get_error_messages() );
$invalid_details[ $key ] = rest_convert_error_to_response( $sanitized_value )->get_data();
} else {
$this->params[ $type ][ $key ] = $sanitized_value;
}
}
}
if ( $invalid_params ) {
return new WP_Error(
'rest_invalid_param',
/* translators: %s: List of invalid parameters. */
sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', array_keys( $invalid_params ) ) ),
array(
'status' => 400,
'params' => $invalid_params,
'details' => $invalid_details,
)
);
}
return true;
}
/**
* Checks whether this request is valid according to its attributes.
*
* @since 4.4.0
*
* @return true|WP_Error True if there are no parameters to validate or if all pass validation,
* WP_Error if required parameters are missing.
*/
public function has_valid_params() {
// If JSON data was passed, check for errors.
$json_error = $this->parse_json_params();
if ( is_wp_error( $json_error ) ) {
return $json_error;
}
$attributes = $this->get_attributes();
$required = array();
$args = empty( $attributes['args'] ) ? array() : $attributes['args'];
foreach ( $args as $key => $arg ) {
$param = $this->get_param( $key );
if ( isset( $arg['required'] ) && true === $arg['required'] && null === $param ) {
$required[] = $key;
}
}
if ( ! empty( $required ) ) {
return new WP_Error(
'rest_missing_callback_param',
/* translators: %s: List of required parameters. */
sprintf( __( 'Missing parameter(s): %s' ), implode( ', ', $required ) ),
array(
'status' => 400,
'params' => $required,
)
);
}
/*
* Check the validation callbacks for each registered arg.
*
* This is done after required checking as required checking is cheaper.
*/
$invalid_params = array();
$invalid_details = array();
foreach ( $args as $key => $arg ) {
$param = $this->get_param( $key );
if ( null !== $param && ! empty( $arg['validate_callback'] ) ) {
/** @var bool|\WP_Error $valid_check */
$valid_check = call_user_func( $arg['validate_callback'], $param, $this, $key );
if ( false === $valid_check ) {
$invalid_params[ $key ] = __( 'Invalid parameter.' );
}
if ( is_wp_error( $valid_check ) ) {
$invalid_params[ $key ] = implode( ' ', $valid_check->get_error_messages() );
$invalid_details[ $key ] = rest_convert_error_to_response( $valid_check )->get_data();
}
}
}
if ( $invalid_params ) {
return new WP_Error(
'rest_invalid_param',
/* translators: %s: List of invalid parameters. */
sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', array_keys( $invalid_params ) ) ),
array(
'status' => 400,
'params' => $invalid_params,
'details' => $invalid_details,
)
);
}
if ( isset( $attributes['validate_callback'] ) ) {
$valid_check = call_user_func( $attributes['validate_callback'], $this );
if ( is_wp_error( $valid_check ) ) {
return $valid_check;
}
if ( false === $valid_check ) {
// A WP_Error instance is preferred, but false is supported for parity with the per-arg validate_callback.
return new WP_Error( 'rest_invalid_params', __( 'Invalid parameters.' ), array( 'status' => 400 ) );
}
}
return true;
}
/**
* Checks if a parameter is set.
*
* @since 4.4.0
*
* @param string $offset Parameter name.
* @return bool Whether the parameter is set.
*/
#[ReturnTypeWillChange]
public function offsetExists( $offset ) {
$order = $this->get_parameter_order();
foreach ( $order as $type ) {
if ( isset( $this->params[ $type ][ $offset ] ) ) {
return true;
}
}
return false;
}
/**
* Retrieves a parameter from the request.
*
* @since 4.4.0
*
* @param string $offset Parameter name.
* @return mixed|null Value if set, null otherwise.
*/
#[ReturnTypeWillChange]
public function offsetGet( $offset ) {
return $this->get_param( $offset );
}
/**
* Sets a parameter on the request.
*
* @since 4.4.0
*
* @param string $offset Parameter name.
* @param mixed $value Parameter value.
*/
#[ReturnTypeWillChange]
public function offsetSet( $offset, $value ) {
$this->set_param( $offset, $value );
}
/**
* Removes a parameter from the request.
*
* @since 4.4.0
*
* @param string $offset Parameter name.
*/
#[ReturnTypeWillChange]
public function offsetUnset( $offset ) {
$order = $this->get_parameter_order();
// Remove the offset from every group.
foreach ( $order as $type ) {
unset( $this->params[ $type ][ $offset ] );
}
}
/**
* Retrieves a WP_REST_Request object from a full URL.
*
* @since 4.5.0
*
* @param string $url URL with protocol, domain, path and query args.
* @return WP_REST_Request|false WP_REST_Request object on success, false on failure.
*/
public static function from_url( $url ) {
$bits = parse_url( $url );
$query_params = array();
if ( ! empty( $bits['query'] ) ) {
wp_parse_str( $bits['query'], $query_params );
}
$api_root = rest_url();
if ( get_option( 'permalink_structure' ) && 0 === strpos( $url, $api_root ) ) {
// Pretty permalinks on, and URL is under the API root.
$api_url_part = substr( $url, strlen( untrailingslashit( $api_root ) ) );
$route = parse_url( $api_url_part, PHP_URL_PATH );
} elseif ( ! empty( $query_params['rest_route'] ) ) {
// ?rest_route=... set directly.
$route = $query_params['rest_route'];
unset( $query_params['rest_route'] );
}
$request = false;
if ( ! empty( $route ) ) {
$request = new WP_REST_Request( 'GET', $route );
$request->set_query_params( $query_params );
}
/**
* Filters the REST API request generated from a URL.
*
* @since 4.5.0
*
* @param WP_REST_Request|false $request Generated request object, or false if URL
* could not be parsed.
* @param string $url URL the request was generated from.
*/
return apply_filters( 'rest_request_from_url', $request, $url );
}
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress class WP_Filesystem_ftpsockets {} class WP\_Filesystem\_ftpsockets {}
===================================
WordPress Filesystem Class for implementing FTP Sockets.
* [WP\_Filesystem\_Base](wp_filesystem_base)
* [\_\_construct](wp_filesystem_ftpsockets/__construct) — Constructor.
* [\_\_destruct](wp_filesystem_ftpsockets/__destruct) — Destructor.
* [atime](wp_filesystem_ftpsockets/atime) — Gets the file's last access time.
* [chdir](wp_filesystem_ftpsockets/chdir) — Changes current directory.
* [chmod](wp_filesystem_ftpsockets/chmod) — Changes filesystem permissions.
* [connect](wp_filesystem_ftpsockets/connect) — Connects filesystem.
* [copy](wp_filesystem_ftpsockets/copy) — Copies a file.
* [cwd](wp_filesystem_ftpsockets/cwd) — Gets the current working directory.
* [delete](wp_filesystem_ftpsockets/delete) — Deletes a file or directory.
* [dirlist](wp_filesystem_ftpsockets/dirlist) — Gets details for files in a directory or a specific file.
* [exists](wp_filesystem_ftpsockets/exists) — Checks if a file or directory exists.
* [get\_contents](wp_filesystem_ftpsockets/get_contents) — Reads entire file into a string.
* [get\_contents\_array](wp_filesystem_ftpsockets/get_contents_array) — Reads entire file into an array.
* [getchmod](wp_filesystem_ftpsockets/getchmod) — Gets the permissions of the specified file or filepath in their octal format.
* [group](wp_filesystem_ftpsockets/group) — Gets the file's group.
* [is\_dir](wp_filesystem_ftpsockets/is_dir) — Checks if resource is a directory.
* [is\_file](wp_filesystem_ftpsockets/is_file) — Checks if resource is a file.
* [is\_readable](wp_filesystem_ftpsockets/is_readable) — Checks if a file is readable.
* [is\_writable](wp_filesystem_ftpsockets/is_writable) — Checks if a file or directory is writable.
* [mkdir](wp_filesystem_ftpsockets/mkdir) — Creates a directory.
* [move](wp_filesystem_ftpsockets/move) — Moves a file.
* [mtime](wp_filesystem_ftpsockets/mtime) — Gets the file modification time.
* [owner](wp_filesystem_ftpsockets/owner) — Gets the file owner.
* [put\_contents](wp_filesystem_ftpsockets/put_contents) — Writes a string to a file.
* [rmdir](wp_filesystem_ftpsockets/rmdir) — Deletes a directory.
* [size](wp_filesystem_ftpsockets/size) — Gets the file size (in bytes).
* [touch](wp_filesystem_ftpsockets/touch) — Sets the access and modification times of a file.
File: `wp-admin/includes/class-wp-filesystem-ftpsockets.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-ftpsockets.php/)
```
class WP_Filesystem_ftpsockets extends WP_Filesystem_Base {
/**
* @since 2.5.0
* @var ftp
*/
public $ftp;
/**
* Constructor.
*
* @since 2.5.0
*
* @param array $opt
*/
public function __construct( $opt = '' ) {
$this->method = 'ftpsockets';
$this->errors = new WP_Error();
// Check if possible to use ftp functions.
if ( ! include_once ABSPATH . 'wp-admin/includes/class-ftp.php' ) {
return;
}
$this->ftp = new ftp();
if ( empty( $opt['port'] ) ) {
$this->options['port'] = 21;
} else {
$this->options['port'] = (int) $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'];
}
}
/**
* Connects filesystem.
*
* @since 2.5.0
*
* @return bool True on success, false on failure.
*/
public function connect() {
if ( ! $this->ftp ) {
return false;
}
$this->ftp->setTimeout( FS_CONNECT_TIMEOUT );
if ( ! $this->ftp->SetServer( $this->options['hostname'], $this->options['port'] ) ) {
$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 ( ! $this->ftp->connect() ) {
$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 ( ! $this->ftp->login( $this->options['username'], $this->options['password'] ) ) {
$this->errors->add(
'auth',
sprintf(
/* translators: %s: Username. */
__( 'Username/Password incorrect for %s' ),
$this->options['username']
)
);
return false;
}
$this->ftp->SetType( FTP_BINARY );
$this->ftp->Passive( true );
$this->ftp->setTimeout( 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 ) {
if ( ! $this->exists( $file ) ) {
return false;
}
$tempfile = wp_tempnam( $file );
$temphandle = fopen( $tempfile, 'w+' );
if ( ! $temphandle ) {
unlink( $tempfile );
return false;
}
mbstring_binary_safe_encoding();
if ( ! $this->ftp->fget( $temphandle, $file ) ) {
fclose( $temphandle );
unlink( $tempfile );
reset_mbstring_encoding();
return ''; // Blank document. File does exist, it's just blank.
}
reset_mbstring_encoding();
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, 'w+' );
if ( ! $temphandle ) {
unlink( $tempfile );
return false;
}
// The FTP class uses string functions internally during file download/upload.
mbstring_binary_safe_encoding();
$bytes_written = fwrite( $temphandle, $contents );
if ( false === $bytes_written || strlen( $contents ) !== $bytes_written ) {
fclose( $temphandle );
unlink( $tempfile );
reset_mbstring_encoding();
return false;
}
fseek( $temphandle, 0 ); // Skip back to the start of the file being written to.
$ret = $this->ftp->fput( $file, $temphandle );
reset_mbstring_encoding();
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 = $this->ftp->pwd();
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 $this->ftp->chdir( $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.
return $this->ftp->chmod( $file, $mode );
}
/**
* 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 $this->ftp->rename( $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 $this->ftp->delete( $file );
}
if ( ! $recursive ) {
return $this->ftp->rmdir( $file );
}
return $this->ftp->mdel( $file );
}
/**
* Checks if a file or directory exists.
*
* @since 2.5.0
* @since 6.1.0 Uses WP_Filesystem_ftpsockets::is_dir() to check for directory existence
* and file size 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 is_numeric( $this->size( $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 ) {
if ( $this->is_dir( $file ) ) {
return false;
}
if ( $this->exists( $file ) ) {
return true;
}
return false;
}
/**
* 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();
if ( $this->chdir( $path ) ) {
$this->chdir( $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 $this->ftp->mdtm( $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 $this->ftp->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 ) {
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 ( ! $this->ftp->mkdir( $path ) ) {
return false;
}
if ( ! $chmod ) {
$chmod = FS_CHMOD_DIR;
}
$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 );
}
/**
* 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;
}
mbstring_binary_safe_encoding();
$list = $this->ftp->dirlist( $path );
if ( empty( $list ) && ! $this->exists( $path ) ) {
reset_mbstring_encoding();
return false;
}
$ret = array();
foreach ( $list as $struc ) {
if ( '.' === $struc['name'] || '..' === $struc['name'] ) {
continue;
}
if ( ! $include_hidden && '.' === $struc['name'][0] ) {
continue;
}
if ( $limit_file && $struc['name'] !== $limit_file ) {
continue;
}
if ( 'd' === $struc['type'] ) {
if ( $recursive ) {
$struc['files'] = $this->dirlist( $path . '/' . $struc['name'], $include_hidden, $recursive );
} else {
$struc['files'] = array();
}
}
// Replace symlinks formatted as "source -> target" with just the source name.
if ( $struc['islink'] ) {
$struc['name'] = preg_replace( '/(\s*->\s*.*)$/', '', $struc['name'] );
}
// Add the octal representation of the file permissions.
$struc['permsn'] = $this->getnumchmodfromh( $struc['perms'] );
$ret[ $struc['name'] ] = $struc;
}
reset_mbstring_encoding();
return $ret;
}
/**
* Destructor.
*
* @since 2.5.0
*/
public function __destruct() {
$this->ftp->quit();
}
}
```
| 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. |
wordpress class WP_oEmbed_Controller {} class WP\_oEmbed\_Controller {}
===============================
oEmbed API endpoint controller.
Registers the REST API route and delivers the response data.
The output format (XML or JSON) is handled by the REST API.
* [get\_item](wp_oembed_controller/get_item) — Callback for the embed API endpoint.
* [get\_proxy\_item](wp_oembed_controller/get_proxy_item) — Callback for the proxy API endpoint.
* [get\_proxy\_item\_permissions\_check](wp_oembed_controller/get_proxy_item_permissions_check) — Checks if current user can make a proxy oEmbed request.
* [register\_routes](wp_oembed_controller/register_routes) — Register the oEmbed REST API route.
File: `wp-includes/class-wp-oembed-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-oembed-controller.php/)
```
final class WP_oEmbed_Controller {
/**
* Register the oEmbed REST API route.
*
* @since 4.4.0
*/
public function register_routes() {
/**
* Filters the maxwidth oEmbed parameter.
*
* @since 4.4.0
*
* @param int $maxwidth Maximum allowed width. Default 600.
*/
$maxwidth = apply_filters( 'oembed_default_width', 600 );
register_rest_route(
'oembed/1.0',
'/embed',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => '__return_true',
'args' => array(
'url' => array(
'description' => __( 'The URL of the resource for which to fetch oEmbed data.' ),
'required' => true,
'type' => 'string',
'format' => 'uri',
),
'format' => array(
'default' => 'json',
'sanitize_callback' => 'wp_oembed_ensure_format',
),
'maxwidth' => array(
'default' => $maxwidth,
'sanitize_callback' => 'absint',
),
),
),
)
);
register_rest_route(
'oembed/1.0',
'/proxy',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_proxy_item' ),
'permission_callback' => array( $this, 'get_proxy_item_permissions_check' ),
'args' => array(
'url' => array(
'description' => __( 'The URL of the resource for which to fetch oEmbed data.' ),
'required' => true,
'type' => 'string',
'format' => 'uri',
),
'format' => array(
'description' => __( 'The oEmbed format to use.' ),
'type' => 'string',
'default' => 'json',
'enum' => array(
'json',
'xml',
),
),
'maxwidth' => array(
'description' => __( 'The maximum width of the embed frame in pixels.' ),
'type' => 'integer',
'default' => $maxwidth,
'sanitize_callback' => 'absint',
),
'maxheight' => array(
'description' => __( 'The maximum height of the embed frame in pixels.' ),
'type' => 'integer',
'sanitize_callback' => 'absint',
),
'discover' => array(
'description' => __( 'Whether to perform an oEmbed discovery request for unsanctioned providers.' ),
'type' => 'boolean',
'default' => true,
),
),
),
)
);
}
/**
* Callback for the embed API endpoint.
*
* Returns the JSON object for the post.
*
* @since 4.4.0
*
* @param WP_REST_Request $request Full data about the request.
* @return array|WP_Error oEmbed response data or WP_Error on failure.
*/
public function get_item( $request ) {
$post_id = url_to_postid( $request['url'] );
/**
* Filters the determined post ID.
*
* @since 4.4.0
*
* @param int $post_id The post ID.
* @param string $url The requested URL.
*/
$post_id = apply_filters( 'oembed_request_post_id', $post_id, $request['url'] );
$data = get_oembed_response_data( $post_id, $request['maxwidth'] );
if ( ! $data ) {
return new WP_Error( 'oembed_invalid_url', get_status_header_desc( 404 ), array( 'status' => 404 ) );
}
return $data;
}
/**
* Checks if current user can make a proxy oEmbed request.
*
* @since 4.8.0
*
* @return true|WP_Error True if the request has read access, WP_Error object otherwise.
*/
public function get_proxy_item_permissions_check() {
if ( ! current_user_can( 'edit_posts' ) ) {
return new WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to make proxied oEmbed requests.' ), array( 'status' => rest_authorization_required_code() ) );
}
return true;
}
/**
* Callback for the proxy API endpoint.
*
* Returns the JSON object for the proxied item.
*
* @since 4.8.0
*
* @see WP_oEmbed::get_html()
* @global WP_Embed $wp_embed
*
* @param WP_REST_Request $request Full data about the request.
* @return object|WP_Error oEmbed response data or WP_Error on failure.
*/
public function get_proxy_item( $request ) {
global $wp_embed;
$args = $request->get_params();
// Serve oEmbed data from cache if set.
unset( $args['_wpnonce'] );
$cache_key = 'oembed_' . md5( serialize( $args ) );
$data = get_transient( $cache_key );
if ( ! empty( $data ) ) {
return $data;
}
$url = $request['url'];
unset( $args['url'] );
// Copy maxwidth/maxheight to width/height since WP_oEmbed::fetch() uses these arg names.
if ( isset( $args['maxwidth'] ) ) {
$args['width'] = $args['maxwidth'];
}
if ( isset( $args['maxheight'] ) ) {
$args['height'] = $args['maxheight'];
}
// Short-circuit process for URLs belonging to the current site.
$data = get_oembed_response_data_for_url( $url, $args );
if ( $data ) {
return $data;
}
$data = _wp_oembed_get_object()->get_data( $url, $args );
if ( false === $data ) {
// Try using a classic embed, instead.
/* @var WP_Embed $wp_embed */
$html = $wp_embed->get_embed_handler_html( $args, $url );
if ( $html ) {
global $wp_scripts;
// Check if any scripts were enqueued by the shortcode, and include them in the response.
$enqueued_scripts = array();
foreach ( $wp_scripts->queue as $script ) {
$enqueued_scripts[] = $wp_scripts->registered[ $script ]->src;
}
return (object) array(
'provider_name' => __( 'Embed Handler' ),
'html' => $html,
'scripts' => $enqueued_scripts,
);
}
return new WP_Error( 'oembed_invalid_url', get_status_header_desc( 404 ), array( 'status' => 404 ) );
}
/** This filter is documented in wp-includes/class-wp-oembed.php */
$data->html = apply_filters( 'oembed_result', _wp_oembed_get_object()->data2html( (object) $data, $url ), $url, $args );
/**
* Filters the oEmbed TTL value (time to live).
*
* Similar to the {@see 'oembed_ttl'} filter, but for the REST API
* oEmbed proxy endpoint.
*
* @since 4.8.0
*
* @param int $time Time to live (in seconds).
* @param string $url The attempted embed URL.
* @param array $args An array of embed request arguments.
*/
$ttl = apply_filters( 'rest_oembed_ttl', DAY_IN_SECONDS, $url, $args );
set_transient( $cache_key, $data, $ttl );
return $data;
}
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress class _WP_Editors {} class \_WP\_Editors {}
======================
Facilitates adding of the WordPress editor as used on the Write and Edit screens.
* [\_\_construct](_wp_editors/__construct)
* [\_parse\_init](_wp_editors/_parse_init)
* [default\_settings](_wp_editors/default_settings) — Returns the default TinyMCE settings.
* [editor](_wp_editors/editor) — Outputs the HTML for a single instance of the editor.
* [editor\_js](_wp_editors/editor_js) — Print (output) the TinyMCE configuration and initialization scripts.
* [editor\_settings](_wp_editors/editor_settings)
* [enqueue\_default\_editor](_wp_editors/enqueue_default_editor) — Enqueue all editor scripts.
* [enqueue\_scripts](_wp_editors/enqueue_scripts)
* [force\_uncompressed\_tinymce](_wp_editors/force_uncompressed_tinymce) — Force uncompressed TinyMCE when a custom theme has been defined.
* [get\_baseurl](_wp_editors/get_baseurl) — Returns the TinyMCE base URL.
* [get\_mce\_locale](_wp_editors/get_mce_locale) — Returns the TinyMCE locale.
* [get\_translation](_wp_editors/get_translation)
* [parse\_settings](_wp_editors/parse_settings) — Parse default arguments for the editor instance.
* [print\_default\_editor\_scripts](_wp_editors/print_default_editor_scripts) — Print (output) all editor scripts and default settings.
* [print\_tinymce\_scripts](_wp_editors/print_tinymce_scripts) — Print (output) the main TinyMCE scripts.
* [wp\_fullscreen\_html](_wp_editors/wp_fullscreen_html) — Outputs the HTML for distraction-free writing mode. — deprecated
* [wp\_link\_dialog](_wp_editors/wp_link_dialog) — Dialog for internal linking.
* [wp\_link\_query](_wp_editors/wp_link_query) — Performs post queries for internal linking.
* [wp\_mce\_translation](_wp_editors/wp_mce_translation) — Translates the default TinyMCE strings and returns them as JSON encoded object ready to be loaded with tinymce.addI18n(), or as JS snippet that should run after tinymce.js is loaded.
File: `wp-includes/class-wp-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-editor.php/)
```
final class _WP_Editors {
public static $mce_locale;
private static $mce_settings = array();
private static $qt_settings = array();
private static $plugins = array();
private static $qt_buttons = array();
private static $ext_plugins;
private static $baseurl;
private static $first_init;
private static $this_tinymce = false;
private static $this_quicktags = false;
private static $has_tinymce = false;
private static $has_quicktags = false;
private static $has_medialib = false;
private static $editor_buttons_css = true;
private static $drag_drop_upload = false;
private static $translation;
private static $tinymce_scripts_printed = false;
private static $link_dialog_printed = false;
private function __construct() {}
/**
* Parse default arguments for the editor instance.
*
* @since 3.3.0
*
* @param string $editor_id HTML ID for the textarea and TinyMCE and Quicktags instances.
* Should not contain square brackets.
* @param array $settings {
* Array of editor arguments.
*
* @type bool $wpautop Whether to use wpautop(). Default true.
* @type bool $media_buttons Whether to show the Add Media/other media buttons.
* @type string $default_editor When both TinyMCE and Quicktags are used, set which
* editor is shown on page load. Default empty.
* @type bool $drag_drop_upload Whether to enable drag & drop on the editor uploading. Default false.
* Requires the media modal.
* @type string $textarea_name Give the textarea a unique name here. Square brackets
* can be used here. Default $editor_id.
* @type int $textarea_rows Number rows in the editor textarea. Default 20.
* @type string|int $tabindex Tabindex value to use. Default empty.
* @type string $tabfocus_elements The previous and next element ID to move the focus to
* when pressing the Tab key in TinyMCE. Default ':prev,:next'.
* @type string $editor_css Intended for extra styles for both Visual and Text editors.
* Should include `<style>` tags, and can use "scoped". Default empty.
* @type string $editor_class Extra classes to add to the editor textarea element. Default empty.
* @type bool $teeny Whether to output the minimal editor config. Examples include
* Press This and the Comment editor. Default false.
* @type bool $dfw Deprecated in 4.1. Unused.
* @type bool|array $tinymce Whether to load TinyMCE. Can be used to pass settings directly to
* TinyMCE using an array. Default true.
* @type bool|array $quicktags Whether to load Quicktags. Can be used to pass settings directly to
* Quicktags using an array. Default true.
* }
* @return array Parsed arguments array.
*/
public static function parse_settings( $editor_id, $settings ) {
/**
* Filters the wp_editor() settings.
*
* @since 4.0.0
*
* @see _WP_Editors::parse_settings()
*
* @param array $settings Array of editor arguments.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$settings = apply_filters( 'wp_editor_settings', $settings, $editor_id );
$set = wp_parse_args(
$settings,
array(
// Disable autop if the current post has blocks in it.
'wpautop' => ! has_blocks(),
'media_buttons' => true,
'default_editor' => '',
'drag_drop_upload' => false,
'textarea_name' => $editor_id,
'textarea_rows' => 20,
'tabindex' => '',
'tabfocus_elements' => ':prev,:next',
'editor_css' => '',
'editor_class' => '',
'teeny' => false,
'_content_editor_dfw' => false,
'tinymce' => true,
'quicktags' => true,
)
);
self::$this_tinymce = ( $set['tinymce'] && user_can_richedit() );
if ( self::$this_tinymce ) {
if ( false !== strpos( $editor_id, '[' ) ) {
self::$this_tinymce = false;
_deprecated_argument( 'wp_editor()', '3.9.0', 'TinyMCE editor IDs cannot have brackets.' );
}
}
self::$this_quicktags = (bool) $set['quicktags'];
if ( self::$this_tinymce ) {
self::$has_tinymce = true;
}
if ( self::$this_quicktags ) {
self::$has_quicktags = true;
}
if ( empty( $set['editor_height'] ) ) {
return $set;
}
if ( 'content' === $editor_id && empty( $set['tinymce']['wp_autoresize_on'] ) ) {
// A cookie (set when a user resizes the editor) overrides the height.
$cookie = (int) get_user_setting( 'ed_size' );
if ( $cookie ) {
$set['editor_height'] = $cookie;
}
}
if ( $set['editor_height'] < 50 ) {
$set['editor_height'] = 50;
} elseif ( $set['editor_height'] > 5000 ) {
$set['editor_height'] = 5000;
}
return $set;
}
/**
* Outputs the HTML for a single instance of the editor.
*
* @since 3.3.0
*
* @param string $content Initial content for the editor.
* @param string $editor_id HTML ID for the textarea and TinyMCE and Quicktags instances.
* Should not contain square brackets.
* @param array $settings See _WP_Editors::parse_settings() for description.
*/
public static function editor( $content, $editor_id, $settings = array() ) {
$set = self::parse_settings( $editor_id, $settings );
$editor_class = ' class="' . trim( esc_attr( $set['editor_class'] ) . ' wp-editor-area' ) . '"';
$tabindex = $set['tabindex'] ? ' tabindex="' . (int) $set['tabindex'] . '"' : '';
$default_editor = 'html';
$buttons = '';
$autocomplete = '';
$editor_id_attr = esc_attr( $editor_id );
if ( $set['drag_drop_upload'] ) {
self::$drag_drop_upload = true;
}
if ( ! empty( $set['editor_height'] ) ) {
$height = ' style="height: ' . (int) $set['editor_height'] . 'px"';
} else {
$height = ' rows="' . (int) $set['textarea_rows'] . '"';
}
if ( ! current_user_can( 'upload_files' ) ) {
$set['media_buttons'] = false;
}
if ( self::$this_tinymce ) {
$autocomplete = ' autocomplete="off"';
if ( self::$this_quicktags ) {
$default_editor = $set['default_editor'] ? $set['default_editor'] : wp_default_editor();
// 'html' is used for the "Text" editor tab.
if ( 'html' !== $default_editor ) {
$default_editor = 'tinymce';
}
$buttons .= '<button type="button" id="' . $editor_id_attr . '-tmce" class="wp-switch-editor switch-tmce"' .
' data-wp-editor-id="' . $editor_id_attr . '">' . _x( 'Visual', 'Name for the Visual editor tab' ) . "</button>\n";
$buttons .= '<button type="button" id="' . $editor_id_attr . '-html" class="wp-switch-editor switch-html"' .
' data-wp-editor-id="' . $editor_id_attr . '">' . _x( 'Text', 'Name for the Text editor tab (formerly HTML)' ) . "</button>\n";
} else {
$default_editor = 'tinymce';
}
}
$switch_class = 'html' === $default_editor ? 'html-active' : 'tmce-active';
$wrap_class = 'wp-core-ui wp-editor-wrap ' . $switch_class;
if ( $set['_content_editor_dfw'] ) {
$wrap_class .= ' has-dfw';
}
echo '<div id="wp-' . $editor_id_attr . '-wrap" class="' . $wrap_class . '">';
if ( self::$editor_buttons_css ) {
wp_print_styles( 'editor-buttons' );
self::$editor_buttons_css = false;
}
if ( ! empty( $set['editor_css'] ) ) {
echo $set['editor_css'] . "\n";
}
if ( ! empty( $buttons ) || $set['media_buttons'] ) {
echo '<div id="wp-' . $editor_id_attr . '-editor-tools" class="wp-editor-tools hide-if-no-js">';
if ( $set['media_buttons'] ) {
self::$has_medialib = true;
if ( ! function_exists( 'media_buttons' ) ) {
require ABSPATH . 'wp-admin/includes/media.php';
}
echo '<div id="wp-' . $editor_id_attr . '-media-buttons" class="wp-media-buttons">';
/**
* Fires after the default media button(s) are displayed.
*
* @since 2.5.0
*
* @param string $editor_id Unique editor identifier, e.g. 'content'.
*/
do_action( 'media_buttons', $editor_id );
echo "</div>\n";
}
echo '<div class="wp-editor-tabs">' . $buttons . "</div>\n";
echo "</div>\n";
}
$quicktags_toolbar = '';
if ( self::$this_quicktags ) {
if ( 'content' === $editor_id && ! empty( $GLOBALS['current_screen'] ) && 'post' === $GLOBALS['current_screen']->base ) {
$toolbar_id = 'ed_toolbar';
} else {
$toolbar_id = 'qt_' . $editor_id_attr . '_toolbar';
}
$quicktags_toolbar = '<div id="' . $toolbar_id . '" class="quicktags-toolbar hide-if-no-js"></div>';
}
/**
* Filters the HTML markup output that displays the editor.
*
* @since 2.1.0
*
* @param string $output Editor's HTML markup.
*/
$the_editor = apply_filters(
'the_editor',
'<div id="wp-' . $editor_id_attr . '-editor-container" class="wp-editor-container">' .
$quicktags_toolbar .
'<textarea' . $editor_class . $height . $tabindex . $autocomplete . ' cols="40" name="' . esc_attr( $set['textarea_name'] ) . '" ' .
'id="' . $editor_id_attr . '">%s</textarea></div>'
);
// Prepare the content for the Visual or Text editor, only when TinyMCE is used (back-compat).
if ( self::$this_tinymce ) {
add_filter( 'the_editor_content', 'format_for_editor', 10, 2 );
}
/**
* Filters the default editor content.
*
* @since 2.1.0
*
* @param string $content Default editor content.
* @param string $default_editor The default editor for the current user.
* Either 'html' or 'tinymce'.
*/
$content = apply_filters( 'the_editor_content', $content, $default_editor );
// Remove the filter as the next editor on the same page may not need it.
if ( self::$this_tinymce ) {
remove_filter( 'the_editor_content', 'format_for_editor' );
}
// Back-compat for the `htmledit_pre` and `richedit_pre` filters.
if ( 'html' === $default_editor && has_filter( 'htmledit_pre' ) ) {
/** This filter is documented in wp-includes/deprecated.php */
$content = apply_filters_deprecated( 'htmledit_pre', array( $content ), '4.3.0', 'format_for_editor' );
} elseif ( 'tinymce' === $default_editor && has_filter( 'richedit_pre' ) ) {
/** This filter is documented in wp-includes/deprecated.php */
$content = apply_filters_deprecated( 'richedit_pre', array( $content ), '4.3.0', 'format_for_editor' );
}
if ( false !== stripos( $content, 'textarea' ) ) {
$content = preg_replace( '%</textarea%i', '</textarea', $content );
}
printf( $the_editor, $content );
echo "\n</div>\n\n";
self::editor_settings( $editor_id, $set );
}
/**
* @since 3.3.0
*
* @param string $editor_id Unique editor identifier, e.g. 'content'.
* @param array $set Array of editor arguments.
*/
public static function editor_settings( $editor_id, $set ) {
if ( empty( self::$first_init ) ) {
if ( is_admin() ) {
add_action( 'admin_print_footer_scripts', array( __CLASS__, 'editor_js' ), 50 );
add_action( 'admin_print_footer_scripts', array( __CLASS__, 'force_uncompressed_tinymce' ), 1 );
add_action( 'admin_print_footer_scripts', array( __CLASS__, 'enqueue_scripts' ), 1 );
} else {
add_action( 'wp_print_footer_scripts', array( __CLASS__, 'editor_js' ), 50 );
add_action( 'wp_print_footer_scripts', array( __CLASS__, 'force_uncompressed_tinymce' ), 1 );
add_action( 'wp_print_footer_scripts', array( __CLASS__, 'enqueue_scripts' ), 1 );
}
}
if ( self::$this_quicktags ) {
$qtInit = array(
'id' => $editor_id,
'buttons' => '',
);
if ( is_array( $set['quicktags'] ) ) {
$qtInit = array_merge( $qtInit, $set['quicktags'] );
}
if ( empty( $qtInit['buttons'] ) ) {
$qtInit['buttons'] = 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,close';
}
if ( $set['_content_editor_dfw'] ) {
$qtInit['buttons'] .= ',dfw';
}
/**
* Filters the Quicktags settings.
*
* @since 3.3.0
*
* @param array $qtInit Quicktags settings.
* @param string $editor_id Unique editor identifier, e.g. 'content'.
*/
$qtInit = apply_filters( 'quicktags_settings', $qtInit, $editor_id );
self::$qt_settings[ $editor_id ] = $qtInit;
self::$qt_buttons = array_merge( self::$qt_buttons, explode( ',', $qtInit['buttons'] ) );
}
if ( self::$this_tinymce ) {
if ( empty( self::$first_init ) ) {
$baseurl = self::get_baseurl();
$mce_locale = self::get_mce_locale();
$ext_plugins = '';
if ( $set['teeny'] ) {
/**
* Filters the list of teenyMCE plugins.
*
* @since 2.7.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $plugins An array of teenyMCE plugins.
* @param string $editor_id Unique editor identifier, e.g. 'content'.
*/
$plugins = apply_filters(
'teeny_mce_plugins',
array(
'colorpicker',
'lists',
'fullscreen',
'image',
'wordpress',
'wpeditimage',
'wplink',
),
$editor_id
);
} else {
/**
* Filters the list of TinyMCE external plugins.
*
* The filter takes an associative array of external plugins for
* TinyMCE in the form 'plugin_name' => 'url'.
*
* The url should be absolute, and should include the js filename
* to be loaded. For example:
* 'myplugin' => 'http://mysite.com/wp-content/plugins/myfolder/mce_plugin.js'.
*
* If the external plugin adds a button, it should be added with
* one of the 'mce_buttons' filters.
*
* @since 2.5.0
* @since 5.3.0 The `$editor_id` parameter was added.
*
* @param array $external_plugins An array of external TinyMCE plugins.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$mce_external_plugins = apply_filters( 'mce_external_plugins', array(), $editor_id );
$plugins = array(
'charmap',
'colorpicker',
'hr',
'lists',
'media',
'paste',
'tabfocus',
'textcolor',
'fullscreen',
'wordpress',
'wpautoresize',
'wpeditimage',
'wpemoji',
'wpgallery',
'wplink',
'wpdialogs',
'wptextpattern',
'wpview',
);
if ( ! self::$has_medialib ) {
$plugins[] = 'image';
}
/**
* Filters the list of default TinyMCE plugins.
*
* The filter specifies which of the default plugins included
* in WordPress should be added to the TinyMCE instance.
*
* @since 3.3.0
* @since 5.3.0 The `$editor_id` parameter was added.
*
* @param array $plugins An array of default TinyMCE plugins.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$plugins = array_unique( apply_filters( 'tiny_mce_plugins', $plugins, $editor_id ) );
$key = array_search( 'spellchecker', $plugins, true );
if ( false !== $key ) {
// Remove 'spellchecker' from the internal plugins if added with 'tiny_mce_plugins' filter to prevent errors.
// It can be added with 'mce_external_plugins'.
unset( $plugins[ $key ] );
}
if ( ! empty( $mce_external_plugins ) ) {
/**
* Filters the translations loaded for external TinyMCE 3.x plugins.
*
* The filter takes an associative array ('plugin_name' => 'path')
* where 'path' is the include path to the file.
*
* The language file should follow the same format as wp_mce_translation(),
* and should define a variable ($strings) that holds all translated strings.
*
* @since 2.5.0
* @since 5.3.0 The `$editor_id` parameter was added.
*
* @param array $translations Translations for external TinyMCE plugins.
* @param string $editor_id Unique editor identifier, e.g. 'content'.
*/
$mce_external_languages = apply_filters( 'mce_external_languages', array(), $editor_id );
$loaded_langs = array();
$strings = '';
if ( ! empty( $mce_external_languages ) ) {
foreach ( $mce_external_languages as $name => $path ) {
if ( @is_file( $path ) && @is_readable( $path ) ) {
include_once $path;
$ext_plugins .= $strings . "\n";
$loaded_langs[] = $name;
}
}
}
foreach ( $mce_external_plugins as $name => $url ) {
if ( in_array( $name, $plugins, true ) ) {
unset( $mce_external_plugins[ $name ] );
continue;
}
$url = set_url_scheme( $url );
$mce_external_plugins[ $name ] = $url;
$plugurl = dirname( $url );
$strings = '';
// Try to load langs/[locale].js and langs/[locale]_dlg.js.
if ( ! in_array( $name, $loaded_langs, true ) ) {
$path = str_replace( content_url(), '', $plugurl );
$path = WP_CONTENT_DIR . $path . '/langs/';
$path = trailingslashit( realpath( $path ) );
if ( @is_file( $path . $mce_locale . '.js' ) ) {
$strings .= @file_get_contents( $path . $mce_locale . '.js' ) . "\n";
}
if ( @is_file( $path . $mce_locale . '_dlg.js' ) ) {
$strings .= @file_get_contents( $path . $mce_locale . '_dlg.js' ) . "\n";
}
if ( 'en' !== $mce_locale && empty( $strings ) ) {
if ( @is_file( $path . 'en.js' ) ) {
$str1 = @file_get_contents( $path . 'en.js' );
$strings .= preg_replace( '/([\'"])en\./', '$1' . $mce_locale . '.', $str1, 1 ) . "\n";
}
if ( @is_file( $path . 'en_dlg.js' ) ) {
$str2 = @file_get_contents( $path . 'en_dlg.js' );
$strings .= preg_replace( '/([\'"])en\./', '$1' . $mce_locale . '.', $str2, 1 ) . "\n";
}
}
if ( ! empty( $strings ) ) {
$ext_plugins .= "\n" . $strings . "\n";
}
}
$ext_plugins .= 'tinyMCEPreInit.load_ext("' . $plugurl . '", "' . $mce_locale . '");' . "\n";
}
}
}
self::$plugins = $plugins;
self::$ext_plugins = $ext_plugins;
$settings = self::default_settings();
$settings['plugins'] = implode( ',', $plugins );
if ( ! empty( $mce_external_plugins ) ) {
$settings['external_plugins'] = wp_json_encode( $mce_external_plugins );
}
/** This filter is documented in wp-admin/includes/media.php */
if ( apply_filters( 'disable_captions', '' ) ) {
$settings['wpeditimage_disable_captions'] = true;
}
$mce_css = $settings['content_css'];
/*
* The `editor-style.css` added by the theme is generally intended for the editor instance on the Edit Post screen.
* Plugins that use wp_editor() on the front-end can decide whether to add the theme stylesheet
* by using `get_editor_stylesheets()` and the `mce_css` or `tiny_mce_before_init` filters, see below.
*/
if ( is_admin() ) {
$editor_styles = get_editor_stylesheets();
if ( ! empty( $editor_styles ) ) {
// Force urlencoding of commas.
foreach ( $editor_styles as $key => $url ) {
if ( strpos( $url, ',' ) !== false ) {
$editor_styles[ $key ] = str_replace( ',', '%2C', $url );
}
}
$mce_css .= ',' . implode( ',', $editor_styles );
}
}
/**
* Filters the comma-delimited list of stylesheets to load in TinyMCE.
*
* @since 2.1.0
*
* @param string $stylesheets Comma-delimited list of stylesheets.
*/
$mce_css = trim( apply_filters( 'mce_css', $mce_css ), ' ,' );
if ( ! empty( $mce_css ) ) {
$settings['content_css'] = $mce_css;
} else {
unset( $settings['content_css'] );
}
self::$first_init = $settings;
}
if ( $set['teeny'] ) {
$mce_buttons = array(
'bold',
'italic',
'underline',
'blockquote',
'strikethrough',
'bullist',
'numlist',
'alignleft',
'aligncenter',
'alignright',
'undo',
'redo',
'link',
'fullscreen',
);
/**
* Filters the list of teenyMCE buttons (Text tab).
*
* @since 2.7.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $mce_buttons An array of teenyMCE buttons.
* @param string $editor_id Unique editor identifier, e.g. 'content'.
*/
$mce_buttons = apply_filters( 'teeny_mce_buttons', $mce_buttons, $editor_id );
$mce_buttons_2 = array();
$mce_buttons_3 = array();
$mce_buttons_4 = array();
} else {
$mce_buttons = array(
'formatselect',
'bold',
'italic',
'bullist',
'numlist',
'blockquote',
'alignleft',
'aligncenter',
'alignright',
'link',
'wp_more',
'spellchecker',
);
if ( ! wp_is_mobile() ) {
if ( $set['_content_editor_dfw'] ) {
$mce_buttons[] = 'wp_adv';
$mce_buttons[] = 'dfw';
} else {
$mce_buttons[] = 'fullscreen';
$mce_buttons[] = 'wp_adv';
}
} else {
$mce_buttons[] = 'wp_adv';
}
/**
* Filters the first-row list of TinyMCE buttons (Visual tab).
*
* @since 2.0.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $mce_buttons First-row list of buttons.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$mce_buttons = apply_filters( 'mce_buttons', $mce_buttons, $editor_id );
$mce_buttons_2 = array(
'strikethrough',
'hr',
'forecolor',
'pastetext',
'removeformat',
'charmap',
'outdent',
'indent',
'undo',
'redo',
);
if ( ! wp_is_mobile() ) {
$mce_buttons_2[] = 'wp_help';
}
/**
* Filters the second-row list of TinyMCE buttons (Visual tab).
*
* @since 2.0.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $mce_buttons_2 Second-row list of buttons.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$mce_buttons_2 = apply_filters( 'mce_buttons_2', $mce_buttons_2, $editor_id );
/**
* Filters the third-row list of TinyMCE buttons (Visual tab).
*
* @since 2.0.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $mce_buttons_3 Third-row list of buttons.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$mce_buttons_3 = apply_filters( 'mce_buttons_3', array(), $editor_id );
/**
* Filters the fourth-row list of TinyMCE buttons (Visual tab).
*
* @since 2.5.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $mce_buttons_4 Fourth-row list of buttons.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$mce_buttons_4 = apply_filters( 'mce_buttons_4', array(), $editor_id );
}
$body_class = $editor_id;
$post = get_post();
if ( $post ) {
$body_class .= ' post-type-' . sanitize_html_class( $post->post_type ) . ' post-status-' . sanitize_html_class( $post->post_status );
if ( post_type_supports( $post->post_type, 'post-formats' ) ) {
$post_format = get_post_format( $post );
if ( $post_format && ! is_wp_error( $post_format ) ) {
$body_class .= ' post-format-' . sanitize_html_class( $post_format );
} else {
$body_class .= ' post-format-standard';
}
}
$page_template = get_page_template_slug( $post );
if ( false !== $page_template ) {
$page_template = empty( $page_template ) ? 'default' : str_replace( '.', '-', basename( $page_template, '.php' ) );
$body_class .= ' page-template-' . sanitize_html_class( $page_template );
}
}
$body_class .= ' locale-' . sanitize_html_class( strtolower( str_replace( '_', '-', get_user_locale() ) ) );
if ( ! empty( $set['tinymce']['body_class'] ) ) {
$body_class .= ' ' . $set['tinymce']['body_class'];
unset( $set['tinymce']['body_class'] );
}
$mceInit = array(
'selector' => "#$editor_id",
'wpautop' => (bool) $set['wpautop'],
'indent' => ! $set['wpautop'],
'toolbar1' => implode( ',', $mce_buttons ),
'toolbar2' => implode( ',', $mce_buttons_2 ),
'toolbar3' => implode( ',', $mce_buttons_3 ),
'toolbar4' => implode( ',', $mce_buttons_4 ),
'tabfocus_elements' => $set['tabfocus_elements'],
'body_class' => $body_class,
);
// Merge with the first part of the init array.
$mceInit = array_merge( self::$first_init, $mceInit );
if ( is_array( $set['tinymce'] ) ) {
$mceInit = array_merge( $mceInit, $set['tinymce'] );
}
/*
* For people who really REALLY know what they're doing with TinyMCE
* You can modify $mceInit to add, remove, change elements of the config
* before tinyMCE.init. Setting "valid_elements", "invalid_elements"
* and "extended_valid_elements" can be done through this filter. Best
* is to use the default cleanup by not specifying valid_elements,
* as TinyMCE checks against the full set of HTML 5.0 elements and attributes.
*/
if ( $set['teeny'] ) {
/**
* Filters the teenyMCE config before init.
*
* @since 2.7.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $mceInit An array with teenyMCE config.
* @param string $editor_id Unique editor identifier, e.g. 'content'.
*/
$mceInit = apply_filters( 'teeny_mce_before_init', $mceInit, $editor_id );
} else {
/**
* Filters the TinyMCE config before init.
*
* @since 2.5.0
* @since 3.3.0 The `$editor_id` parameter was added.
*
* @param array $mceInit An array with TinyMCE config.
* @param string $editor_id Unique editor identifier, e.g. 'content'. Accepts 'classic-block'
* when called from block editor's Classic block.
*/
$mceInit = apply_filters( 'tiny_mce_before_init', $mceInit, $editor_id );
}
if ( empty( $mceInit['toolbar3'] ) && ! empty( $mceInit['toolbar4'] ) ) {
$mceInit['toolbar3'] = $mceInit['toolbar4'];
$mceInit['toolbar4'] = '';
}
self::$mce_settings[ $editor_id ] = $mceInit;
} // End if self::$this_tinymce.
}
/**
* @since 3.3.0
*
* @param array $init
* @return string
*/
private static function _parse_init( $init ) {
$options = '';
foreach ( $init as $key => $value ) {
if ( is_bool( $value ) ) {
$val = $value ? 'true' : 'false';
$options .= $key . ':' . $val . ',';
continue;
} elseif ( ! empty( $value ) && is_string( $value ) && (
( '{' === $value[0] && '}' === $value[ strlen( $value ) - 1 ] ) ||
( '[' === $value[0] && ']' === $value[ strlen( $value ) - 1 ] ) ||
preg_match( '/^\(?function ?\(/', $value ) ) ) {
$options .= $key . ':' . $value . ',';
continue;
}
$options .= $key . ':"' . $value . '",';
}
return '{' . trim( $options, ' ,' ) . '}';
}
/**
* @since 3.3.0
*
* @param bool $default_scripts Optional. Whether default scripts should be enqueued. Default false.
*/
public static function enqueue_scripts( $default_scripts = false ) {
if ( $default_scripts || self::$has_tinymce ) {
wp_enqueue_script( 'editor' );
}
if ( $default_scripts || self::$has_quicktags ) {
wp_enqueue_script( 'quicktags' );
wp_enqueue_style( 'buttons' );
}
if ( $default_scripts || in_array( 'wplink', self::$plugins, true ) || in_array( 'link', self::$qt_buttons, true ) ) {
wp_enqueue_script( 'wplink' );
wp_enqueue_script( 'jquery-ui-autocomplete' );
}
if ( self::$has_medialib ) {
add_thickbox();
wp_enqueue_script( 'media-upload' );
wp_enqueue_script( 'wp-embed' );
} elseif ( $default_scripts ) {
wp_enqueue_script( 'media-upload' );
}
/**
* Fires when scripts and styles are enqueued for the editor.
*
* @since 3.9.0
*
* @param array $to_load An array containing boolean values whether TinyMCE
* and Quicktags are being loaded.
*/
do_action(
'wp_enqueue_editor',
array(
'tinymce' => ( $default_scripts || self::$has_tinymce ),
'quicktags' => ( $default_scripts || self::$has_quicktags ),
)
);
}
/**
* Enqueue all editor scripts.
* For use when the editor is going to be initialized after page load.
*
* @since 4.8.0
*/
public static function enqueue_default_editor() {
// We are past the point where scripts can be enqueued properly.
if ( did_action( 'wp_enqueue_editor' ) ) {
return;
}
self::enqueue_scripts( true );
// Also add wp-includes/css/editor.css.
wp_enqueue_style( 'editor-buttons' );
if ( is_admin() ) {
add_action( 'admin_print_footer_scripts', array( __CLASS__, 'force_uncompressed_tinymce' ), 1 );
add_action( 'admin_print_footer_scripts', array( __CLASS__, 'print_default_editor_scripts' ), 45 );
} else {
add_action( 'wp_print_footer_scripts', array( __CLASS__, 'force_uncompressed_tinymce' ), 1 );
add_action( 'wp_print_footer_scripts', array( __CLASS__, 'print_default_editor_scripts' ), 45 );
}
}
/**
* Print (output) all editor scripts and default settings.
* For use when the editor is going to be initialized after page load.
*
* @since 4.8.0
*/
public static function print_default_editor_scripts() {
$user_can_richedit = user_can_richedit();
if ( $user_can_richedit ) {
$settings = self::default_settings();
$settings['toolbar1'] = 'bold,italic,bullist,numlist,link';
$settings['wpautop'] = false;
$settings['indent'] = true;
$settings['elementpath'] = false;
if ( is_rtl() ) {
$settings['directionality'] = 'rtl';
}
/*
* In production all plugins are loaded (they are in wp-editor.js.gz).
* The 'wpview', 'wpdialogs', and 'media' TinyMCE plugins are not initialized by default.
* Can be added from js by using the 'wp-before-tinymce-init' event.
*/
$settings['plugins'] = implode(
',',
array(
'charmap',
'colorpicker',
'hr',
'lists',
'paste',
'tabfocus',
'textcolor',
'fullscreen',
'wordpress',
'wpautoresize',
'wpeditimage',
'wpemoji',
'wpgallery',
'wplink',
'wptextpattern',
)
);
$settings = self::_parse_init( $settings );
} else {
$settings = '{}';
}
?>
<script type="text/javascript">
window.wp = window.wp || {};
window.wp.editor = window.wp.editor || {};
window.wp.editor.getDefaultSettings = function() {
return {
tinymce: <?php echo $settings; ?>,
quicktags: {
buttons: 'strong,em,link,ul,ol,li,code'
}
};
};
<?php
if ( $user_can_richedit ) {
$suffix = SCRIPT_DEBUG ? '' : '.min';
$baseurl = self::get_baseurl();
?>
var tinyMCEPreInit = {
baseURL: "<?php echo $baseurl; ?>",
suffix: "<?php echo $suffix; ?>",
mceInit: {},
qtInit: {},
load_ext: function(url,lang){var sl=tinymce.ScriptLoader;sl.markDone(url+'/langs/'+lang+'.js');sl.markDone(url+'/langs/'+lang+'_dlg.js');}
};
<?php
}
?>
</script>
<?php
if ( $user_can_richedit ) {
self::print_tinymce_scripts();
}
/**
* Fires when the editor scripts are loaded for later initialization,
* after all scripts and settings are printed.
*
* @since 4.8.0
*/
do_action( 'print_default_editor_scripts' );
self::wp_link_dialog();
}
/**
* Returns the TinyMCE locale.
*
* @since 4.8.0
*
* @return string
*/
public static function get_mce_locale() {
if ( empty( self::$mce_locale ) ) {
$mce_locale = get_user_locale();
self::$mce_locale = empty( $mce_locale ) ? 'en' : strtolower( substr( $mce_locale, 0, 2 ) ); // ISO 639-1.
}
return self::$mce_locale;
}
/**
* Returns the TinyMCE base URL.
*
* @since 4.8.0
*
* @return string
*/
public static function get_baseurl() {
if ( empty( self::$baseurl ) ) {
self::$baseurl = includes_url( 'js/tinymce' );
}
return self::$baseurl;
}
/**
* Returns the default TinyMCE settings.
* Doesn't include plugins, buttons, editor selector.
*
* @since 4.8.0
*
* @global string $tinymce_version
*
* @return array
*/
private static function default_settings() {
global $tinymce_version;
$shortcut_labels = array();
foreach ( self::get_translation() as $name => $value ) {
if ( is_array( $value ) ) {
$shortcut_labels[ $name ] = $value[1];
}
}
$settings = array(
'theme' => 'modern',
'skin' => 'lightgray',
'language' => self::get_mce_locale(),
'formats' => '{' .
'alignleft: [' .
'{selector: "p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li", styles: {textAlign:"left"}},' .
'{selector: "img,table,dl.wp-caption", classes: "alignleft"}' .
'],' .
'aligncenter: [' .
'{selector: "p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li", styles: {textAlign:"center"}},' .
'{selector: "img,table,dl.wp-caption", classes: "aligncenter"}' .
'],' .
'alignright: [' .
'{selector: "p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li", styles: {textAlign:"right"}},' .
'{selector: "img,table,dl.wp-caption", classes: "alignright"}' .
'],' .
'strikethrough: {inline: "del"}' .
'}',
'relative_urls' => false,
'remove_script_host' => false,
'convert_urls' => false,
'browser_spellcheck' => true,
'fix_list_elements' => true,
'entities' => '38,amp,60,lt,62,gt',
'entity_encoding' => 'raw',
'keep_styles' => false,
'cache_suffix' => 'wp-mce-' . $tinymce_version,
'resize' => 'vertical',
'menubar' => false,
'branding' => false,
// Limit the preview styles in the menu/toolbar.
'preview_styles' => 'font-family font-size font-weight font-style text-decoration text-transform',
'end_container_on_empty_block' => true,
'wpeditimage_html5_captions' => true,
'wp_lang_attr' => get_bloginfo( 'language' ),
'wp_keep_scroll_position' => false,
'wp_shortcut_labels' => wp_json_encode( $shortcut_labels ),
);
$suffix = SCRIPT_DEBUG ? '' : '.min';
$version = 'ver=' . get_bloginfo( 'version' );
// Default stylesheets.
$settings['content_css'] = includes_url( "css/dashicons$suffix.css?$version" ) . ',' .
includes_url( "js/tinymce/skins/wordpress/wp-content.css?$version" );
return $settings;
}
/**
* @since 4.7.0
*
* @return array
*/
private static function get_translation() {
if ( empty( self::$translation ) ) {
self::$translation = array(
// Default TinyMCE strings.
'New document' => __( 'New document' ),
'Formats' => _x( 'Formats', 'TinyMCE' ),
'Headings' => _x( 'Headings', 'TinyMCE' ),
'Heading 1' => array( __( 'Heading 1' ), 'access1' ),
'Heading 2' => array( __( 'Heading 2' ), 'access2' ),
'Heading 3' => array( __( 'Heading 3' ), 'access3' ),
'Heading 4' => array( __( 'Heading 4' ), 'access4' ),
'Heading 5' => array( __( 'Heading 5' ), 'access5' ),
'Heading 6' => array( __( 'Heading 6' ), 'access6' ),
/* translators: Block tags. */
'Blocks' => _x( 'Blocks', 'TinyMCE' ),
'Paragraph' => array( __( 'Paragraph' ), 'access7' ),
'Blockquote' => array( __( 'Blockquote' ), 'accessQ' ),
'Div' => _x( 'Div', 'HTML tag' ),
'Pre' => _x( 'Pre', 'HTML tag' ),
'Preformatted' => _x( 'Preformatted', 'HTML tag' ),
'Address' => _x( 'Address', 'HTML tag' ),
'Inline' => _x( 'Inline', 'HTML elements' ),
'Underline' => array( __( 'Underline' ), 'metaU' ),
'Strikethrough' => array( __( 'Strikethrough' ), 'accessD' ),
'Subscript' => __( 'Subscript' ),
'Superscript' => __( 'Superscript' ),
'Clear formatting' => __( 'Clear formatting' ),
'Bold' => array( __( 'Bold' ), 'metaB' ),
'Italic' => array( __( 'Italic' ), 'metaI' ),
'Code' => array( __( 'Code' ), 'accessX' ),
'Source code' => __( 'Source code' ),
'Font Family' => __( 'Font Family' ),
'Font Sizes' => __( 'Font Sizes' ),
'Align center' => array( __( 'Align center' ), 'accessC' ),
'Align right' => array( __( 'Align right' ), 'accessR' ),
'Align left' => array( __( 'Align left' ), 'accessL' ),
'Justify' => array( __( 'Justify' ), 'accessJ' ),
'Increase indent' => __( 'Increase indent' ),
'Decrease indent' => __( 'Decrease indent' ),
'Cut' => array( __( 'Cut' ), 'metaX' ),
'Copy' => array( __( 'Copy' ), 'metaC' ),
'Paste' => array( __( 'Paste' ), 'metaV' ),
'Select all' => array( __( 'Select all' ), 'metaA' ),
'Undo' => array( __( 'Undo' ), 'metaZ' ),
'Redo' => array( __( 'Redo' ), 'metaY' ),
'Ok' => __( 'OK' ),
'Cancel' => __( 'Cancel' ),
'Close' => __( 'Close' ),
'Visual aids' => __( 'Visual aids' ),
'Bullet list' => array( __( 'Bulleted list' ), 'accessU' ),
'Numbered list' => array( __( 'Numbered list' ), 'accessO' ),
'Square' => _x( 'Square', 'list style' ),
'Default' => _x( 'Default', 'list style' ),
'Circle' => _x( 'Circle', 'list style' ),
'Disc' => _x( 'Disc', 'list style' ),
'Lower Greek' => _x( 'Lower Greek', 'list style' ),
'Lower Alpha' => _x( 'Lower Alpha', 'list style' ),
'Upper Alpha' => _x( 'Upper Alpha', 'list style' ),
'Upper Roman' => _x( 'Upper Roman', 'list style' ),
'Lower Roman' => _x( 'Lower Roman', 'list style' ),
// Anchor plugin.
'Name' => _x( 'Name', 'Name of link anchor (TinyMCE)' ),
'Anchor' => _x( 'Anchor', 'Link anchor (TinyMCE)' ),
'Anchors' => _x( 'Anchors', 'Link anchors (TinyMCE)' ),
'Id should start with a letter, followed only by letters, numbers, dashes, dots, colons or underscores.' =>
__( 'Id should start with a letter, followed only by letters, numbers, dashes, dots, colons or underscores.' ),
'Id' => _x( 'Id', 'Id for link anchor (TinyMCE)' ),
// Fullpage plugin.
'Document properties' => __( 'Document properties' ),
'Robots' => __( 'Robots' ),
'Title' => __( 'Title' ),
'Keywords' => __( 'Keywords' ),
'Encoding' => __( 'Encoding' ),
'Description' => __( 'Description' ),
'Author' => __( 'Author' ),
// Media, image plugins.
'Image' => __( 'Image' ),
'Insert/edit image' => array( __( 'Insert/edit image' ), 'accessM' ),
'General' => __( 'General' ),
'Advanced' => __( 'Advanced' ),
'Source' => __( 'Source' ),
'Border' => __( 'Border' ),
'Constrain proportions' => __( 'Constrain proportions' ),
'Vertical space' => __( 'Vertical space' ),
'Image description' => __( 'Image description' ),
'Style' => __( 'Style' ),
'Dimensions' => __( 'Dimensions' ),
'Insert image' => __( 'Insert image' ),
'Date/time' => __( 'Date/time' ),
'Insert date/time' => __( 'Insert date/time' ),
'Table of Contents' => __( 'Table of Contents' ),
'Insert/Edit code sample' => __( 'Insert/edit code sample' ),
'Language' => __( 'Language' ),
'Media' => __( 'Media' ),
'Insert/edit media' => __( 'Insert/edit media' ),
'Poster' => __( 'Poster' ),
'Alternative source' => __( 'Alternative source' ),
'Paste your embed code below:' => __( 'Paste your embed code below:' ),
'Insert video' => __( 'Insert video' ),
'Embed' => __( 'Embed' ),
// Each of these have a corresponding plugin.
'Special character' => __( 'Special character' ),
'Right to left' => _x( 'Right to left', 'editor button' ),
'Left to right' => _x( 'Left to right', 'editor button' ),
'Emoticons' => __( 'Emoticons' ),
'Nonbreaking space' => __( 'Nonbreaking space' ),
'Page break' => __( 'Page break' ),
'Paste as text' => __( 'Paste as text' ),
'Preview' => __( 'Preview' ),
'Print' => __( 'Print' ),
'Save' => __( 'Save' ),
'Fullscreen' => __( 'Fullscreen' ),
'Horizontal line' => __( 'Horizontal line' ),
'Horizontal space' => __( 'Horizontal space' ),
'Restore last draft' => __( 'Restore last draft' ),
'Insert/edit link' => array( __( 'Insert/edit link' ), 'metaK' ),
'Remove link' => array( __( 'Remove link' ), 'accessS' ),
// Link plugin.
'Link' => __( 'Link' ),
'Insert link' => __( 'Insert link' ),
'Target' => __( 'Target' ),
'New window' => __( 'New window' ),
'Text to display' => __( 'Text to display' ),
'Url' => __( 'URL' ),
'The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?' =>
__( 'The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?' ),
'The URL you entered seems to be an external link. Do you want to add the required http:// prefix?' =>
__( 'The URL you entered seems to be an external link. Do you want to add the required http:// prefix?' ),
'Color' => __( 'Color' ),
'Custom color' => __( 'Custom color' ),
'Custom...' => _x( 'Custom...', 'label for custom color' ), // No ellipsis.
'No color' => __( 'No color' ),
'R' => _x( 'R', 'Short for red in RGB' ),
'G' => _x( 'G', 'Short for green in RGB' ),
'B' => _x( 'B', 'Short for blue in RGB' ),
// Spelling, search/replace plugins.
'Could not find the specified string.' => __( 'Could not find the specified string.' ),
'Replace' => _x( 'Replace', 'find/replace' ),
'Next' => _x( 'Next', 'find/replace' ),
/* translators: Previous. */
'Prev' => _x( 'Prev', 'find/replace' ),
'Whole words' => _x( 'Whole words', 'find/replace' ),
'Find and replace' => __( 'Find and replace' ),
'Replace with' => _x( 'Replace with', 'find/replace' ),
'Find' => _x( 'Find', 'find/replace' ),
'Replace all' => _x( 'Replace all', 'find/replace' ),
'Match case' => __( 'Match case' ),
'Spellcheck' => __( 'Check Spelling' ),
'Finish' => _x( 'Finish', 'spellcheck' ),
'Ignore all' => _x( 'Ignore all', 'spellcheck' ),
'Ignore' => _x( 'Ignore', 'spellcheck' ),
'Add to Dictionary' => __( 'Add to Dictionary' ),
// TinyMCE tables.
'Insert table' => __( 'Insert table' ),
'Delete table' => __( 'Delete table' ),
'Table properties' => __( 'Table properties' ),
'Row properties' => __( 'Table row properties' ),
'Cell properties' => __( 'Table cell properties' ),
'Border color' => __( 'Border color' ),
'Row' => __( 'Row' ),
'Rows' => __( 'Rows' ),
'Column' => __( 'Column' ),
'Cols' => __( 'Columns' ),
'Cell' => _x( 'Cell', 'table cell' ),
'Header cell' => __( 'Header cell' ),
'Header' => _x( 'Header', 'table header' ),
'Body' => _x( 'Body', 'table body' ),
'Footer' => _x( 'Footer', 'table footer' ),
'Insert row before' => __( 'Insert row before' ),
'Insert row after' => __( 'Insert row after' ),
'Insert column before' => __( 'Insert column before' ),
'Insert column after' => __( 'Insert column after' ),
'Paste row before' => __( 'Paste table row before' ),
'Paste row after' => __( 'Paste table row after' ),
'Delete row' => __( 'Delete row' ),
'Delete column' => __( 'Delete column' ),
'Cut row' => __( 'Cut table row' ),
'Copy row' => __( 'Copy table row' ),
'Merge cells' => __( 'Merge table cells' ),
'Split cell' => __( 'Split table cell' ),
'Height' => __( 'Height' ),
'Width' => __( 'Width' ),
'Caption' => __( 'Caption' ),
'Alignment' => __( 'Alignment' ),
'H Align' => _x( 'H Align', 'horizontal table cell alignment' ),
'Left' => __( 'Left' ),
'Center' => __( 'Center' ),
'Right' => __( 'Right' ),
'None' => _x( 'None', 'table cell alignment attribute' ),
'V Align' => _x( 'V Align', 'vertical table cell alignment' ),
'Top' => __( 'Top' ),
'Middle' => __( 'Middle' ),
'Bottom' => __( 'Bottom' ),
'Row group' => __( 'Row group' ),
'Column group' => __( 'Column group' ),
'Row type' => __( 'Row type' ),
'Cell type' => __( 'Cell type' ),
'Cell padding' => __( 'Cell padding' ),
'Cell spacing' => __( 'Cell spacing' ),
'Scope' => _x( 'Scope', 'table cell scope attribute' ),
'Insert template' => _x( 'Insert template', 'TinyMCE' ),
'Templates' => _x( 'Templates', 'TinyMCE' ),
'Background color' => __( 'Background color' ),
'Text color' => __( 'Text color' ),
'Show blocks' => _x( 'Show blocks', 'editor button' ),
'Show invisible characters' => __( 'Show invisible characters' ),
/* translators: Word count. */
'Words: {0}' => sprintf( __( 'Words: %s' ), '{0}' ),
'Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.' =>
__( 'Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.' ) . "\n\n" .
__( 'If you are looking to paste rich content from Microsoft Word, try turning this option off. The editor will clean up text pasted from Word automatically.' ),
'Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help' =>
__( 'Rich Text Area. Press Alt-Shift-H for help.' ),
'Rich Text Area. Press Control-Option-H for help.' => __( 'Rich Text Area. Press Control-Option-H for help.' ),
'You have unsaved changes are you sure you want to navigate away?' =>
__( 'The changes you made will be lost if you navigate away from this page.' ),
'Your browser doesn\'t support direct access to the clipboard. Please use the Ctrl+X/C/V keyboard shortcuts instead.' =>
__( 'Your browser does not support direct access to the clipboard. Please use keyboard shortcuts or your browser’s edit menu instead.' ),
// TinyMCE menus.
'Insert' => _x( 'Insert', 'TinyMCE menu' ),
'File' => _x( 'File', 'TinyMCE menu' ),
'Edit' => _x( 'Edit', 'TinyMCE menu' ),
'Tools' => _x( 'Tools', 'TinyMCE menu' ),
'View' => _x( 'View', 'TinyMCE menu' ),
'Table' => _x( 'Table', 'TinyMCE menu' ),
'Format' => _x( 'Format', 'TinyMCE menu' ),
// WordPress strings.
'Toolbar Toggle' => array( __( 'Toolbar Toggle' ), 'accessZ' ),
'Insert Read More tag' => array( __( 'Insert Read More tag' ), 'accessT' ),
'Insert Page Break tag' => array( __( 'Insert Page Break tag' ), 'accessP' ),
'Read more...' => __( 'Read more...' ), // Title on the placeholder inside the editor (no ellipsis).
'Distraction-free writing mode' => array( __( 'Distraction-free writing mode' ), 'accessW' ),
'No alignment' => __( 'No alignment' ), // Tooltip for the 'alignnone' button in the image toolbar.
'Remove' => __( 'Remove' ), // Tooltip for the 'remove' button in the image toolbar.
'Edit|button' => __( 'Edit' ), // Tooltip for the 'edit' button in the image toolbar.
'Paste URL or type to search' => __( 'Paste URL or type to search' ), // Placeholder for the inline link dialog.
'Apply' => __( 'Apply' ), // Tooltip for the 'apply' button in the inline link dialog.
'Link options' => __( 'Link options' ), // Tooltip for the 'link options' button in the inline link dialog.
'Visual' => _x( 'Visual', 'Name for the Visual editor tab' ), // Editor switch tab label.
'Text' => _x( 'Text', 'Name for the Text editor tab (formerly HTML)' ), // Editor switch tab label.
'Add Media' => array( __( 'Add Media' ), 'accessM' ), // Tooltip for the 'Add Media' button in the block editor Classic block.
// Shortcuts help modal.
'Keyboard Shortcuts' => array( __( 'Keyboard Shortcuts' ), 'accessH' ),
'Classic Block Keyboard Shortcuts' => __( 'Classic Block Keyboard Shortcuts' ),
'Default shortcuts,' => __( 'Default shortcuts,' ),
'Additional shortcuts,' => __( 'Additional shortcuts,' ),
'Focus shortcuts:' => __( 'Focus shortcuts:' ),
'Inline toolbar (when an image, link or preview is selected)' => __( 'Inline toolbar (when an image, link or preview is selected)' ),
'Editor menu (when enabled)' => __( 'Editor menu (when enabled)' ),
'Editor toolbar' => __( 'Editor toolbar' ),
'Elements path' => __( 'Elements path' ),
'Ctrl + Alt + letter:' => __( 'Ctrl + Alt + letter:' ),
'Shift + Alt + letter:' => __( 'Shift + Alt + letter:' ),
'Cmd + letter:' => __( 'Cmd + letter:' ),
'Ctrl + letter:' => __( 'Ctrl + letter:' ),
'Letter' => __( 'Letter' ),
'Action' => __( 'Action' ),
'Warning: the link has been inserted but may have errors. Please test it.' => __( 'Warning: the link has been inserted but may have errors. Please test it.' ),
'To move focus to other buttons use Tab or the arrow keys. To return focus to the editor press Escape or use one of the buttons.' =>
__( 'To move focus to other buttons use Tab or the arrow keys. To return focus to the editor press Escape or use one of the buttons.' ),
'When starting a new paragraph with one of these formatting shortcuts followed by a space, the formatting will be applied automatically. Press Backspace or Escape to undo.' =>
__( 'When starting a new paragraph with one of these formatting shortcuts followed by a space, the formatting will be applied automatically. Press Backspace or Escape to undo.' ),
'The following formatting shortcuts are replaced when pressing Enter. Press Escape or the Undo button to undo.' =>
__( 'The following formatting shortcuts are replaced when pressing Enter. Press Escape or the Undo button to undo.' ),
'The next group of formatting shortcuts are applied as you type or when you insert them around plain text in the same paragraph. Press Escape or the Undo button to undo.' =>
__( 'The next group of formatting shortcuts are applied as you type or when you insert them around plain text in the same paragraph. Press Escape or the Undo button to undo.' ),
);
}
/*
Imagetools plugin (not included):
'Edit image' => __( 'Edit image' ),
'Image options' => __( 'Image options' ),
'Back' => __( 'Back' ),
'Invert' => __( 'Invert' ),
'Flip horizontally' => __( 'Flip horizontal' ),
'Flip vertically' => __( 'Flip vertical' ),
'Crop' => __( 'Crop' ),
'Orientation' => __( 'Orientation' ),
'Resize' => __( 'Resize' ),
'Rotate clockwise' => __( 'Rotate right' ),
'Rotate counterclockwise' => __( 'Rotate left' ),
'Sharpen' => __( 'Sharpen' ),
'Brightness' => __( 'Brightness' ),
'Color levels' => __( 'Color levels' ),
'Contrast' => __( 'Contrast' ),
'Gamma' => __( 'Gamma' ),
'Zoom in' => __( 'Zoom in' ),
'Zoom out' => __( 'Zoom out' ),
*/
return self::$translation;
}
/**
* Translates the default TinyMCE strings and returns them as JSON encoded object ready to be loaded with tinymce.addI18n(),
* or as JS snippet that should run after tinymce.js is loaded.
*
* @since 3.9.0
*
* @param string $mce_locale The locale used for the editor.
* @param bool $json_only Optional. Whether to include the JavaScript calls to tinymce.addI18n() and
* tinymce.ScriptLoader.markDone().
* @return string Translation object, JSON encoded.
*/
public static function wp_mce_translation( $mce_locale = '', $json_only = false ) {
if ( ! $mce_locale ) {
$mce_locale = self::get_mce_locale();
}
$mce_translation = self::get_translation();
foreach ( $mce_translation as $name => $value ) {
if ( is_array( $value ) ) {
$mce_translation[ $name ] = $value[0];
}
}
/**
* Filters translated strings prepared for TinyMCE.
*
* @since 3.9.0
*
* @param array $mce_translation Key/value pairs of strings.
* @param string $mce_locale Locale.
*/
$mce_translation = apply_filters( 'wp_mce_translation', $mce_translation, $mce_locale );
foreach ( $mce_translation as $key => $value ) {
// Remove strings that are not translated.
if ( $key === $value ) {
unset( $mce_translation[ $key ] );
continue;
}
if ( false !== strpos( $value, '&' ) ) {
$mce_translation[ $key ] = html_entity_decode( $value, ENT_QUOTES, 'UTF-8' );
}
}
// Set direction.
if ( is_rtl() ) {
$mce_translation['_dir'] = 'rtl';
}
if ( $json_only ) {
return wp_json_encode( $mce_translation );
}
$baseurl = self::get_baseurl();
return "tinymce.addI18n( '$mce_locale', " . wp_json_encode( $mce_translation ) . ");\n" .
"tinymce.ScriptLoader.markDone( '$baseurl/langs/$mce_locale.js' );\n";
}
/**
* Force uncompressed TinyMCE when a custom theme has been defined.
*
* The compressed TinyMCE file cannot deal with custom themes, so this makes
* sure that we use the uncompressed TinyMCE file if a theme is defined.
* Even if we are on a production environment.
*
* @since 5.0.0
*/
public static function force_uncompressed_tinymce() {
$has_custom_theme = false;
foreach ( self::$mce_settings as $init ) {
if ( ! empty( $init['theme_url'] ) ) {
$has_custom_theme = true;
break;
}
}
if ( ! $has_custom_theme ) {
return;
}
$wp_scripts = wp_scripts();
$wp_scripts->remove( 'wp-tinymce' );
wp_register_tinymce_scripts( $wp_scripts, true );
}
/**
* Print (output) the main TinyMCE scripts.
*
* @since 4.8.0
*
* @global bool $concatenate_scripts
*/
public static function print_tinymce_scripts() {
global $concatenate_scripts;
if ( self::$tinymce_scripts_printed ) {
return;
}
self::$tinymce_scripts_printed = true;
if ( ! isset( $concatenate_scripts ) ) {
script_concat_settings();
}
wp_print_scripts( array( 'wp-tinymce' ) );
echo "<script type='text/javascript'>\n" . self::wp_mce_translation() . "</script>\n";
}
/**
* Print (output) the TinyMCE configuration and initialization scripts.
*
* @since 3.3.0
*
* @global string $tinymce_version
*/
public static function editor_js() {
global $tinymce_version;
$tmce_on = ! empty( self::$mce_settings );
$mceInit = '';
$qtInit = '';
if ( $tmce_on ) {
foreach ( self::$mce_settings as $editor_id => $init ) {
$options = self::_parse_init( $init );
$mceInit .= "'$editor_id':{$options},";
}
$mceInit = '{' . trim( $mceInit, ',' ) . '}';
} else {
$mceInit = '{}';
}
if ( ! empty( self::$qt_settings ) ) {
foreach ( self::$qt_settings as $editor_id => $init ) {
$options = self::_parse_init( $init );
$qtInit .= "'$editor_id':{$options},";
}
$qtInit = '{' . trim( $qtInit, ',' ) . '}';
} else {
$qtInit = '{}';
}
$ref = array(
'plugins' => implode( ',', self::$plugins ),
'theme' => 'modern',
'language' => self::$mce_locale,
);
$suffix = SCRIPT_DEBUG ? '' : '.min';
$baseurl = self::get_baseurl();
$version = 'ver=' . $tinymce_version;
/**
* Fires immediately before the TinyMCE settings are printed.
*
* @since 3.2.0
*
* @param array $mce_settings TinyMCE settings array.
*/
do_action( 'before_wp_tiny_mce', self::$mce_settings );
?>
<script type="text/javascript">
tinyMCEPreInit = {
baseURL: "<?php echo $baseurl; ?>",
suffix: "<?php echo $suffix; ?>",
<?php
if ( self::$drag_drop_upload ) {
echo 'dragDropUpload: true,';
}
?>
mceInit: <?php echo $mceInit; ?>,
qtInit: <?php echo $qtInit; ?>,
ref: <?php echo self::_parse_init( $ref ); ?>,
load_ext: function(url,lang){var sl=tinymce.ScriptLoader;sl.markDone(url+'/langs/'+lang+'.js');sl.markDone(url+'/langs/'+lang+'_dlg.js');}
};
</script>
<?php
if ( $tmce_on ) {
self::print_tinymce_scripts();
if ( self::$ext_plugins ) {
// Load the old-format English strings to prevent unsightly labels in old style popups.
echo "<script type='text/javascript' src='{$baseurl}/langs/wp-langs-en.js?$version'></script>\n";
}
}
/**
* Fires after tinymce.js is loaded, but before any TinyMCE editor
* instances are created.
*
* @since 3.9.0
*
* @param array $mce_settings TinyMCE settings array.
*/
do_action( 'wp_tiny_mce_init', self::$mce_settings );
?>
<script type="text/javascript">
<?php
if ( self::$ext_plugins ) {
echo self::$ext_plugins . "\n";
}
if ( ! is_admin() ) {
echo 'var ajaxurl = "' . admin_url( 'admin-ajax.php', 'relative' ) . '";';
}
?>
( function() {
var initialized = [];
var initialize = function() {
var init, id, inPostbox, $wrap;
var readyState = document.readyState;
if ( readyState !== 'complete' && readyState !== 'interactive' ) {
return;
}
for ( id in tinyMCEPreInit.mceInit ) {
if ( initialized.indexOf( id ) > -1 ) {
continue;
}
init = tinyMCEPreInit.mceInit[id];
$wrap = tinymce.$( '#wp-' + id + '-wrap' );
inPostbox = $wrap.parents( '.postbox' ).length > 0;
if (
! init.wp_skip_init &&
( $wrap.hasClass( 'tmce-active' ) || ! tinyMCEPreInit.qtInit.hasOwnProperty( id ) ) &&
( readyState === 'complete' || ( ! inPostbox && readyState === 'interactive' ) )
) {
tinymce.init( init );
initialized.push( id );
if ( ! window.wpActiveEditor ) {
window.wpActiveEditor = id;
}
}
}
}
if ( typeof tinymce !== 'undefined' ) {
if ( tinymce.Env.ie && tinymce.Env.ie < 11 ) {
tinymce.$( '.wp-editor-wrap ' ).removeClass( 'tmce-active' ).addClass( 'html-active' );
} else {
if ( document.readyState === 'complete' ) {
initialize();
} else {
document.addEventListener( 'readystatechange', initialize );
}
}
}
if ( typeof quicktags !== 'undefined' ) {
for ( id in tinyMCEPreInit.qtInit ) {
quicktags( tinyMCEPreInit.qtInit[id] );
if ( ! window.wpActiveEditor ) {
window.wpActiveEditor = id;
}
}
}
}());
</script>
<?php
if ( in_array( 'wplink', self::$plugins, true ) || in_array( 'link', self::$qt_buttons, true ) ) {
self::wp_link_dialog();
}
/**
* Fires after any core TinyMCE editor instances are created.
*
* @since 3.2.0
*
* @param array $mce_settings TinyMCE settings array.
*/
do_action( 'after_wp_tiny_mce', self::$mce_settings );
}
/**
* Outputs the HTML for distraction-free writing mode.
*
* @since 3.2.0
* @deprecated 4.3.0
*/
public static function wp_fullscreen_html() {
_deprecated_function( __FUNCTION__, '4.3.0' );
}
/**
* Performs post queries for internal linking.
*
* @since 3.1.0
*
* @param array $args Optional. Accepts 'pagenum' and 's' (search) arguments.
* @return array|false $results {
* An array of associative arrays of query results, false if there are none.
*
* @type array ...$0 {
* @type int $ID Post ID.
* @type string $title The trimmed, escaped post title.
* @type string $permalink Post permalink.
* @type string $info A 'Y/m/d'-formatted date for 'post' post type,
* the 'singular_name' post type label otherwise.
* }
* }
*/
public static function wp_link_query( $args = array() ) {
$pts = get_post_types( array( 'public' => true ), 'objects' );
$pt_names = array_keys( $pts );
$query = array(
'post_type' => $pt_names,
'suppress_filters' => true,
'update_post_term_cache' => false,
'update_post_meta_cache' => false,
'post_status' => 'publish',
'posts_per_page' => 20,
);
$args['pagenum'] = isset( $args['pagenum'] ) ? absint( $args['pagenum'] ) : 1;
if ( isset( $args['s'] ) ) {
$query['s'] = $args['s'];
}
$query['offset'] = $args['pagenum'] > 1 ? $query['posts_per_page'] * ( $args['pagenum'] - 1 ) : 0;
/**
* Filters the link query arguments.
*
* Allows modification of the link query arguments before querying.
*
* @see WP_Query for a full list of arguments
*
* @since 3.7.0
*
* @param array $query An array of WP_Query arguments.
*/
$query = apply_filters( 'wp_link_query_args', $query );
// Do main query.
$get_posts = new WP_Query;
$posts = $get_posts->query( $query );
// Build results.
$results = array();
foreach ( $posts as $post ) {
if ( 'post' === $post->post_type ) {
$info = mysql2date( __( 'Y/m/d' ), $post->post_date );
} else {
$info = $pts[ $post->post_type ]->labels->singular_name;
}
$results[] = array(
'ID' => $post->ID,
'title' => trim( esc_html( strip_tags( get_the_title( $post ) ) ) ),
'permalink' => get_permalink( $post->ID ),
'info' => $info,
);
}
/**
* Filters the link query results.
*
* Allows modification of the returned link query results.
*
* @since 3.7.0
*
* @see 'wp_link_query_args' filter
*
* @param array $results {
* An array of associative arrays of query results.
*
* @type array ...$0 {
* @type int $ID Post ID.
* @type string $title The trimmed, escaped post title.
* @type string $permalink Post permalink.
* @type string $info A 'Y/m/d'-formatted date for 'post' post type,
* the 'singular_name' post type label otherwise.
* }
* }
* @param array $query An array of WP_Query arguments.
*/
$results = apply_filters( 'wp_link_query', $results, $query );
return ! empty( $results ) ? $results : false;
}
/**
* Dialog for internal linking.
*
* @since 3.1.0
*/
public static function wp_link_dialog() {
// Run once.
if ( self::$link_dialog_printed ) {
return;
}
self::$link_dialog_printed = true;
// `display: none` is required here, see #WP27605.
?>
<div id="wp-link-backdrop" style="display: none"></div>
<div id="wp-link-wrap" class="wp-core-ui" style="display: none" role="dialog" aria-labelledby="link-modal-title">
<form id="wp-link" tabindex="-1">
<?php wp_nonce_field( 'internal-linking', '_ajax_linking_nonce', false ); ?>
<h1 id="link-modal-title"><?php _e( 'Insert/edit link' ); ?></h1>
<button type="button" id="wp-link-close"><span class="screen-reader-text"><?php _e( 'Close' ); ?></span></button>
<div id="link-selector">
<div id="link-options">
<p class="howto" id="wplink-enter-url"><?php _e( 'Enter the destination URL' ); ?></p>
<div>
<label><span><?php _e( 'URL' ); ?></span>
<input id="wp-link-url" type="text" aria-describedby="wplink-enter-url" /></label>
</div>
<div class="wp-link-text-field">
<label><span><?php _e( 'Link Text' ); ?></span>
<input id="wp-link-text" type="text" /></label>
</div>
<div class="link-target">
<label><span></span>
<input type="checkbox" id="wp-link-target" /> <?php _e( 'Open link in a new tab' ); ?></label>
</div>
</div>
<p class="howto" id="wplink-link-existing-content"><?php _e( 'Or link to existing content' ); ?></p>
<div id="search-panel">
<div class="link-search-wrapper">
<label>
<span class="search-label"><?php _e( 'Search' ); ?></span>
<input type="search" id="wp-link-search" class="link-search-field" autocomplete="off" aria-describedby="wplink-link-existing-content" />
<span class="spinner"></span>
</label>
</div>
<div id="search-results" class="query-results" tabindex="0">
<ul></ul>
<div class="river-waiting">
<span class="spinner"></span>
</div>
</div>
<div id="most-recent-results" class="query-results" tabindex="0">
<div class="query-notice" id="query-notice-message">
<em class="query-notice-default"><?php _e( 'No search term specified. Showing recent items.' ); ?></em>
<em class="query-notice-hint screen-reader-text"><?php _e( 'Search or use up and down arrow keys to select an item.' ); ?></em>
</div>
<ul></ul>
<div class="river-waiting">
<span class="spinner"></span>
</div>
</div>
</div>
</div>
<div class="submitbox">
<div id="wp-link-cancel">
<button type="button" class="button"><?php _e( 'Cancel' ); ?></button>
</div>
<div id="wp-link-update">
<input type="submit" value="<?php esc_attr_e( 'Add Link' ); ?>" class="button button-primary" id="wp-link-submit" name="wp-link-submit">
</div>
</div>
</form>
</div>
<?php
}
}
```
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
| programming_docs |
wordpress class WP_Http_Curl {} class WP\_Http\_Curl {}
=======================
Core class used to integrate Curl as an HTTP transport.
HTTP request method uses Curl extension to retrieve the url.
Requires the Curl extension to be installed.
* [request](wp_http_curl/request) — Send a HTTP request to a URI using cURL extension.
* [stream\_body](wp_http_curl/stream_body) — Grabs the body of the cURL request.
* [stream\_headers](wp_http_curl/stream_headers) — Grabs the headers of the cURL request.
* [test](wp_http_curl/test) — Determines whether this class can be used for retrieving a URL.
File: `wp-includes/class-wp-http-curl.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-curl.php/)
```
class WP_Http_Curl {
/**
* Temporary header storage for during requests.
*
* @since 3.2.0
* @var string
*/
private $headers = '';
/**
* Temporary body storage for during requests.
*
* @since 3.6.0
* @var string
*/
private $body = '';
/**
* The maximum amount of data to receive from the remote server.
*
* @since 3.6.0
* @var int|false
*/
private $max_body_length = false;
/**
* The file resource used for streaming to file.
*
* @since 3.6.0
* @var resource|false
*/
private $stream_handle = false;
/**
* The total bytes written in the current request.
*
* @since 4.1.0
* @var int
*/
private $bytes_written_total = 0;
/**
* Send a HTTP request to a URI using cURL extension.
*
* @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 request( $url, $args = array() ) {
$defaults = array(
'method' => 'GET',
'timeout' => 5,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => null,
'cookies' => array(),
);
$parsed_args = wp_parse_args( $args, $defaults );
if ( isset( $parsed_args['headers']['User-Agent'] ) ) {
$parsed_args['user-agent'] = $parsed_args['headers']['User-Agent'];
unset( $parsed_args['headers']['User-Agent'] );
} elseif ( isset( $parsed_args['headers']['user-agent'] ) ) {
$parsed_args['user-agent'] = $parsed_args['headers']['user-agent'];
unset( $parsed_args['headers']['user-agent'] );
}
// Construct Cookie: header if any cookies are set.
WP_Http::buildCookieHeader( $parsed_args );
$handle = curl_init();
// cURL offers really easy proxy support.
$proxy = new WP_HTTP_Proxy();
if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() );
curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() );
if ( $proxy->use_authentication() ) {
curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY );
curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() );
}
}
$is_local = isset( $parsed_args['local'] ) && $parsed_args['local'];
$ssl_verify = isset( $parsed_args['sslverify'] ) && $parsed_args['sslverify'];
if ( $is_local ) {
/** This filter is documented in wp-includes/class-wp-http-streams.php */
$ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify, $url );
} elseif ( ! $is_local ) {
/** This filter is documented in wp-includes/class-wp-http.php */
$ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify, $url );
}
/*
* CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since.
* a value of 0 will allow an unlimited timeout.
*/
$timeout = (int) ceil( $parsed_args['timeout'] );
curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $handle, CURLOPT_URL, $url );
curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, ( true === $ssl_verify ) ? 2 : false );
curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify );
if ( $ssl_verify ) {
curl_setopt( $handle, CURLOPT_CAINFO, $parsed_args['sslcertificates'] );
}
curl_setopt( $handle, CURLOPT_USERAGENT, $parsed_args['user-agent'] );
/*
* The option doesn't work with safe mode or when open_basedir is set, and there's
* a bug #17490 with redirected POST requests, so handle redirections outside Curl.
*/
curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, false );
curl_setopt( $handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
switch ( $parsed_args['method'] ) {
case 'HEAD':
curl_setopt( $handle, CURLOPT_NOBODY, true );
break;
case 'POST':
curl_setopt( $handle, CURLOPT_POST, true );
curl_setopt( $handle, CURLOPT_POSTFIELDS, $parsed_args['body'] );
break;
case 'PUT':
curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' );
curl_setopt( $handle, CURLOPT_POSTFIELDS, $parsed_args['body'] );
break;
default:
curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, $parsed_args['method'] );
if ( ! is_null( $parsed_args['body'] ) ) {
curl_setopt( $handle, CURLOPT_POSTFIELDS, $parsed_args['body'] );
}
break;
}
if ( true === $parsed_args['blocking'] ) {
curl_setopt( $handle, CURLOPT_HEADERFUNCTION, array( $this, 'stream_headers' ) );
curl_setopt( $handle, CURLOPT_WRITEFUNCTION, array( $this, 'stream_body' ) );
}
curl_setopt( $handle, CURLOPT_HEADER, false );
if ( isset( $parsed_args['limit_response_size'] ) ) {
$this->max_body_length = (int) $parsed_args['limit_response_size'];
} else {
$this->max_body_length = false;
}
// If streaming to a file open a file handle, and setup our curl streaming handler.
if ( $parsed_args['stream'] ) {
if ( ! WP_DEBUG ) {
$this->stream_handle = @fopen( $parsed_args['filename'], 'w+' );
} else {
$this->stream_handle = fopen( $parsed_args['filename'], 'w+' );
}
if ( ! $this->stream_handle ) {
return new WP_Error(
'http_request_failed',
sprintf(
/* translators: 1: fopen(), 2: File name. */
__( 'Could not open handle for %1$s to %2$s.' ),
'fopen()',
$parsed_args['filename']
)
);
}
} else {
$this->stream_handle = false;
}
if ( ! empty( $parsed_args['headers'] ) ) {
// cURL expects full header strings in each element.
$headers = array();
foreach ( $parsed_args['headers'] as $name => $value ) {
$headers[] = "{$name}: $value";
}
curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers );
}
if ( '1.0' === $parsed_args['httpversion'] ) {
curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 );
} else {
curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
}
/**
* Fires before the cURL request is executed.
*
* Cookies are not currently handled by the HTTP API. This action allows
* plugins to handle cookies themselves.
*
* @since 2.8.0
*
* @param resource $handle The cURL handle returned by curl_init() (passed by reference).
* @param array $parsed_args The HTTP request arguments.
* @param string $url The request URL.
*/
do_action_ref_array( 'http_api_curl', array( &$handle, $parsed_args, $url ) );
// We don't need to return the body, so don't. Just execute request and return.
if ( ! $parsed_args['blocking'] ) {
curl_exec( $handle );
$curl_error = curl_error( $handle );
if ( $curl_error ) {
curl_close( $handle );
return new WP_Error( 'http_request_failed', $curl_error );
}
if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ), true ) ) {
curl_close( $handle );
return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
}
curl_close( $handle );
return array(
'headers' => array(),
'body' => '',
'response' => array(
'code' => false,
'message' => false,
),
'cookies' => array(),
);
}
curl_exec( $handle );
$processed_headers = WP_Http::processHeaders( $this->headers, $url );
$body = $this->body;
$bytes_written_total = $this->bytes_written_total;
$this->headers = '';
$this->body = '';
$this->bytes_written_total = 0;
$curl_error = curl_errno( $handle );
// If an error occurred, or, no response.
if ( $curl_error || ( 0 === strlen( $body ) && empty( $processed_headers['headers'] ) ) ) {
if ( CURLE_WRITE_ERROR /* 23 */ === $curl_error ) {
if ( ! $this->max_body_length || $this->max_body_length !== $bytes_written_total ) {
if ( $parsed_args['stream'] ) {
curl_close( $handle );
fclose( $this->stream_handle );
return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
} else {
curl_close( $handle );
return new WP_Error( 'http_request_failed', curl_error( $handle ) );
}
}
} else {
$curl_error = curl_error( $handle );
if ( $curl_error ) {
curl_close( $handle );
return new WP_Error( 'http_request_failed', $curl_error );
}
}
if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ), true ) ) {
curl_close( $handle );
return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) );
}
}
curl_close( $handle );
if ( $parsed_args['stream'] ) {
fclose( $this->stream_handle );
}
$response = array(
'headers' => $processed_headers['headers'],
'body' => null,
'response' => $processed_headers['response'],
'cookies' => $processed_headers['cookies'],
'filename' => $parsed_args['filename'],
);
// Handle redirects.
$redirect_response = WP_Http::handle_redirects( $url, $parsed_args, $response );
if ( false !== $redirect_response ) {
return $redirect_response;
}
if ( true === $parsed_args['decompress']
&& true === WP_Http_Encoding::should_decode( $processed_headers['headers'] )
) {
$body = WP_Http_Encoding::decompress( $body );
}
$response['body'] = $body;
return $response;
}
/**
* Grabs the headers of the cURL request.
*
* Each header is sent individually to this callback, so we append to the `$header` property
* for temporary storage
*
* @since 3.2.0
*
* @param resource $handle cURL handle.
* @param string $headers cURL request headers.
* @return int Length of the request headers.
*/
private function stream_headers( $handle, $headers ) {
$this->headers .= $headers;
return strlen( $headers );
}
/**
* Grabs the body of the cURL request.
*
* The contents of the document are passed in chunks, so we append to the `$body`
* property for temporary storage. Returning a length shorter than the length of
* `$data` passed in will cause cURL to abort the request with `CURLE_WRITE_ERROR`.
*
* @since 3.6.0
*
* @param resource $handle cURL handle.
* @param string $data cURL request body.
* @return int Total bytes of data written.
*/
private function stream_body( $handle, $data ) {
$data_length = strlen( $data );
if ( $this->max_body_length && ( $this->bytes_written_total + $data_length ) > $this->max_body_length ) {
$data_length = ( $this->max_body_length - $this->bytes_written_total );
$data = substr( $data, 0, $data_length );
}
if ( $this->stream_handle ) {
$bytes_written = fwrite( $this->stream_handle, $data );
} else {
$this->body .= $data;
$bytes_written = $data_length;
}
$this->bytes_written_total += $bytes_written;
// Upon event of this function returning less than strlen( $data ) curl will error with CURLE_WRITE_ERROR.
return $bytes_written;
}
/**
* Determines whether this class can be used for retrieving a URL.
*
* @since 2.7.0
*
* @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( 'curl_init' ) || ! function_exists( 'curl_exec' ) ) {
return false;
}
$is_ssl = isset( $args['ssl'] ) && $args['ssl'];
if ( $is_ssl ) {
$curl_version = curl_version();
// Check whether this cURL version support SSL requests.
if ( ! ( CURL_VERSION_SSL & $curl_version['features'] ) ) {
return false;
}
}
/**
* Filters whether cURL can be used as a transport for retrieving a URL.
*
* @since 2.7.0
*
* @param bool $use_class Whether the class can be used. Default true.
* @param array $args An array of request arguments.
*/
return apply_filters( 'use_curl_transport', true, $args );
}
}
```
| Version | Description |
| --- | --- |
| [2.7.0](https://developer.wordpress.org/reference/since/2.7.0/) | Introduced. |
wordpress class WP_REST_Post_Meta_Fields {} class WP\_REST\_Post\_Meta\_Fields {}
=====================================
Core class used to manage meta values for posts via the REST API.
* [WP\_REST\_Meta\_Fields](wp_rest_meta_fields)
* [\_\_construct](wp_rest_post_meta_fields/__construct) — Constructor.
* [get\_meta\_subtype](wp_rest_post_meta_fields/get_meta_subtype) — Retrieves the post meta subtype.
* [get\_meta\_type](wp_rest_post_meta_fields/get_meta_type) — Retrieves the post meta type.
* [get\_rest\_field\_type](wp_rest_post_meta_fields/get_rest_field_type) — Retrieves the type for register\_rest\_field().
File: `wp-includes/rest-api/fields/class-wp-rest-post-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-post-meta-fields.php/)
```
class WP_REST_Post_Meta_Fields extends WP_REST_Meta_Fields {
/**
* Post type to register fields for.
*
* @since 4.7.0
* @var string
*/
protected $post_type;
/**
* Constructor.
*
* @since 4.7.0
*
* @param string $post_type Post type to register fields for.
*/
public function __construct( $post_type ) {
$this->post_type = $post_type;
}
/**
* Retrieves the post meta type.
*
* @since 4.7.0
*
* @return string The meta type.
*/
protected function get_meta_type() {
return 'post';
}
/**
* Retrieves the post meta subtype.
*
* @since 4.9.8
*
* @return string Subtype for the meta type, or empty string if no specific subtype.
*/
protected function get_meta_subtype() {
return $this->post_type;
}
/**
* Retrieves the type for register_rest_field().
*
* @since 4.7.0
*
* @see register_rest_field()
*
* @return string The REST field type.
*/
public function get_rest_field_type() {
return $this->post_type;
}
}
```
| 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_Code_Editor_Control {} class WP\_Customize\_Code\_Editor\_Control {}
=============================================
Customize Code Editor Control class.
* [WP\_Customize\_Control](wp_customize_control)
* [content\_template](wp_customize_code_editor_control/content_template) — Render a JS template for control display.
* [enqueue](wp_customize_code_editor_control/enqueue) — Enqueue control related scripts/styles.
* [json](wp_customize_code_editor_control/json) — Refresh the parameters passed to the JavaScript via JSON.
* [render\_content](wp_customize_code_editor_control/render_content) — Don't render the control content from PHP, as it's rendered via JS on load.
File: `wp-includes/customize/class-wp-customize-code-editor-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-code-editor-control.php/)
```
class WP_Customize_Code_Editor_Control extends WP_Customize_Control {
/**
* Customize control type.
*
* @since 4.9.0
* @var string
*/
public $type = 'code_editor';
/**
* Type of code that is being edited.
*
* @since 4.9.0
* @var string
*/
public $code_type = '';
/**
* Code editor settings.
*
* @see wp_enqueue_code_editor()
* @since 4.9.0
* @var array|false
*/
public $editor_settings = array();
/**
* Enqueue control related scripts/styles.
*
* @since 4.9.0
*/
public function enqueue() {
$this->editor_settings = wp_enqueue_code_editor(
array_merge(
array(
'type' => $this->code_type,
'codemirror' => array(
'indentUnit' => 2,
'tabSize' => 2,
),
),
$this->editor_settings
)
);
}
/**
* Refresh the parameters passed to the JavaScript via JSON.
*
* @since 4.9.0
*
* @see WP_Customize_Control::json()
*
* @return array Array of parameters passed to the JavaScript.
*/
public function json() {
$json = parent::json();
$json['editor_settings'] = $this->editor_settings;
$json['input_attrs'] = $this->input_attrs;
return $json;
}
/**
* Don't render the control content from PHP, as it's rendered via JS on load.
*
* @since 4.9.0
*/
public function render_content() {}
/**
* Render a JS template for control display.
*
* @since 4.9.0
*/
public function content_template() {
?>
<# var elementIdPrefix = 'el' + String( Math.random() ); #>
<# if ( data.label ) { #>
<label for="{{ elementIdPrefix }}_editor" class="customize-control-title">
{{ data.label }}
</label>
<# } #>
<# if ( data.description ) { #>
<span class="description customize-control-description">{{{ data.description }}}</span>
<# } #>
<div class="customize-control-notifications-container"></div>
<textarea id="{{ elementIdPrefix }}_editor"
<# _.each( _.extend( { 'class': 'code' }, data.input_attrs ), function( value, key ) { #>
{{{ key }}}="{{ value }}"
<# }); #>
></textarea>
<?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/) | Introduced. |
wordpress class Requests_Exception_HTTP_418 {} class Requests\_Exception\_HTTP\_418 {}
=======================================
Exception for 418 I’m A Teapot responses
* <https://tools.ietf.org/html/rfc2324>
File: `wp-includes/Requests/Exception/HTTP/418.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/418.php/)
```
class Requests_Exception_HTTP_418 extends Requests_Exception_HTTP {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 418;
/**
* Reason phrase
*
* @var string
*/
protected $reason = "I'm A Teapot";
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response |
wordpress class WP_Application_Passwords {} class WP\_Application\_Passwords {}
===================================
Class for displaying, modifying, and sanitizing application passwords.
* [application\_name\_exists\_for\_user](wp_application_passwords/application_name_exists_for_user) — Checks if an application password with the given name exists for this user.
* [chunk\_password](wp_application_passwords/chunk_password) — Sanitizes and then splits a password into smaller chunks.
* [create\_new\_application\_password](wp_application_passwords/create_new_application_password) — Creates a new application password.
* [delete\_all\_application\_passwords](wp_application_passwords/delete_all_application_passwords) — Deletes all application passwords for the given user.
* [delete\_application\_password](wp_application_passwords/delete_application_password) — Deletes an application password.
* [get\_user\_application\_password](wp_application_passwords/get_user_application_password) — Gets a user's application password with the given UUID.
* [get\_user\_application\_passwords](wp_application_passwords/get_user_application_passwords) — Gets a user's application passwords.
* [is\_in\_use](wp_application_passwords/is_in_use) — Checks if application passwords are being used by the site.
* [record\_application\_password\_usage](wp_application_passwords/record_application_password_usage) — Records that an application password has been used.
* [set\_user\_application\_passwords](wp_application_passwords/set_user_application_passwords) — Sets a user's application passwords.
* [update\_application\_password](wp_application_passwords/update_application_password) — Updates an application password.
File: `wp-includes/class-wp-application-passwords.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-application-passwords.php/)
```
class WP_Application_Passwords {
/**
* The application passwords user meta key.
*
* @since 5.6.0
*
* @var string
*/
const USERMETA_KEY_APPLICATION_PASSWORDS = '_application_passwords';
/**
* The option name used to store whether application passwords are in use.
*
* @since 5.6.0
*
* @var string
*/
const OPTION_KEY_IN_USE = 'using_application_passwords';
/**
* The generated application password length.
*
* @since 5.6.0
*
* @var int
*/
const PW_LENGTH = 24;
/**
* Checks if application passwords are being used by the site.
*
* This returns true if at least one application password has ever been created.
*
* @since 5.6.0
*
* @return bool
*/
public static function is_in_use() {
$network_id = get_main_network_id();
return (bool) get_network_option( $network_id, self::OPTION_KEY_IN_USE );
}
/**
* Creates a new application password.
*
* @since 5.6.0
* @since 5.7.0 Returns WP_Error if application name already exists.
*
* @param int $user_id User ID.
* @param array $args {
* Arguments used to create the application password.
*
* @type string $name The name of the application password.
* @type string $app_id A UUID provided by the application to uniquely identify it.
* }
* @return array|WP_Error The first key in the array is the new password, the second is its detailed information.
* A WP_Error instance is returned on error.
*/
public static function create_new_application_password( $user_id, $args = array() ) {
if ( ! empty( $args['name'] ) ) {
$args['name'] = sanitize_text_field( $args['name'] );
}
if ( empty( $args['name'] ) ) {
return new WP_Error( 'application_password_empty_name', __( 'An application name is required to create an application password.' ), array( 'status' => 400 ) );
}
if ( self::application_name_exists_for_user( $user_id, $args['name'] ) ) {
return new WP_Error( 'application_password_duplicate_name', __( 'Each application name should be unique.' ), array( 'status' => 409 ) );
}
$new_password = wp_generate_password( static::PW_LENGTH, false );
$hashed_password = wp_hash_password( $new_password );
$new_item = array(
'uuid' => wp_generate_uuid4(),
'app_id' => empty( $args['app_id'] ) ? '' : $args['app_id'],
'name' => $args['name'],
'password' => $hashed_password,
'created' => time(),
'last_used' => null,
'last_ip' => null,
);
$passwords = static::get_user_application_passwords( $user_id );
$passwords[] = $new_item;
$saved = static::set_user_application_passwords( $user_id, $passwords );
if ( ! $saved ) {
return new WP_Error( 'db_error', __( 'Could not save application password.' ) );
}
$network_id = get_main_network_id();
if ( ! get_network_option( $network_id, self::OPTION_KEY_IN_USE ) ) {
update_network_option( $network_id, self::OPTION_KEY_IN_USE, true );
}
/**
* Fires when an application password is created.
*
* @since 5.6.0
*
* @param int $user_id The user ID.
* @param array $new_item {
* The details about the created password.
*
* @type string $uuid The unique identifier for the application password.
* @type string $app_id A UUID provided by the application to uniquely identify it.
* @type string $name The name of the application password.
* @type string $password A one-way hash of the password.
* @type int $created Unix timestamp of when the password was created.
* @type null $last_used Null.
* @type null $last_ip Null.
* }
* @param string $new_password The unhashed generated application password.
* @param array $args {
* Arguments used to create the application password.
*
* @type string $name The name of the application password.
* @type string $app_id A UUID provided by the application to uniquely identify it.
* }
*/
do_action( 'wp_create_application_password', $user_id, $new_item, $new_password, $args );
return array( $new_password, $new_item );
}
/**
* Gets a user's application passwords.
*
* @since 5.6.0
*
* @param int $user_id User ID.
* @return array {
* The list of app passwords.
*
* @type array ...$0 {
* @type string $uuid The unique identifier for the application password.
* @type string $app_id A UUID provided by the application to uniquely identify it.
* @type string $name The name of the application password.
* @type string $password A one-way hash of the password.
* @type int $created Unix timestamp of when the password was created.
* @type int|null $last_used The Unix timestamp of the GMT date the application password was last used.
* @type string|null $last_ip The IP address the application password was last used by.
* }
* }
*/
public static function get_user_application_passwords( $user_id ) {
$passwords = get_user_meta( $user_id, static::USERMETA_KEY_APPLICATION_PASSWORDS, true );
if ( ! is_array( $passwords ) ) {
return array();
}
$save = false;
foreach ( $passwords as $i => $password ) {
if ( ! isset( $password['uuid'] ) ) {
$passwords[ $i ]['uuid'] = wp_generate_uuid4();
$save = true;
}
}
if ( $save ) {
static::set_user_application_passwords( $user_id, $passwords );
}
return $passwords;
}
/**
* Gets a user's application password with the given UUID.
*
* @since 5.6.0
*
* @param int $user_id User ID.
* @param string $uuid The password's UUID.
* @return array|null The application password if found, null otherwise.
*/
public static function get_user_application_password( $user_id, $uuid ) {
$passwords = static::get_user_application_passwords( $user_id );
foreach ( $passwords as $password ) {
if ( $password['uuid'] === $uuid ) {
return $password;
}
}
return null;
}
/**
* Checks if an application password with the given name exists for this user.
*
* @since 5.7.0
*
* @param int $user_id User ID.
* @param string $name Application name.
* @return bool Whether the provided application name exists.
*/
public static function application_name_exists_for_user( $user_id, $name ) {
$passwords = static::get_user_application_passwords( $user_id );
foreach ( $passwords as $password ) {
if ( strtolower( $password['name'] ) === strtolower( $name ) ) {
return true;
}
}
return false;
}
/**
* Updates an application password.
*
* @since 5.6.0
*
* @param int $user_id User ID.
* @param string $uuid The password's UUID.
* @param array $update Information about the application password to update.
* @return true|WP_Error True if successful, otherwise a WP_Error instance is returned on error.
*/
public static function update_application_password( $user_id, $uuid, $update = array() ) {
$passwords = static::get_user_application_passwords( $user_id );
foreach ( $passwords as &$item ) {
if ( $item['uuid'] !== $uuid ) {
continue;
}
if ( ! empty( $update['name'] ) ) {
$update['name'] = sanitize_text_field( $update['name'] );
}
$save = false;
if ( ! empty( $update['name'] ) && $item['name'] !== $update['name'] ) {
$item['name'] = $update['name'];
$save = true;
}
if ( $save ) {
$saved = static::set_user_application_passwords( $user_id, $passwords );
if ( ! $saved ) {
return new WP_Error( 'db_error', __( 'Could not save application password.' ) );
}
}
/**
* Fires when an application password is updated.
*
* @since 5.6.0
*
* @param int $user_id The user ID.
* @param array $item The updated app password details.
* @param array $update The information to update.
*/
do_action( 'wp_update_application_password', $user_id, $item, $update );
return true;
}
return new WP_Error( 'application_password_not_found', __( 'Could not find an application password with that id.' ) );
}
/**
* Records that an application password has been used.
*
* @since 5.6.0
*
* @param int $user_id User ID.
* @param string $uuid The password's UUID.
* @return true|WP_Error True if the usage was recorded, a WP_Error if an error occurs.
*/
public static function record_application_password_usage( $user_id, $uuid ) {
$passwords = static::get_user_application_passwords( $user_id );
foreach ( $passwords as &$password ) {
if ( $password['uuid'] !== $uuid ) {
continue;
}
// Only record activity once a day.
if ( $password['last_used'] + DAY_IN_SECONDS > time() ) {
return true;
}
$password['last_used'] = time();
$password['last_ip'] = $_SERVER['REMOTE_ADDR'];
$saved = static::set_user_application_passwords( $user_id, $passwords );
if ( ! $saved ) {
return new WP_Error( 'db_error', __( 'Could not save application password.' ) );
}
return true;
}
// Specified application password not found!
return new WP_Error( 'application_password_not_found', __( 'Could not find an application password with that id.' ) );
}
/**
* Deletes an application password.
*
* @since 5.6.0
*
* @param int $user_id User ID.
* @param string $uuid The password's UUID.
* @return true|WP_Error Whether the password was successfully found and deleted, a WP_Error otherwise.
*/
public static function delete_application_password( $user_id, $uuid ) {
$passwords = static::get_user_application_passwords( $user_id );
foreach ( $passwords as $key => $item ) {
if ( $item['uuid'] === $uuid ) {
unset( $passwords[ $key ] );
$saved = static::set_user_application_passwords( $user_id, $passwords );
if ( ! $saved ) {
return new WP_Error( 'db_error', __( 'Could not delete application password.' ) );
}
/**
* Fires when an application password is deleted.
*
* @since 5.6.0
*
* @param int $user_id The user ID.
* @param array $item The data about the application password.
*/
do_action( 'wp_delete_application_password', $user_id, $item );
return true;
}
}
return new WP_Error( 'application_password_not_found', __( 'Could not find an application password with that id.' ) );
}
/**
* Deletes all application passwords for the given user.
*
* @since 5.6.0
*
* @param int $user_id User ID.
* @return int|WP_Error The number of passwords that were deleted or a WP_Error on failure.
*/
public static function delete_all_application_passwords( $user_id ) {
$passwords = static::get_user_application_passwords( $user_id );
if ( $passwords ) {
$saved = static::set_user_application_passwords( $user_id, array() );
if ( ! $saved ) {
return new WP_Error( 'db_error', __( 'Could not delete application passwords.' ) );
}
foreach ( $passwords as $item ) {
/** This action is documented in wp-includes/class-wp-application-passwords.php */
do_action( 'wp_delete_application_password', $user_id, $item );
}
return count( $passwords );
}
return 0;
}
/**
* Sets a user's application passwords.
*
* @since 5.6.0
*
* @param int $user_id User ID.
* @param array $passwords Application passwords.
*
* @return bool
*/
protected static function set_user_application_passwords( $user_id, $passwords ) {
return update_user_meta( $user_id, static::USERMETA_KEY_APPLICATION_PASSWORDS, $passwords );
}
/**
* Sanitizes and then splits a password into smaller chunks.
*
* @since 5.6.0
*
* @param string $raw_password The raw application password.
* @return string The chunked password.
*/
public static function chunk_password( $raw_password ) {
$raw_password = preg_replace( '/[^a-z\d]/i', '', $raw_password );
return trim( chunk_split( $raw_password, 4, ' ' ) );
}
}
```
| programming_docs |
wordpress class WP_REST_Block_Pattern_Categories_Controller {} class WP\_REST\_Block\_Pattern\_Categories\_Controller {}
=========================================================
Core class used to access block pattern categories via the REST API.
* [WP\_REST\_Controller](wp_rest_controller)
* [\_\_construct](wp_rest_block_pattern_categories_controller/__construct) — Constructs the controller.
* [get\_item\_schema](wp_rest_block_pattern_categories_controller/get_item_schema) — Retrieves the block pattern category schema, conforming to JSON Schema.
* [get\_items](wp_rest_block_pattern_categories_controller/get_items) — Retrieves all block pattern categories.
* [get\_items\_permissions\_check](wp_rest_block_pattern_categories_controller/get_items_permissions_check) — Checks whether a given request has permission to read block patterns.
* [prepare\_item\_for\_response](wp_rest_block_pattern_categories_controller/prepare_item_for_response) — Prepare a raw block pattern category before it gets output in a REST API response.
* [register\_routes](wp_rest_block_pattern_categories_controller/register_routes) — Registers the routes for the objects of the controller.
File: `wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php/)
```
class WP_REST_Block_Pattern_Categories_Controller extends WP_REST_Controller {
/**
* Constructs the controller.
*
* @since 6.0.0
*/
public function __construct() {
$this->namespace = 'wp/v2';
$this->rest_base = 'block-patterns/categories';
}
/**
* 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 pattern categories.' ),
array( 'status' => rest_authorization_required_code() )
);
}
/**
* Retrieves all block pattern categories.
*
* @since 6.0.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 ) {
$response = array();
$categories = WP_Block_Pattern_Categories_Registry::get_instance()->get_all_registered();
foreach ( $categories as $category ) {
$prepared_category = $this->prepare_item_for_response( $category, $request );
$response[] = $this->prepare_response_for_collection( $prepared_category );
}
return rest_ensure_response( $response );
}
/**
* Prepare a raw block pattern category before it gets output in a REST API response.
*
* @since 6.0.0
*
* @param array $item Raw category 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', 'label' );
$data = array();
foreach ( $keys as $key ) {
if ( rest_is_field_included( $key, $fields ) ) {
$data[ $key ] = $item[ $key ];
}
}
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
return rest_ensure_response( $data );
}
/**
* Retrieves the block pattern category 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-category',
'type' => 'object',
'properties' => array(
'name' => array(
'description' => __( 'The category name.' ),
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
'label' => array(
'description' => __( 'The category label, in human readable format.' ),
'type' => 'string',
'readonly' => true,
'context' => array( 'view', 'edit', 'embed' ),
),
),
);
return $this->add_additional_fields_schema( $schema );
}
}
```
| Uses | Description |
| --- | --- |
| [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. |
wordpress class WP_Block_Supports {} class WP\_Block\_Supports {}
============================
Class encapsulating and implementing Block Supports.
* [apply\_block\_supports](wp_block_supports/apply_block_supports) — Generates an array of HTML attributes, such as classes, by applying to the given block all of the features that the block supports.
* [get\_instance](wp_block_supports/get_instance) — Utility method to retrieve the main instance of the class.
* [init](wp_block_supports/init) — Initializes the block supports. It registers the block supports block attributes.
* [register](wp_block_supports/register) — Registers a block support.
* [register\_attributes](wp_block_supports/register_attributes) — Registers the block attributes required by the different block supports.
File: `wp-includes/class-wp-block-supports.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-supports.php/)
```
class WP_Block_Supports {
/**
* Config.
*
* @since 5.6.0
* @var array
*/
private $block_supports = array();
/**
* Tracks the current block to be rendered.
*
* @since 5.6.0
* @var array
*/
public static $block_to_render = null;
/**
* Container for the main instance of the class.
*
* @since 5.6.0
* @var WP_Block_Supports|null
*/
private static $instance = null;
/**
* Utility method to retrieve the main instance of the class.
*
* The instance will be created if it does not exist yet.
*
* @since 5.6.0
*
* @return WP_Block_Supports The main instance.
*/
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Initializes the block supports. It registers the block supports block attributes.
*
* @since 5.6.0
*/
public static function init() {
$instance = self::get_instance();
$instance->register_attributes();
}
/**
* Registers a block support.
*
* @since 5.6.0
*
* @link https://developer.wordpress.org/block-editor/reference-guides/block-api/block-supports/
*
* @param string $block_support_name Block support name.
* @param array $block_support_config Array containing the properties of the block support.
*/
public function register( $block_support_name, $block_support_config ) {
$this->block_supports[ $block_support_name ] = array_merge(
$block_support_config,
array( 'name' => $block_support_name )
);
}
/**
* Generates an array of HTML attributes, such as classes, by applying to
* the given block all of the features that the block supports.
*
* @since 5.6.0
*
* @return string[] Array of HTML attributes.
*/
public function apply_block_supports() {
$block_type = WP_Block_Type_Registry::get_instance()->get_registered(
self::$block_to_render['blockName']
);
// If no render_callback, assume styles have been previously handled.
if ( ! $block_type || empty( $block_type ) ) {
return array();
}
$block_attributes = array_key_exists( 'attrs', self::$block_to_render )
? self::$block_to_render['attrs']
: array();
$output = array();
foreach ( $this->block_supports as $block_support_config ) {
if ( ! isset( $block_support_config['apply'] ) ) {
continue;
}
$new_attributes = call_user_func(
$block_support_config['apply'],
$block_type,
$block_attributes
);
if ( ! empty( $new_attributes ) ) {
foreach ( $new_attributes as $attribute_name => $attribute_value ) {
if ( empty( $output[ $attribute_name ] ) ) {
$output[ $attribute_name ] = $attribute_value;
} else {
$output[ $attribute_name ] .= " $attribute_value";
}
}
}
}
return $output;
}
/**
* Registers the block attributes required by the different block supports.
*
* @since 5.6.0
*/
private function register_attributes() {
$block_registry = WP_Block_Type_Registry::get_instance();
$registered_block_types = $block_registry->get_all_registered();
foreach ( $registered_block_types as $block_type ) {
if ( ! property_exists( $block_type, 'supports' ) ) {
continue;
}
if ( ! $block_type->attributes ) {
$block_type->attributes = array();
}
foreach ( $this->block_supports as $block_support_config ) {
if ( ! isset( $block_support_config['register_attribute'] ) ) {
continue;
}
call_user_func(
$block_support_config['register_attribute'],
$block_type
);
}
}
}
}
```
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress class WP_Theme_JSON {} class WP\_Theme\_JSON {}
========================
Class that encapsulates the processing of structures that adhere to the theme.json spec.
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.
* [\_\_construct](wp_theme_json/__construct) — Constructor.
* [append\_to\_selector](wp_theme_json/append_to_selector) — Appends a sub-selector to an existing one.
* [compute\_preset\_classes](wp_theme_json/compute_preset_classes) — Given a settings array, returns the generated rulesets for the preset classes.
* [compute\_preset\_vars](wp_theme_json/compute_preset_vars) — Given the block settings, extracts the CSS Custom Properties for the presets and adds them to the $declarations array following the format:
* [compute\_style\_properties](wp_theme_json/compute_style_properties) — Given a styles array, it extracts the style properties and adds them to the $declarations array following the format:
* [compute\_theme\_vars](wp_theme_json/compute_theme_vars) — Given an array of settings, extracts the CSS Custom Properties for the custom values and adds them to the $declarations array following the format:
* [do\_opt\_in\_into\_settings](wp_theme_json/do_opt_in_into_settings) — Enables some settings.
* [filter\_slugs](wp_theme_json/filter_slugs) — Removes the preset values whose slug is equal to any of given slugs.
* [flatten\_tree](wp_theme_json/flatten_tree) — Given a tree, it creates a flattened one by merging the keys and binding the leaf values to the new keys.
* [get\_block\_classes](wp_theme_json/get_block_classes) — Converts each style section into a list of rulesets containing the block styles to be appended to the stylesheet.
* [get\_block\_nodes](wp_theme_json/get_block_nodes) — An internal method to get the block nodes from a theme.json file.
* [get\_block\_styles](wp_theme_json/get_block_styles) — Converts each style section into a list of rulesets containing the block styles to be appended to the stylesheet.
* [get\_blocks\_metadata](wp_theme_json/get_blocks_metadata) — Returns the metadata for each block.
* [get\_css\_variables](wp_theme_json/get_css_variables) — Converts each styles section into a list of rulesets to be appended to the stylesheet.
* [get\_custom\_templates](wp_theme_json/get_custom_templates) — Returns the page templates of the active theme.
* [get\_data](wp_theme_json/get_data) — Returns a valid theme.json as provided by a theme.
* [get\_default\_slugs](wp_theme_json/get_default_slugs) — Returns the default slugs for all the presets in an associative array whose keys are the preset paths and the leafs is the list of slugs.
* [get\_element\_class\_name](wp_theme_json/get_element_class_name) — Returns a class name by an element name.
* [get\_from\_editor\_settings](wp_theme_json/get_from_editor_settings) — Transforms the given editor settings according the add\_theme\_support format to the theme.json format.
* [get\_layout\_styles](wp_theme_json/get_layout_styles) — Gets the CSS layout rules for a particular block from theme.json layout definitions.
* [get\_merged\_preset\_by\_slug](wp_theme_json/get_merged_preset_by_slug) — Given an array of presets keyed by origin and the value key of the preset, it returns an array where each key is the preset slug and each value the preset value.
* [get\_metadata\_boolean](wp_theme_json/get_metadata_boolean) — For metadata values that can either be booleans or paths to booleans, gets the value.
* [get\_name\_from\_defaults](wp_theme_json/get_name_from_defaults) — Gets a `default`'s preset name by a provided slug.
* [get\_patterns](wp_theme_json/get_patterns) — Returns the current theme's wanted patterns(slugs) to be registered from Pattern Directory.
* [get\_preset\_classes](wp_theme_json/get_preset_classes) — Creates new rulesets as classes for each preset value such as:
* [get\_property\_value](wp_theme_json/get_property_value) — Returns the style property for the given path.
* [get\_raw\_data](wp_theme_json/get_raw_data) — Returns the raw data.
* [get\_root\_layout\_rules](wp_theme_json/get_root_layout_rules) — Outputs the CSS for layout rules on the root.
* [get\_setting\_nodes](wp_theme_json/get_setting_nodes) — Builds metadata for the setting nodes, which returns in the form of:
* [get\_settings](wp_theme_json/get_settings) — Returns the existing settings for each block.
* [get\_settings\_slugs](wp_theme_json/get_settings_slugs) — Similar to get\_settings\_values\_by\_slug, but doesn't compute the value.
* [get\_settings\_values\_by\_slug](wp_theme_json/get_settings_values_by_slug) — Gets preset values keyed by slugs based on settings and metadata.
* [get\_style\_nodes](wp_theme_json/get_style_nodes) — Builds metadata for the style nodes, which returns in the form of:
* [get\_styles\_block\_nodes](wp_theme_json/get_styles_block_nodes) — A public helper to get the block nodes from a theme.json file.
* [get\_styles\_for\_block](wp_theme_json/get_styles_for_block) — Gets the CSS rules for a particular block from theme.json.
* [get\_stylesheet](wp_theme_json/get_stylesheet) — Returns the stylesheet that results of processing the theme.json structure this object represents.
* [get\_svg\_filters](wp_theme_json/get_svg_filters) — Converts all filter (duotone) presets into SVGs.
* [get\_template\_parts](wp_theme_json/get_template_parts) — Returns the template part data of active theme.
* [has\_properties](wp_theme_json/has_properties) — Whether the metadata contains a key named properties.
* [is\_safe\_css\_declaration](wp_theme_json/is_safe_css_declaration) — Checks that a declaration provided by the user is safe.
* [maybe\_opt\_in\_into\_settings](wp_theme_json/maybe_opt_in_into_settings) — Enables some opt-in settings if theme declared support.
* [merge](wp_theme_json/merge) — Merges new incoming data.
* [remove\_insecure\_properties](wp_theme_json/remove_insecure_properties) — Removes insecure data from theme.json.
* [remove\_insecure\_settings](wp_theme_json/remove_insecure_settings) — Processes a setting node and returns the same node without the insecure settings.
* [remove\_insecure\_styles](wp_theme_json/remove_insecure_styles) — Processes a style node and returns the same node without the insecure styles.
* [remove\_keys\_not\_in\_schema](wp_theme_json/remove_keys_not_in_schema) — Given a tree, removes the keys that are not present in the schema.
* [replace\_slug\_in\_string](wp_theme_json/replace_slug_in_string) — Transforms a slug into a CSS Custom Property.
* [sanitize](wp_theme_json/sanitize) — Sanitizes the input according to the schemas.
* [scope\_selector](wp_theme_json/scope_selector) — Function that scopes a selector with another one. This works a bit like SCSS nesting except the `&` operator isn't supported.
* [set\_spacing\_sizes](wp_theme_json/set_spacing_sizes) — Sets the spacingSizes array based on the spacingScale values from theme.json.
* [should\_override\_preset](wp_theme_json/should_override_preset) — Determines whether a presets should be overridden or not. — deprecated
* [to\_ruleset](wp_theme_json/to_ruleset) — Given a selector and a declaration list, creates the corresponding ruleset.
File: `wp-includes/class-wp-theme-json.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme-json.php/)
```
class WP_Theme_JSON {
/**
* Container of data in theme.json format.
*
* @since 5.8.0
* @var array
*/
protected $theme_json = null;
/**
* Holds block metadata extracted from block.json
* to be shared among all instances so we don't
* process it twice.
*
* @since 5.8.0
* @since 6.1.0 Initialize as an empty array.
* @var array
*/
protected static $blocks_metadata = array();
/**
* The CSS selector for the top-level styles.
*
* @since 5.8.0
* @var string
*/
const ROOT_BLOCK_SELECTOR = 'body';
/**
* The sources of data this object can represent.
*
* @since 5.8.0
* @since 6.1.0 Added 'blocks'.
* @var string[]
*/
const VALID_ORIGINS = array(
'default',
'blocks',
'theme',
'custom',
);
/**
* Presets are a set of values that serve
* to bootstrap some styles: colors, font sizes, etc.
*
* They are a unkeyed array of values such as:
*
* ```php
* array(
* array(
* 'slug' => 'unique-name-within-the-set',
* 'name' => 'Name for the UI',
* <value_key> => 'value'
* ),
* )
* ```
*
* This contains the necessary metadata to process them:
*
* - path => Where to find the preset within the settings section.
* - prevent_override => Disables override of default presets by theme presets.
* The relationship between whether to override the defaults
* and whether the defaults are enabled is inverse:
* - If defaults are enabled => theme presets should not be overriden
* - If defaults are disabled => theme presets should be overriden
* For example, a theme sets defaultPalette to false,
* making the default palette hidden from the user.
* In that case, we want all the theme presets to be present,
* so they should override the defaults by setting this false.
* - use_default_names => whether to use the default names
* - value_key => the key that represents the value
* - value_func => optionally, instead of value_key, a function to generate
* the value that takes a preset as an argument
* (either value_key or value_func should be present)
* - css_vars => template string to use in generating the CSS Custom Property.
* Example output: "--wp--preset--duotone--blue: <value>" will generate as many CSS Custom Properties as presets defined
* substituting the $slug for the slug's value for each preset value.
* - classes => array containing a structure with the classes to
* generate for the presets, where for each array item
* the key is the class name and the value the property name.
* The "$slug" substring will be replaced by the slug of each preset.
* For example:
* 'classes' => array(
* '.has-$slug-color' => 'color',
* '.has-$slug-background-color' => 'background-color',
* '.has-$slug-border-color' => 'border-color',
* )
* - properties => array of CSS properties to be used by kses to
* validate the content of each preset
* by means of the remove_insecure_properties method.
*
* @since 5.8.0
* @since 5.9.0 Added the `color.duotone` and `typography.fontFamilies` presets,
* `use_default_names` preset key, and simplified the metadata structure.
* @since 6.0.0 Replaced `override` with `prevent_override` and updated the
* `prevent_overried` value for `color.duotone` to use `color.defaultDuotone`.
* @var array
*/
const PRESETS_METADATA = array(
array(
'path' => array( 'color', 'palette' ),
'prevent_override' => array( 'color', 'defaultPalette' ),
'use_default_names' => false,
'value_key' => 'color',
'css_vars' => '--wp--preset--color--$slug',
'classes' => array(
'.has-$slug-color' => 'color',
'.has-$slug-background-color' => 'background-color',
'.has-$slug-border-color' => 'border-color',
),
'properties' => array( 'color', 'background-color', 'border-color' ),
),
array(
'path' => array( 'color', 'gradients' ),
'prevent_override' => array( 'color', 'defaultGradients' ),
'use_default_names' => false,
'value_key' => 'gradient',
'css_vars' => '--wp--preset--gradient--$slug',
'classes' => array( '.has-$slug-gradient-background' => 'background' ),
'properties' => array( 'background' ),
),
array(
'path' => array( 'color', 'duotone' ),
'prevent_override' => array( 'color', 'defaultDuotone' ),
'use_default_names' => false,
'value_func' => 'wp_get_duotone_filter_property',
'css_vars' => '--wp--preset--duotone--$slug',
'classes' => array(),
'properties' => array( 'filter' ),
),
array(
'path' => array( 'typography', 'fontSizes' ),
'prevent_override' => false,
'use_default_names' => true,
'value_func' => 'wp_get_typography_font_size_value',
'css_vars' => '--wp--preset--font-size--$slug',
'classes' => array( '.has-$slug-font-size' => 'font-size' ),
'properties' => array( 'font-size' ),
),
array(
'path' => array( 'typography', 'fontFamilies' ),
'prevent_override' => false,
'use_default_names' => false,
'value_key' => 'fontFamily',
'css_vars' => '--wp--preset--font-family--$slug',
'classes' => array( '.has-$slug-font-family' => 'font-family' ),
'properties' => array( 'font-family' ),
),
array(
'path' => array( 'spacing', 'spacingSizes' ),
'prevent_override' => false,
'use_default_names' => true,
'value_key' => 'size',
'css_vars' => '--wp--preset--spacing--$slug',
'classes' => array(),
'properties' => array( 'padding', 'margin' ),
),
);
/**
* Metadata for style properties.
*
* Each element is a direct mapping from the CSS property name to the
* path to the value in theme.json & block attributes.
*
* @since 5.8.0
* @since 5.9.0 Added the `border-*`, `font-family`, `font-style`, `font-weight`,
* `letter-spacing`, `margin-*`, `padding-*`, `--wp--style--block-gap`,
* `text-decoration`, `text-transform`, and `filter` properties,
* simplified the metadata structure.
* @since 6.1.0 Added the `border-*-color`, `border-*-width`, `border-*-style`,
* `--wp--style--root--padding-*`, and `box-shadow` properties,
* removed the `--wp--style--block-gap` property.
* @var array
*/
const PROPERTIES_METADATA = array(
'background' => array( 'color', 'gradient' ),
'background-color' => array( 'color', 'background' ),
'border-radius' => array( 'border', 'radius' ),
'border-top-left-radius' => array( 'border', 'radius', 'topLeft' ),
'border-top-right-radius' => array( 'border', 'radius', 'topRight' ),
'border-bottom-left-radius' => array( 'border', 'radius', 'bottomLeft' ),
'border-bottom-right-radius' => array( 'border', 'radius', 'bottomRight' ),
'border-color' => array( 'border', 'color' ),
'border-width' => array( 'border', 'width' ),
'border-style' => array( 'border', 'style' ),
'border-top-color' => array( 'border', 'top', 'color' ),
'border-top-width' => array( 'border', 'top', 'width' ),
'border-top-style' => array( 'border', 'top', 'style' ),
'border-right-color' => array( 'border', 'right', 'color' ),
'border-right-width' => array( 'border', 'right', 'width' ),
'border-right-style' => array( 'border', 'right', 'style' ),
'border-bottom-color' => array( 'border', 'bottom', 'color' ),
'border-bottom-width' => array( 'border', 'bottom', 'width' ),
'border-bottom-style' => array( 'border', 'bottom', 'style' ),
'border-left-color' => array( 'border', 'left', 'color' ),
'border-left-width' => array( 'border', 'left', 'width' ),
'border-left-style' => array( 'border', 'left', 'style' ),
'color' => array( 'color', 'text' ),
'font-family' => array( 'typography', 'fontFamily' ),
'font-size' => array( 'typography', 'fontSize' ),
'font-style' => array( 'typography', 'fontStyle' ),
'font-weight' => array( 'typography', 'fontWeight' ),
'letter-spacing' => array( 'typography', 'letterSpacing' ),
'line-height' => array( 'typography', 'lineHeight' ),
'margin' => array( 'spacing', 'margin' ),
'margin-top' => array( 'spacing', 'margin', 'top' ),
'margin-right' => array( 'spacing', 'margin', 'right' ),
'margin-bottom' => array( 'spacing', 'margin', 'bottom' ),
'margin-left' => array( 'spacing', 'margin', 'left' ),
'padding' => array( 'spacing', 'padding' ),
'padding-top' => array( 'spacing', 'padding', 'top' ),
'padding-right' => array( 'spacing', 'padding', 'right' ),
'padding-bottom' => array( 'spacing', 'padding', 'bottom' ),
'padding-left' => array( 'spacing', 'padding', 'left' ),
'--wp--style--root--padding' => array( 'spacing', 'padding' ),
'--wp--style--root--padding-top' => array( 'spacing', 'padding', 'top' ),
'--wp--style--root--padding-right' => array( 'spacing', 'padding', 'right' ),
'--wp--style--root--padding-bottom' => array( 'spacing', 'padding', 'bottom' ),
'--wp--style--root--padding-left' => array( 'spacing', 'padding', 'left' ),
'text-decoration' => array( 'typography', 'textDecoration' ),
'text-transform' => array( 'typography', 'textTransform' ),
'filter' => array( 'filter', 'duotone' ),
'box-shadow' => array( 'shadow' ),
);
/**
* Protected style properties.
*
* These style properties are only rendered if a setting enables it
* via a value other than `null`.
*
* Each element maps the style property to the corresponding theme.json
* setting key.
*
* @since 5.9.0
*/
const PROTECTED_PROPERTIES = array(
'spacing.blockGap' => array( 'spacing', 'blockGap' ),
);
/**
* The top-level keys a theme.json can have.
*
* @since 5.8.0 As `ALLOWED_TOP_LEVEL_KEYS`.
* @since 5.9.0 Renamed from `ALLOWED_TOP_LEVEL_KEYS` to `VALID_TOP_LEVEL_KEYS`,
* added the `customTemplates` and `templateParts` values.
* @var string[]
*/
const VALID_TOP_LEVEL_KEYS = array(
'customTemplates',
'patterns',
'settings',
'styles',
'templateParts',
'version',
'title',
);
/**
* The valid properties under the settings key.
*
* @since 5.8.0 As `ALLOWED_SETTINGS`.
* @since 5.9.0 Renamed from `ALLOWED_SETTINGS` to `VALID_SETTINGS`,
* added new properties for `border`, `color`, `spacing`,
* and `typography`, and renamed others according to the new schema.
* @since 6.0.0 Added `color.defaultDuotone`.
* @since 6.1.0 Added `layout.definitions` and `useRootPaddingAwareAlignments`.
* @var array
*/
const VALID_SETTINGS = array(
'appearanceTools' => null,
'useRootPaddingAwareAlignments' => null,
'border' => array(
'color' => null,
'radius' => null,
'style' => null,
'width' => null,
),
'color' => array(
'background' => null,
'custom' => null,
'customDuotone' => null,
'customGradient' => null,
'defaultDuotone' => null,
'defaultGradients' => null,
'defaultPalette' => null,
'duotone' => null,
'gradients' => null,
'link' => null,
'palette' => null,
'text' => null,
),
'custom' => null,
'layout' => array(
'contentSize' => null,
'definitions' => null,
'wideSize' => null,
),
'spacing' => array(
'customSpacingSize' => null,
'spacingSizes' => null,
'spacingScale' => null,
'blockGap' => null,
'margin' => null,
'padding' => null,
'units' => null,
),
'typography' => array(
'fluid' => null,
'customFontSize' => null,
'dropCap' => null,
'fontFamilies' => null,
'fontSizes' => null,
'fontStyle' => null,
'fontWeight' => null,
'letterSpacing' => null,
'lineHeight' => null,
'textDecoration' => null,
'textTransform' => null,
),
);
/**
* The valid properties under the styles key.
*
* @since 5.8.0 As `ALLOWED_STYLES`.
* @since 5.9.0 Renamed from `ALLOWED_STYLES` to `VALID_STYLES`,
* added new properties for `border`, `filter`, `spacing`,
* and `typography`.
* @since 6.1.0 Added new side properties for `border`,
* added new property `shadow`,
* updated `blockGap` to be allowed at any level.
* @var array
*/
const VALID_STYLES = array(
'border' => array(
'color' => null,
'radius' => null,
'style' => null,
'width' => null,
'top' => null,
'right' => null,
'bottom' => null,
'left' => null,
),
'color' => array(
'background' => null,
'gradient' => null,
'text' => null,
),
'filter' => array(
'duotone' => null,
),
'shadow' => null,
'spacing' => array(
'margin' => null,
'padding' => null,
'blockGap' => null,
),
'typography' => array(
'fontFamily' => null,
'fontSize' => null,
'fontStyle' => null,
'fontWeight' => null,
'letterSpacing' => null,
'lineHeight' => null,
'textDecoration' => null,
'textTransform' => null,
),
);
/**
* Defines which pseudo selectors are enabled for which elements.
*
* Note: this will affect both top-level and block-level elements.
*
* @since 6.1.0
*/
const VALID_ELEMENT_PSEUDO_SELECTORS = array(
'link' => array( ':hover', ':focus', ':active', ':visited' ),
'button' => array( ':hover', ':focus', ':active', ':visited' ),
);
/**
* The valid elements that can be found under styles.
*
* @since 5.8.0
* @since 6.1.0 Added `heading`, `button`. and `caption` elements.
* @var string[]
*/
const ELEMENTS = array(
'link' => 'a:where(:not(.wp-element-button))', // The `where` is needed to lower the specificity.
'heading' => 'h1, h2, h3, h4, h5, h6',
'h1' => 'h1',
'h2' => 'h2',
'h3' => 'h3',
'h4' => 'h4',
'h5' => 'h5',
'h6' => 'h6',
// We have the .wp-block-button__link class so that this will target older buttons that have been serialized.
'button' => '.wp-element-button, .wp-block-button__link',
// The block classes are necessary to target older content that won't use the new class names.
'caption' => '.wp-element-caption, .wp-block-audio figcaption, .wp-block-embed figcaption, .wp-block-gallery figcaption, .wp-block-image figcaption, .wp-block-table figcaption, .wp-block-video figcaption',
'cite' => 'cite',
);
const __EXPERIMENTAL_ELEMENT_CLASS_NAMES = array(
'button' => 'wp-element-button',
'caption' => 'wp-element-caption',
);
/**
* List of block support features that can have their related styles
* generated under their own feature level selector rather than the block's.
*
* @since 6.1.0
* @var string[]
*/
const BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS = array(
'__experimentalBorder' => 'border',
'color' => 'color',
'spacing' => 'spacing',
'typography' => 'typography',
);
/**
* Returns a class name by an element name.
*
* @since 6.1.0
*
* @param string $element The name of the element.
* @return string The name of the class.
*/
public static function get_element_class_name( $element ) {
$class_name = '';
if ( array_key_exists( $element, static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES ) ) {
$class_name = static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $element ];
}
return $class_name;
}
/**
* Options that settings.appearanceTools enables.
*
* @since 6.0.0
* @var array
*/
const APPEARANCE_TOOLS_OPT_INS = array(
array( 'border', 'color' ),
array( 'border', 'radius' ),
array( 'border', 'style' ),
array( 'border', 'width' ),
array( 'color', 'link' ),
array( 'spacing', 'blockGap' ),
array( 'spacing', 'margin' ),
array( 'spacing', 'padding' ),
array( 'typography', 'lineHeight' ),
);
/**
* The latest version of the schema in use.
*
* @since 5.8.0
* @since 5.9.0 Changed value from 1 to 2.
* @var int
*/
const LATEST_SCHEMA = 2;
/**
* Constructor.
*
* @since 5.8.0
*
* @param array $theme_json A structure that follows the theme.json schema.
* @param string $origin Optional. What source of data this object represents.
* One of 'default', 'theme', or 'custom'. Default 'theme'.
*/
public function __construct( $theme_json = array(), $origin = 'theme' ) {
if ( ! in_array( $origin, static::VALID_ORIGINS, true ) ) {
$origin = 'theme';
}
$this->theme_json = WP_Theme_JSON_Schema::migrate( $theme_json );
$valid_block_names = array_keys( static::get_blocks_metadata() );
$valid_element_names = array_keys( static::ELEMENTS );
$theme_json = static::sanitize( $this->theme_json, $valid_block_names, $valid_element_names );
$this->theme_json = static::maybe_opt_in_into_settings( $theme_json );
// Internally, presets are keyed by origin.
$nodes = static::get_setting_nodes( $this->theme_json );
foreach ( $nodes as $node ) {
foreach ( static::PRESETS_METADATA as $preset_metadata ) {
$path = array_merge( $node['path'], $preset_metadata['path'] );
$preset = _wp_array_get( $this->theme_json, $path, null );
if ( null !== $preset ) {
// If the preset is not already keyed by origin.
if ( isset( $preset[0] ) || empty( $preset ) ) {
_wp_array_set( $this->theme_json, $path, array( $origin => $preset ) );
}
}
}
}
}
/**
* Enables some opt-in settings if theme declared support.
*
* @since 5.9.0
*
* @param array $theme_json A theme.json structure to modify.
* @return array The modified theme.json structure.
*/
protected static function maybe_opt_in_into_settings( $theme_json ) {
$new_theme_json = $theme_json;
if (
isset( $new_theme_json['settings']['appearanceTools'] ) &&
true === $new_theme_json['settings']['appearanceTools']
) {
static::do_opt_in_into_settings( $new_theme_json['settings'] );
}
if ( isset( $new_theme_json['settings']['blocks'] ) && is_array( $new_theme_json['settings']['blocks'] ) ) {
foreach ( $new_theme_json['settings']['blocks'] as &$block ) {
if ( isset( $block['appearanceTools'] ) && ( true === $block['appearanceTools'] ) ) {
static::do_opt_in_into_settings( $block );
}
}
}
return $new_theme_json;
}
/**
* Enables some settings.
*
* @since 5.9.0
*
* @param array $context The context to which the settings belong.
*/
protected static function do_opt_in_into_settings( &$context ) {
foreach ( static::APPEARANCE_TOOLS_OPT_INS as $path ) {
// Use "unset prop" as a marker instead of "null" because
// "null" can be a valid value for some props (e.g. blockGap).
if ( 'unset prop' === _wp_array_get( $context, $path, 'unset prop' ) ) {
_wp_array_set( $context, $path, true );
}
}
unset( $context['appearanceTools'] );
}
/**
* Sanitizes the input according to the schemas.
*
* @since 5.8.0
* @since 5.9.0 Added the `$valid_block_names` and `$valid_element_name` parameters.
*
* @param array $input Structure to sanitize.
* @param array $valid_block_names List of valid block names.
* @param array $valid_element_names List of valid element names.
* @return array The sanitized output.
*/
protected static function sanitize( $input, $valid_block_names, $valid_element_names ) {
$output = array();
if ( ! is_array( $input ) ) {
return $output;
}
// Preserve only the top most level keys.
$output = array_intersect_key( $input, array_flip( static::VALID_TOP_LEVEL_KEYS ) );
/*
* Remove any rules that are annotated as "top" in VALID_STYLES constant.
* Some styles are only meant to be available at the top-level (e.g.: blockGap),
* hence, the schema for blocks & elements should not have them.
*/
$styles_non_top_level = static::VALID_STYLES;
foreach ( array_keys( $styles_non_top_level ) as $section ) {
if ( array_key_exists( $section, $styles_non_top_level ) && is_array( $styles_non_top_level[ $section ] ) ) {
foreach ( array_keys( $styles_non_top_level[ $section ] ) as $prop ) {
if ( 'top' === $styles_non_top_level[ $section ][ $prop ] ) {
unset( $styles_non_top_level[ $section ][ $prop ] );
}
}
}
}
// Build the schema based on valid block & element names.
$schema = array();
$schema_styles_elements = array();
/*
* Set allowed element pseudo selectors based on per element allow list.
* Target data structure in schema:
* e.g.
* - top level elements: `$schema['styles']['elements']['link'][':hover']`.
* - block level elements: `$schema['styles']['blocks']['core/button']['elements']['link'][':hover']`.
*/
foreach ( $valid_element_names as $element ) {
$schema_styles_elements[ $element ] = $styles_non_top_level;
if ( array_key_exists( $element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ) {
foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
$schema_styles_elements[ $element ][ $pseudo_selector ] = $styles_non_top_level;
}
}
}
$schema_styles_blocks = array();
$schema_settings_blocks = array();
foreach ( $valid_block_names as $block ) {
$schema_settings_blocks[ $block ] = static::VALID_SETTINGS;
$schema_styles_blocks[ $block ] = $styles_non_top_level;
$schema_styles_blocks[ $block ]['elements'] = $schema_styles_elements;
}
$schema['styles'] = static::VALID_STYLES;
$schema['styles']['blocks'] = $schema_styles_blocks;
$schema['styles']['elements'] = $schema_styles_elements;
$schema['settings'] = static::VALID_SETTINGS;
$schema['settings']['blocks'] = $schema_settings_blocks;
// Remove anything that's not present in the schema.
foreach ( array( 'styles', 'settings' ) as $subtree ) {
if ( ! isset( $input[ $subtree ] ) ) {
continue;
}
if ( ! is_array( $input[ $subtree ] ) ) {
unset( $output[ $subtree ] );
continue;
}
$result = static::remove_keys_not_in_schema( $input[ $subtree ], $schema[ $subtree ] );
if ( empty( $result ) ) {
unset( $output[ $subtree ] );
} else {
$output[ $subtree ] = $result;
}
}
return $output;
}
/**
* Appends a sub-selector to an existing one.
*
* Given the compounded $selector "h1, h2, h3"
* and the $to_append selector ".some-class" the result will be
* "h1.some-class, h2.some-class, h3.some-class".
*
* @since 5.8.0
* @since 6.1.0 Added append position.
*
* @param string $selector Original selector.
* @param string $to_append Selector to append.
* @param string $position A position sub-selector should be appended. Default 'right'.
* @return string The new selector.
*/
protected static function append_to_selector( $selector, $to_append, $position = 'right' ) {
$new_selectors = array();
$selectors = explode( ',', $selector );
foreach ( $selectors as $sel ) {
$new_selectors[] = 'right' === $position ? $sel . $to_append : $to_append . $sel;
}
return implode( ',', $new_selectors );
}
/**
* Returns the metadata for each block.
*
* Example:
*
* {
* 'core/paragraph': {
* 'selector': 'p',
* 'elements': {
* 'link' => 'link selector',
* 'etc' => 'element selector'
* }
* },
* 'core/heading': {
* 'selector': 'h1',
* 'elements': {}
* },
* 'core/image': {
* 'selector': '.wp-block-image',
* 'duotone': 'img',
* 'elements': {}
* }
* }
*
* @since 5.8.0
* @since 5.9.0 Added `duotone` key with CSS selector.
* @since 6.1.0 Added `features` key with block support feature level selectors.
*
* @return array Block metadata.
*/
protected static function get_blocks_metadata() {
$registry = WP_Block_Type_Registry::get_instance();
$blocks = $registry->get_all_registered();
// Is there metadata for all currently registered blocks?
$blocks = array_diff_key( $blocks, static::$blocks_metadata );
if ( empty( $blocks ) ) {
return static::$blocks_metadata;
}
foreach ( $blocks as $block_name => $block_type ) {
if (
isset( $block_type->supports['__experimentalSelector'] ) &&
is_string( $block_type->supports['__experimentalSelector'] )
) {
static::$blocks_metadata[ $block_name ]['selector'] = $block_type->supports['__experimentalSelector'];
} else {
static::$blocks_metadata[ $block_name ]['selector'] = '.wp-block-' . str_replace( '/', '-', str_replace( 'core/', '', $block_name ) );
}
if (
isset( $block_type->supports['color']['__experimentalDuotone'] ) &&
is_string( $block_type->supports['color']['__experimentalDuotone'] )
) {
static::$blocks_metadata[ $block_name ]['duotone'] = $block_type->supports['color']['__experimentalDuotone'];
}
// Generate block support feature level selectors if opted into
// for the current block.
$features = array();
foreach ( static::BLOCK_SUPPORT_FEATURE_LEVEL_SELECTORS as $key => $feature ) {
if (
isset( $block_type->supports[ $key ]['__experimentalSelector'] ) &&
$block_type->supports[ $key ]['__experimentalSelector']
) {
$features[ $feature ] = static::scope_selector(
static::$blocks_metadata[ $block_name ]['selector'],
$block_type->supports[ $key ]['__experimentalSelector']
);
}
}
if ( ! empty( $features ) ) {
static::$blocks_metadata[ $block_name ]['features'] = $features;
}
// Assign defaults, then overwrite those that the block sets by itself.
// If the block selector is compounded, will append the element to each
// individual block selector.
$block_selectors = explode( ',', static::$blocks_metadata[ $block_name ]['selector'] );
foreach ( static::ELEMENTS as $el_name => $el_selector ) {
$element_selector = array();
foreach ( $block_selectors as $selector ) {
if ( $selector === $el_selector ) {
$element_selector = array( $el_selector );
break;
}
$element_selector[] = static::append_to_selector( $el_selector, $selector . ' ', 'left' );
}
static::$blocks_metadata[ $block_name ]['elements'][ $el_name ] = implode( ',', $element_selector );
}
}
return static::$blocks_metadata;
}
/**
* Given a tree, removes the keys that are not present in the schema.
*
* It is recursive and modifies the input in-place.
*
* @since 5.8.0
*
* @param array $tree Input to process.
* @param array $schema Schema to adhere to.
* @return array The modified $tree.
*/
protected static function remove_keys_not_in_schema( $tree, $schema ) {
$tree = array_intersect_key( $tree, $schema );
foreach ( $schema as $key => $data ) {
if ( ! isset( $tree[ $key ] ) ) {
continue;
}
if ( is_array( $schema[ $key ] ) && is_array( $tree[ $key ] ) ) {
$tree[ $key ] = static::remove_keys_not_in_schema( $tree[ $key ], $schema[ $key ] );
if ( empty( $tree[ $key ] ) ) {
unset( $tree[ $key ] );
}
} elseif ( is_array( $schema[ $key ] ) && ! is_array( $tree[ $key ] ) ) {
unset( $tree[ $key ] );
}
}
return $tree;
}
/**
* Returns the existing settings for each block.
*
* Example:
*
* {
* 'root': {
* 'color': {
* 'custom': true
* }
* },
* 'core/paragraph': {
* 'spacing': {
* 'customPadding': true
* }
* }
* }
*
* @since 5.8.0
*
* @return array Settings per block.
*/
public function get_settings() {
if ( ! isset( $this->theme_json['settings'] ) ) {
return array();
} else {
return $this->theme_json['settings'];
}
}
/**
* Returns the stylesheet that results of processing
* the theme.json structure this object represents.
*
* @since 5.8.0
* @since 5.9.0 Removed the `$type` parameter`, added the `$types` and `$origins` parameters.
*
* @param array $types Types of styles to load. Will load all by default. It accepts:
* - `variables`: only the CSS Custom Properties for presets & custom ones.
* - `styles`: only the styles section in theme.json.
* - `presets`: only the classes for the presets.
* @param array $origins A list of origins to include. By default it includes VALID_ORIGINS.
* @return string The resulting stylesheet.
*/
public function get_stylesheet( $types = array( 'variables', 'styles', 'presets' ), $origins = null ) {
if ( null === $origins ) {
$origins = static::VALID_ORIGINS;
}
if ( is_string( $types ) ) {
// Dispatch error and map old arguments to new ones.
_deprecated_argument( __FUNCTION__, '5.9.0' );
if ( 'block_styles' === $types ) {
$types = array( 'styles', 'presets' );
} elseif ( 'css_variables' === $types ) {
$types = array( 'variables' );
} else {
$types = array( 'variables', 'styles', 'presets' );
}
}
$blocks_metadata = static::get_blocks_metadata();
$style_nodes = static::get_style_nodes( $this->theme_json, $blocks_metadata );
$setting_nodes = static::get_setting_nodes( $this->theme_json, $blocks_metadata );
$stylesheet = '';
if ( in_array( 'variables', $types, true ) ) {
$stylesheet .= $this->get_css_variables( $setting_nodes, $origins );
}
if ( in_array( 'styles', $types, true ) ) {
$root_block_key = array_search( static::ROOT_BLOCK_SELECTOR, array_column( $style_nodes, 'selector' ), true );
if ( false !== $root_block_key ) {
$stylesheet .= $this->get_root_layout_rules( static::ROOT_BLOCK_SELECTOR, $style_nodes[ $root_block_key ] );
}
$stylesheet .= $this->get_block_classes( $style_nodes );
} elseif ( in_array( 'base-layout-styles', $types, true ) ) {
// Base layout styles are provided as part of `styles`, so only output separately if explicitly requested.
// For backwards compatibility, the Columns block is explicitly included, to support a different default gap value.
$base_styles_nodes = array(
array(
'path' => array( 'styles' ),
'selector' => static::ROOT_BLOCK_SELECTOR,
),
array(
'path' => array( 'styles', 'blocks', 'core/columns' ),
'selector' => '.wp-block-columns',
'name' => 'core/columns',
),
);
foreach ( $base_styles_nodes as $base_style_node ) {
$stylesheet .= $this->get_layout_styles( $base_style_node );
}
}
if ( in_array( 'presets', $types, true ) ) {
$stylesheet .= $this->get_preset_classes( $setting_nodes, $origins );
}
return $stylesheet;
}
/**
* Returns the page templates of the active theme.
*
* @since 5.9.0
*
* @return array
*/
public function get_custom_templates() {
$custom_templates = array();
if ( ! isset( $this->theme_json['customTemplates'] ) || ! is_array( $this->theme_json['customTemplates'] ) ) {
return $custom_templates;
}
foreach ( $this->theme_json['customTemplates'] as $item ) {
if ( isset( $item['name'] ) ) {
$custom_templates[ $item['name'] ] = array(
'title' => isset( $item['title'] ) ? $item['title'] : '',
'postTypes' => isset( $item['postTypes'] ) ? $item['postTypes'] : array( 'page' ),
);
}
}
return $custom_templates;
}
/**
* Returns the template part data of active theme.
*
* @since 5.9.0
*
* @return array
*/
public function get_template_parts() {
$template_parts = array();
if ( ! isset( $this->theme_json['templateParts'] ) || ! is_array( $this->theme_json['templateParts'] ) ) {
return $template_parts;
}
foreach ( $this->theme_json['templateParts'] as $item ) {
if ( isset( $item['name'] ) ) {
$template_parts[ $item['name'] ] = array(
'title' => isset( $item['title'] ) ? $item['title'] : '',
'area' => isset( $item['area'] ) ? $item['area'] : '',
);
}
}
return $template_parts;
}
/**
* Converts each style section into a list of rulesets
* containing the block styles to be appended to the stylesheet.
*
* See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax
*
* For each section this creates a new ruleset such as:
*
* block-selector {
* style-property-one: value;
* }
*
* @since 5.8.0 As `get_block_styles()`.
* @since 5.9.0 Renamed from `get_block_styles()` to `get_block_classes()`
* and no longer returns preset classes.
* Removed the `$setting_nodes` parameter.
* @since 6.1.0 Moved most internal logic to `get_styles_for_block()`.
*
* @param array $style_nodes Nodes with styles.
* @return string The new stylesheet.
*/
protected function get_block_classes( $style_nodes ) {
$block_rules = '';
foreach ( $style_nodes as $metadata ) {
if ( null === $metadata['selector'] ) {
continue;
}
$block_rules .= static::get_styles_for_block( $metadata );
}
return $block_rules;
}
/**
* Gets the CSS layout rules for a particular block from theme.json layout definitions.
*
* @since 6.1.0
*
* @param array $block_metadata Metadata about the block to get styles for.
* @return string Layout styles for the block.
*/
protected function get_layout_styles( $block_metadata ) {
$block_rules = '';
$block_type = null;
// Skip outputting layout styles if explicitly disabled.
if ( current_theme_supports( 'disable-layout-styles' ) ) {
return $block_rules;
}
if ( isset( $block_metadata['name'] ) ) {
$block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block_metadata['name'] );
if ( ! block_has_support( $block_type, array( '__experimentalLayout' ), false ) ) {
return $block_rules;
}
}
$selector = isset( $block_metadata['selector'] ) ? $block_metadata['selector'] : '';
$has_block_gap_support = _wp_array_get( $this->theme_json, array( 'settings', 'spacing', 'blockGap' ) ) !== null;
$has_fallback_gap_support = ! $has_block_gap_support; // This setting isn't useful yet: it exists as a placeholder for a future explicit fallback gap styles support.
$node = _wp_array_get( $this->theme_json, $block_metadata['path'], array() );
$layout_definitions = _wp_array_get( $this->theme_json, array( 'settings', 'layout', 'definitions' ), array() );
$layout_selector_pattern = '/^[a-zA-Z0-9\-\.\ *+>:\(\)]*$/'; // Allow alphanumeric classnames, spaces, wildcard, sibling, child combinator and pseudo class selectors.
// Gap styles will only be output if the theme has block gap support, or supports a fallback gap.
// Default layout gap styles will be skipped for themes that do not explicitly opt-in to blockGap with a `true` or `false` value.
if ( $has_block_gap_support || $has_fallback_gap_support ) {
$block_gap_value = null;
// Use a fallback gap value if block gap support is not available.
if ( ! $has_block_gap_support ) {
$block_gap_value = static::ROOT_BLOCK_SELECTOR === $selector ? '0.5em' : null;
if ( ! empty( $block_type ) ) {
$block_gap_value = _wp_array_get( $block_type->supports, array( 'spacing', 'blockGap', '__experimentalDefault' ), null );
}
} else {
$block_gap_value = static::get_property_value( $node, array( 'spacing', 'blockGap' ) );
}
// Support split row / column values and concatenate to a shorthand value.
if ( is_array( $block_gap_value ) ) {
if ( isset( $block_gap_value['top'] ) && isset( $block_gap_value['left'] ) ) {
$gap_row = static::get_property_value( $node, array( 'spacing', 'blockGap', 'top' ) );
$gap_column = static::get_property_value( $node, array( 'spacing', 'blockGap', 'left' ) );
$block_gap_value = $gap_row === $gap_column ? $gap_row : $gap_row . ' ' . $gap_column;
} else {
// Skip outputting gap value if not all sides are provided.
$block_gap_value = null;
}
}
// If the block should have custom gap, add the gap styles.
if ( null !== $block_gap_value && false !== $block_gap_value && '' !== $block_gap_value ) {
foreach ( $layout_definitions as $layout_definition_key => $layout_definition ) {
// Allow outputting fallback gap styles for flex layout type when block gap support isn't available.
if ( ! $has_block_gap_support && 'flex' !== $layout_definition_key ) {
continue;
}
$class_name = sanitize_title( _wp_array_get( $layout_definition, array( 'className' ), false ) );
$spacing_rules = _wp_array_get( $layout_definition, array( 'spacingStyles' ), array() );
if (
! empty( $class_name ) &&
! empty( $spacing_rules )
) {
foreach ( $spacing_rules as $spacing_rule ) {
$declarations = array();
if (
isset( $spacing_rule['selector'] ) &&
preg_match( $layout_selector_pattern, $spacing_rule['selector'] ) &&
! empty( $spacing_rule['rules'] )
) {
// Iterate over each of the styling rules and substitute non-string values such as `null` with the real `blockGap` value.
foreach ( $spacing_rule['rules'] as $css_property => $css_value ) {
$current_css_value = is_string( $css_value ) ? $css_value : $block_gap_value;
if ( static::is_safe_css_declaration( $css_property, $current_css_value ) ) {
$declarations[] = array(
'name' => $css_property,
'value' => $current_css_value,
);
}
}
if ( ! $has_block_gap_support ) {
// For fallback gap styles, use lower specificity, to ensure styles do not unintentionally override theme styles.
$format = static::ROOT_BLOCK_SELECTOR === $selector ? ':where(.%2$s%3$s)' : ':where(%1$s.%2$s%3$s)';
$layout_selector = sprintf(
$format,
$selector,
$class_name,
$spacing_rule['selector']
);
} else {
$format = static::ROOT_BLOCK_SELECTOR === $selector ? '%s .%s%s' : '%s.%s%s';
$layout_selector = sprintf(
$format,
$selector,
$class_name,
$spacing_rule['selector']
);
}
$block_rules .= static::to_ruleset( $layout_selector, $declarations );
}
}
}
}
}
}
// Output base styles.
if (
static::ROOT_BLOCK_SELECTOR === $selector
) {
$valid_display_modes = array( 'block', 'flex', 'grid' );
foreach ( $layout_definitions as $layout_definition ) {
$class_name = sanitize_title( _wp_array_get( $layout_definition, array( 'className' ), false ) );
$base_style_rules = _wp_array_get( $layout_definition, array( 'baseStyles' ), array() );
if (
! empty( $class_name ) &&
! empty( $base_style_rules )
) {
// Output display mode. This requires special handling as `display` is not exposed in `safe_style_css_filter`.
if (
! empty( $layout_definition['displayMode'] ) &&
is_string( $layout_definition['displayMode'] ) &&
in_array( $layout_definition['displayMode'], $valid_display_modes, true )
) {
$layout_selector = sprintf(
'%s .%s',
$selector,
$class_name
);
$block_rules .= static::to_ruleset(
$layout_selector,
array(
array(
'name' => 'display',
'value' => $layout_definition['displayMode'],
),
)
);
}
foreach ( $base_style_rules as $base_style_rule ) {
$declarations = array();
if (
isset( $base_style_rule['selector'] ) &&
preg_match( $layout_selector_pattern, $base_style_rule['selector'] ) &&
! empty( $base_style_rule['rules'] )
) {
foreach ( $base_style_rule['rules'] as $css_property => $css_value ) {
if ( static::is_safe_css_declaration( $css_property, $css_value ) ) {
$declarations[] = array(
'name' => $css_property,
'value' => $css_value,
);
}
}
$layout_selector = sprintf(
'%s .%s%s',
$selector,
$class_name,
$base_style_rule['selector']
);
$block_rules .= static::to_ruleset( $layout_selector, $declarations );
}
}
}
}
}
return $block_rules;
}
/**
* Creates new rulesets as classes for each preset value such as:
*
* .has-value-color {
* color: value;
* }
*
* .has-value-background-color {
* background-color: value;
* }
*
* .has-value-font-size {
* font-size: value;
* }
*
* .has-value-gradient-background {
* background: value;
* }
*
* p.has-value-gradient-background {
* background: value;
* }
*
* @since 5.9.0
*
* @param array $setting_nodes Nodes with settings.
* @param array $origins List of origins to process presets from.
* @return string The new stylesheet.
*/
protected function get_preset_classes( $setting_nodes, $origins ) {
$preset_rules = '';
foreach ( $setting_nodes as $metadata ) {
if ( null === $metadata['selector'] ) {
continue;
}
$selector = $metadata['selector'];
$node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
$preset_rules .= static::compute_preset_classes( $node, $selector, $origins );
}
return $preset_rules;
}
/**
* Converts each styles section into a list of rulesets
* to be appended to the stylesheet.
* These rulesets contain all the css variables (custom variables and preset variables).
*
* See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax
*
* For each section this creates a new ruleset such as:
*
* block-selector {
* --wp--preset--category--slug: value;
* --wp--custom--variable: value;
* }
*
* @since 5.8.0
* @since 5.9.0 Added the `$origins` parameter.
*
* @param array $nodes Nodes with settings.
* @param array $origins List of origins to process.
* @return string The new stylesheet.
*/
protected function get_css_variables( $nodes, $origins ) {
$stylesheet = '';
foreach ( $nodes as $metadata ) {
if ( null === $metadata['selector'] ) {
continue;
}
$selector = $metadata['selector'];
$node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
$declarations = array_merge( static::compute_preset_vars( $node, $origins ), static::compute_theme_vars( $node ) );
$stylesheet .= static::to_ruleset( $selector, $declarations );
}
return $stylesheet;
}
/**
* Given a selector and a declaration list,
* creates the corresponding ruleset.
*
* @since 5.8.0
*
* @param string $selector CSS selector.
* @param array $declarations List of declarations.
* @return string The resulting CSS ruleset.
*/
protected static function to_ruleset( $selector, $declarations ) {
if ( empty( $declarations ) ) {
return '';
}
$declaration_block = array_reduce(
$declarations,
static function ( $carry, $element ) {
return $carry .= $element['name'] . ': ' . $element['value'] . ';'; },
''
);
return $selector . '{' . $declaration_block . '}';
}
/**
* Given a settings array, returns the generated rulesets
* for the preset classes.
*
* @since 5.8.0
* @since 5.9.0 Added the `$origins` parameter.
*
* @param array $settings Settings to process.
* @param string $selector Selector wrapping the classes.
* @param array $origins List of origins to process.
* @return string The result of processing the presets.
*/
protected static function compute_preset_classes( $settings, $selector, $origins ) {
if ( static::ROOT_BLOCK_SELECTOR === $selector ) {
// Classes at the global level do not need any CSS prefixed,
// and we don't want to increase its specificity.
$selector = '';
}
$stylesheet = '';
foreach ( static::PRESETS_METADATA as $preset_metadata ) {
$slugs = static::get_settings_slugs( $settings, $preset_metadata, $origins );
foreach ( $preset_metadata['classes'] as $class => $property ) {
foreach ( $slugs as $slug ) {
$css_var = static::replace_slug_in_string( $preset_metadata['css_vars'], $slug );
$class_name = static::replace_slug_in_string( $class, $slug );
$stylesheet .= static::to_ruleset(
static::append_to_selector( $selector, $class_name ),
array(
array(
'name' => $property,
'value' => 'var(' . $css_var . ') !important',
),
)
);
}
}
}
return $stylesheet;
}
/**
* Function that scopes a selector with another one. This works a bit like
* SCSS nesting except the `&` operator isn't supported.
*
* <code>
* $scope = '.a, .b .c';
* $selector = '> .x, .y';
* $merged = scope_selector( $scope, $selector );
* // $merged is '.a > .x, .a .y, .b .c > .x, .b .c .y'
* </code>
*
* @since 5.9.0
*
* @param string $scope Selector to scope to.
* @param string $selector Original selector.
* @return string Scoped selector.
*/
protected static function scope_selector( $scope, $selector ) {
$scopes = explode( ',', $scope );
$selectors = explode( ',', $selector );
$selectors_scoped = array();
foreach ( $scopes as $outer ) {
foreach ( $selectors as $inner ) {
$selectors_scoped[] = trim( $outer ) . ' ' . trim( $inner );
}
}
return implode( ', ', $selectors_scoped );
}
/**
* Gets preset values keyed by slugs based on settings and metadata.
*
* <code>
* $settings = array(
* 'typography' => array(
* 'fontFamilies' => array(
* array(
* 'slug' => 'sansSerif',
* 'fontFamily' => '"Helvetica Neue", sans-serif',
* ),
* array(
* 'slug' => 'serif',
* 'colors' => 'Georgia, serif',
* )
* ),
* ),
* );
* $meta = array(
* 'path' => array( 'typography', 'fontFamilies' ),
* 'value_key' => 'fontFamily',
* );
* $values_by_slug = get_settings_values_by_slug();
* // $values_by_slug === array(
* // 'sans-serif' => '"Helvetica Neue", sans-serif',
* // 'serif' => 'Georgia, serif',
* // );
* </code>
*
* @since 5.9.0
*
* @param array $settings Settings to process.
* @param array $preset_metadata One of the PRESETS_METADATA values.
* @param array $origins List of origins to process.
* @return array Array of presets where each key is a slug and each value is the preset value.
*/
protected static function get_settings_values_by_slug( $settings, $preset_metadata, $origins ) {
$preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
$result = array();
foreach ( $origins as $origin ) {
if ( ! isset( $preset_per_origin[ $origin ] ) ) {
continue;
}
foreach ( $preset_per_origin[ $origin ] as $preset ) {
$slug = _wp_to_kebab_case( $preset['slug'] );
$value = '';
if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) {
$value_key = $preset_metadata['value_key'];
$value = $preset[ $value_key ];
} elseif (
isset( $preset_metadata['value_func'] ) &&
is_callable( $preset_metadata['value_func'] )
) {
$value_func = $preset_metadata['value_func'];
$value = call_user_func( $value_func, $preset );
} else {
// If we don't have a value, then don't add it to the result.
continue;
}
$result[ $slug ] = $value;
}
}
return $result;
}
/**
* Similar to get_settings_values_by_slug, but doesn't compute the value.
*
* @since 5.9.0
*
* @param array $settings Settings to process.
* @param array $preset_metadata One of the PRESETS_METADATA values.
* @param array $origins List of origins to process.
* @return array Array of presets where the key and value are both the slug.
*/
protected static function get_settings_slugs( $settings, $preset_metadata, $origins = null ) {
if ( null === $origins ) {
$origins = static::VALID_ORIGINS;
}
$preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
$result = array();
foreach ( $origins as $origin ) {
if ( ! isset( $preset_per_origin[ $origin ] ) ) {
continue;
}
foreach ( $preset_per_origin[ $origin ] as $preset ) {
$slug = _wp_to_kebab_case( $preset['slug'] );
// Use the array as a set so we don't get duplicates.
$result[ $slug ] = $slug;
}
}
return $result;
}
/**
* Transforms a slug into a CSS Custom Property.
*
* @since 5.9.0
*
* @param string $input String to replace.
* @param string $slug The slug value to use to generate the custom property.
* @return string The CSS Custom Property. Something along the lines of `--wp--preset--color--black`.
*/
protected static function replace_slug_in_string( $input, $slug ) {
return strtr( $input, array( '$slug' => $slug ) );
}
/**
* Given the block settings, extracts the CSS Custom Properties
* for the presets and adds them to the $declarations array
* following the format:
*
* array(
* 'name' => 'property_name',
* 'value' => 'property_value,
* )
*
* @since 5.8.0
* @since 5.9.0 Added the `$origins` parameter.
*
* @param array $settings Settings to process.
* @param array $origins List of origins to process.
* @return array The modified $declarations.
*/
protected static function compute_preset_vars( $settings, $origins ) {
$declarations = array();
foreach ( static::PRESETS_METADATA as $preset_metadata ) {
$values_by_slug = static::get_settings_values_by_slug( $settings, $preset_metadata, $origins );
foreach ( $values_by_slug as $slug => $value ) {
$declarations[] = array(
'name' => static::replace_slug_in_string( $preset_metadata['css_vars'], $slug ),
'value' => $value,
);
}
}
return $declarations;
}
/**
* Given an array of settings, extracts the CSS Custom Properties
* for the custom values and adds them to the $declarations
* array following the format:
*
* array(
* 'name' => 'property_name',
* 'value' => 'property_value,
* )
*
* @since 5.8.0
*
* @param array $settings Settings to process.
* @return array The modified $declarations.
*/
protected static function compute_theme_vars( $settings ) {
$declarations = array();
$custom_values = _wp_array_get( $settings, array( 'custom' ), array() );
$css_vars = static::flatten_tree( $custom_values );
foreach ( $css_vars as $key => $value ) {
$declarations[] = array(
'name' => '--wp--custom--' . $key,
'value' => $value,
);
}
return $declarations;
}
/**
* Given a tree, it creates a flattened one
* by merging the keys and binding the leaf values
* to the new keys.
*
* It also transforms camelCase names into kebab-case
* and substitutes '/' by '-'.
*
* This is thought to be useful to generate
* CSS Custom Properties from a tree,
* although there's nothing in the implementation
* of this function that requires that format.
*
* For example, assuming the given prefix is '--wp'
* and the token is '--', for this input tree:
*
* {
* 'some/property': 'value',
* 'nestedProperty': {
* 'sub-property': 'value'
* }
* }
*
* it'll return this output:
*
* {
* '--wp--some-property': 'value',
* '--wp--nested-property--sub-property': 'value'
* }
*
* @since 5.8.0
*
* @param array $tree Input tree to process.
* @param string $prefix Optional. Prefix to prepend to each variable. Default empty string.
* @param string $token Optional. Token to use between levels. Default '--'.
* @return array The flattened tree.
*/
protected static function flatten_tree( $tree, $prefix = '', $token = '--' ) {
$result = array();
foreach ( $tree as $property => $value ) {
$new_key = $prefix . str_replace(
'/',
'-',
strtolower( _wp_to_kebab_case( $property ) )
);
if ( is_array( $value ) ) {
$new_prefix = $new_key . $token;
$result = array_merge(
$result,
static::flatten_tree( $value, $new_prefix, $token )
);
} else {
$result[ $new_key ] = $value;
}
}
return $result;
}
/**
* Given a styles array, it extracts the style properties
* and adds them to the $declarations array following the format:
*
* array(
* 'name' => 'property_name',
* 'value' => 'property_value,
* )
*
* @since 5.8.0
* @since 5.9.0 Added the `$settings` and `$properties` parameters.
* @since 6.1.0 Added `$theme_json`, `$selector`, and `$use_root_padding` parameters.
*
* @param array $styles Styles to process.
* @param array $settings Theme settings.
* @param array $properties Properties metadata.
* @param array $theme_json Theme JSON array.
* @param string $selector The style block selector.
* @param boolean $use_root_padding Whether to add custom properties at root level.
* @return array Returns the modified $declarations.
*/
protected static function compute_style_properties( $styles, $settings = array(), $properties = null, $theme_json = null, $selector = null, $use_root_padding = null ) {
if ( null === $properties ) {
$properties = static::PROPERTIES_METADATA;
}
$declarations = array();
if ( empty( $styles ) ) {
return $declarations;
}
$root_variable_duplicates = array();
foreach ( $properties as $css_property => $value_path ) {
$value = static::get_property_value( $styles, $value_path, $theme_json );
if ( str_starts_with( $css_property, '--wp--style--root--' ) && ( static::ROOT_BLOCK_SELECTOR !== $selector || ! $use_root_padding ) ) {
continue;
}
// Root-level padding styles don't currently support strings with CSS shorthand values.
// This may change: https://github.com/WordPress/gutenberg/issues/40132.
if ( '--wp--style--root--padding' === $css_property && is_string( $value ) ) {
continue;
}
if ( str_starts_with( $css_property, '--wp--style--root--' ) && $use_root_padding ) {
$root_variable_duplicates[] = substr( $css_property, strlen( '--wp--style--root--' ) );
}
// Look up protected properties, keyed by value path.
// Skip protected properties that are explicitly set to `null`.
if ( is_array( $value_path ) ) {
$path_string = implode( '.', $value_path );
if (
array_key_exists( $path_string, static::PROTECTED_PROPERTIES ) &&
_wp_array_get( $settings, static::PROTECTED_PROPERTIES[ $path_string ], null ) === null
) {
continue;
}
}
// Skip if empty and not "0" or value represents array of longhand values.
$has_missing_value = empty( $value ) && ! is_numeric( $value );
if ( $has_missing_value || is_array( $value ) ) {
continue;
}
// Calculates fluid typography rules where available.
if ( 'font-size' === $css_property ) {
/*
* wp_get_typography_font_size_value() will check
* if fluid typography has been activated and also
* whether the incoming value can be converted to a fluid value.
* Values that already have a clamp() function will not pass the test,
* and therefore the original $value will be returned.
*/
$value = wp_get_typography_font_size_value( array( 'size' => $value ) );
}
$declarations[] = array(
'name' => $css_property,
'value' => $value,
);
}
// If a variable value is added to the root, the corresponding property should be removed.
foreach ( $root_variable_duplicates as $duplicate ) {
$discard = array_search( $duplicate, array_column( $declarations, 'name' ), true );
if ( is_numeric( $discard ) ) {
array_splice( $declarations, $discard, 1 );
}
}
return $declarations;
}
/**
* Returns the style property for the given path.
*
* It also converts CSS Custom Property stored as
* "var:preset|color|secondary" to the form
* "--wp--preset--color--secondary".
*
* It also converts references to a path to the value
* stored at that location, e.g.
* { "ref": "style.color.background" } => "#fff".
*
* @since 5.8.0
* @since 5.9.0 Added support for values of array type, which are returned as is.
* @since 6.1.0 Added the `$theme_json` parameter.
*
* @param array $styles Styles subtree.
* @param array $path Which property to process.
* @param array $theme_json Theme JSON array.
* @return string|array Style property value.
*/
protected static function get_property_value( $styles, $path, $theme_json = null ) {
$value = _wp_array_get( $styles, $path, '' );
if ( '' === $value || null === $value ) {
// No need to process the value further.
return '';
}
/*
* This converts references to a path to the value at that path
* where the values is an array with a "ref" key, pointing to a path.
* For example: { "ref": "style.color.background" } => "#fff".
*/
if ( is_array( $value ) && array_key_exists( 'ref', $value ) ) {
$value_path = explode( '.', $value['ref'] );
$ref_value = _wp_array_get( $theme_json, $value_path );
// Only use the ref value if we find anything.
if ( ! empty( $ref_value ) && is_string( $ref_value ) ) {
$value = $ref_value;
}
if ( is_array( $ref_value ) && array_key_exists( 'ref', $ref_value ) ) {
$path_string = json_encode( $path );
$ref_value_string = json_encode( $ref_value );
_doing_it_wrong(
'get_property_value',
sprintf(
/* translators: 1: theme.json, 2: Value name, 3: Value path, 4: Another value name. */
__( 'Your %1$s file uses a dynamic value (%2$s) for the path at %3$s. However, the value at %3$s is also a dynamic value (pointing to %4$s) and pointing to another dynamic value is not supported. Please update %3$s to point directly to %4$s.' ),
'theme.json',
$ref_value_string,
$path_string,
$ref_value['ref']
),
'6.1.0'
);
}
}
if ( is_array( $value ) ) {
return $value;
}
// Convert custom CSS properties.
$prefix = 'var:';
$prefix_len = strlen( $prefix );
$token_in = '|';
$token_out = '--';
if ( 0 === strncmp( $value, $prefix, $prefix_len ) ) {
$unwrapped_name = str_replace(
$token_in,
$token_out,
substr( $value, $prefix_len )
);
$value = "var(--wp--$unwrapped_name)";
}
return $value;
}
/**
* Builds metadata for the setting nodes, which returns in the form of:
*
* [
* [
* 'path' => ['path', 'to', 'some', 'node' ],
* 'selector' => 'CSS selector for some node'
* ],
* [
* 'path' => [ 'path', 'to', 'other', 'node' ],
* 'selector' => 'CSS selector for other node'
* ],
* ]
*
* @since 5.8.0
*
* @param array $theme_json The tree to extract setting nodes from.
* @param array $selectors List of selectors per block.
* @return array An array of setting nodes metadata.
*/
protected static function get_setting_nodes( $theme_json, $selectors = array() ) {
$nodes = array();
if ( ! isset( $theme_json['settings'] ) ) {
return $nodes;
}
// Top-level.
$nodes[] = array(
'path' => array( 'settings' ),
'selector' => static::ROOT_BLOCK_SELECTOR,
);
// Calculate paths for blocks.
if ( ! isset( $theme_json['settings']['blocks'] ) ) {
return $nodes;
}
foreach ( $theme_json['settings']['blocks'] as $name => $node ) {
$selector = null;
if ( isset( $selectors[ $name ]['selector'] ) ) {
$selector = $selectors[ $name ]['selector'];
}
$nodes[] = array(
'path' => array( 'settings', 'blocks', $name ),
'selector' => $selector,
);
}
return $nodes;
}
/**
* Builds metadata for the style nodes, which returns in the form of:
*
* [
* [
* 'path' => [ 'path', 'to', 'some', 'node' ],
* 'selector' => 'CSS selector for some node',
* 'duotone' => 'CSS selector for duotone for some node'
* ],
* [
* 'path' => ['path', 'to', 'other', 'node' ],
* 'selector' => 'CSS selector for other node',
* 'duotone' => null
* ],
* ]
*
* @since 5.8.0
*
* @param array $theme_json The tree to extract style nodes from.
* @param array $selectors List of selectors per block.
* @return array An array of style nodes metadata.
*/
protected static function get_style_nodes( $theme_json, $selectors = array() ) {
$nodes = array();
if ( ! isset( $theme_json['styles'] ) ) {
return $nodes;
}
// Top-level.
$nodes[] = array(
'path' => array( 'styles' ),
'selector' => static::ROOT_BLOCK_SELECTOR,
);
if ( isset( $theme_json['styles']['elements'] ) ) {
foreach ( self::ELEMENTS as $element => $selector ) {
if ( ! isset( $theme_json['styles']['elements'][ $element ] ) ) {
continue;
}
$nodes[] = array(
'path' => array( 'styles', 'elements', $element ),
'selector' => static::ELEMENTS[ $element ],
);
// Handle any pseudo selectors for the element.
if ( array_key_exists( $element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ) {
foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
if ( isset( $theme_json['styles']['elements'][ $element ][ $pseudo_selector ] ) ) {
$nodes[] = array(
'path' => array( 'styles', 'elements', $element ),
'selector' => static::append_to_selector( static::ELEMENTS[ $element ], $pseudo_selector ),
);
}
}
}
}
}
// Blocks.
if ( ! isset( $theme_json['styles']['blocks'] ) ) {
return $nodes;
}
$nodes = array_merge( $nodes, static::get_block_nodes( $theme_json ) );
/**
* Filters the list of style nodes with metadata.
*
* This allows for things like loading block CSS independently.
*
* @since 6.1.0
*
* @param array $nodes Style nodes with metadata.
*/
return apply_filters( 'wp_theme_json_get_style_nodes', $nodes );
}
/**
* A public helper to get the block nodes from a theme.json file.
*
* @since 6.1.0
*
* @return array The block nodes in theme.json.
*/
public function get_styles_block_nodes() {
return static::get_block_nodes( $this->theme_json );
}
/**
* An internal method to get the block nodes from a theme.json file.
*
* @since 6.1.0
*
* @param array $theme_json The theme.json converted to an array.
* @return array The block nodes in theme.json.
*/
private static function get_block_nodes( $theme_json ) {
$selectors = static::get_blocks_metadata();
$nodes = array();
if ( ! isset( $theme_json['styles'] ) ) {
return $nodes;
}
// Blocks.
if ( ! isset( $theme_json['styles']['blocks'] ) ) {
return $nodes;
}
foreach ( $theme_json['styles']['blocks'] as $name => $node ) {
$selector = null;
if ( isset( $selectors[ $name ]['selector'] ) ) {
$selector = $selectors[ $name ]['selector'];
}
$duotone_selector = null;
if ( isset( $selectors[ $name ]['duotone'] ) ) {
$duotone_selector = $selectors[ $name ]['duotone'];
}
$feature_selectors = null;
if ( isset( $selectors[ $name ]['features'] ) ) {
$feature_selectors = $selectors[ $name ]['features'];
}
$nodes[] = array(
'name' => $name,
'path' => array( 'styles', 'blocks', $name ),
'selector' => $selector,
'duotone' => $duotone_selector,
'features' => $feature_selectors,
);
if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'] ) ) {
foreach ( $theme_json['styles']['blocks'][ $name ]['elements'] as $element => $node ) {
$nodes[] = array(
'path' => array( 'styles', 'blocks', $name, 'elements', $element ),
'selector' => $selectors[ $name ]['elements'][ $element ],
);
// Handle any pseudo selectors for the element.
if ( array_key_exists( $element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ) {
foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element ] as $pseudo_selector ) {
if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'][ $element ][ $pseudo_selector ] ) ) {
$nodes[] = array(
'path' => array( 'styles', 'blocks', $name, 'elements', $element ),
'selector' => static::append_to_selector( $selectors[ $name ]['elements'][ $element ], $pseudo_selector ),
);
}
}
}
}
}
}
return $nodes;
}
/**
* Gets the CSS rules for a particular block from theme.json.
*
* @since 6.1.0
*
* @param array $block_metadata Metadata about the block to get styles for.
*
* @return string Styles for the block.
*/
public function get_styles_for_block( $block_metadata ) {
$node = _wp_array_get( $this->theme_json, $block_metadata['path'], array() );
$use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments'];
$selector = $block_metadata['selector'];
$settings = _wp_array_get( $this->theme_json, array( 'settings' ) );
/*
* Process style declarations for block support features the current
* block contains selectors for. Values for a feature with a custom
* selector are filtered from the theme.json node before it is
* processed as normal.
*/
$feature_declarations = array();
if ( ! empty( $block_metadata['features'] ) ) {
foreach ( $block_metadata['features'] as $feature_name => $feature_selector ) {
if ( ! empty( $node[ $feature_name ] ) ) {
// Create temporary node containing only the feature data
// to leverage existing `compute_style_properties` function.
$feature = array( $feature_name => $node[ $feature_name ] );
// Generate the feature's declarations only.
$new_feature_declarations = static::compute_style_properties( $feature, $settings, null, $this->theme_json );
// Merge new declarations with any that already exist for
// the feature selector. This may occur when multiple block
// support features use the same custom selector.
if ( isset( $feature_declarations[ $feature_selector ] ) ) {
$feature_declarations[ $feature_selector ] = array_merge( $feature_declarations[ $feature_selector ], $new_feature_declarations );
} else {
$feature_declarations[ $feature_selector ] = $new_feature_declarations;
}
// Remove the feature from the block's node now the
// styles will be included under the feature level selector.
unset( $node[ $feature_name ] );
}
}
}
/*
* Get a reference to element name from path.
* $block_metadata['path'] = array( 'styles','elements','link' );
* Make sure that $block_metadata['path'] describes an element node, like [ 'styles', 'element', 'link' ].
* Skip non-element paths like just ['styles'].
*/
$is_processing_element = in_array( 'elements', $block_metadata['path'], true );
$current_element = $is_processing_element ? $block_metadata['path'][ count( $block_metadata['path'] ) - 1 ] : null;
$element_pseudo_allowed = array();
if ( array_key_exists( $current_element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ) {
$element_pseudo_allowed = static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ];
}
/*
* Check for allowed pseudo classes (e.g. ":hover") from the $selector ("a:hover").
* This also resets the array keys.
*/
$pseudo_matches = array_values(
array_filter(
$element_pseudo_allowed,
function( $pseudo_selector ) use ( $selector ) {
return str_contains( $selector, $pseudo_selector );
}
)
);
$pseudo_selector = isset( $pseudo_matches[0] ) ? $pseudo_matches[0] : null;
/*
* If the current selector is a pseudo selector that's defined in the allow list for the current
* element then compute the style properties for it.
* Otherwise just compute the styles for the default selector as normal.
*/
if ( $pseudo_selector && isset( $node[ $pseudo_selector ] ) &&
array_key_exists( $current_element, static::VALID_ELEMENT_PSEUDO_SELECTORS )
&& in_array( $pseudo_selector, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ], true )
) {
$declarations = static::compute_style_properties( $node[ $pseudo_selector ], $settings, null, $this->theme_json, $selector, $use_root_padding );
} else {
$declarations = static::compute_style_properties( $node, $settings, null, $this->theme_json, $selector, $use_root_padding );
}
$block_rules = '';
/*
* 1. Separate the declarations that use the general selector
* from the ones using the duotone selector.
*/
$declarations_duotone = array();
foreach ( $declarations as $index => $declaration ) {
if ( 'filter' === $declaration['name'] ) {
unset( $declarations[ $index ] );
$declarations_duotone[] = $declaration;
}
}
// 2. Generate and append the rules that use the general selector.
$block_rules .= static::to_ruleset( $selector, $declarations );
// 3. Generate and append the rules that use the duotone selector.
if ( isset( $block_metadata['duotone'] ) && ! empty( $declarations_duotone ) ) {
$selector_duotone = static::scope_selector( $block_metadata['selector'], $block_metadata['duotone'] );
$block_rules .= static::to_ruleset( $selector_duotone, $declarations_duotone );
}
// 4. Generate Layout block gap styles.
if (
static::ROOT_BLOCK_SELECTOR !== $selector &&
! empty( $block_metadata['name'] )
) {
$block_rules .= $this->get_layout_styles( $block_metadata );
}
// 5. Generate and append the feature level rulesets.
foreach ( $feature_declarations as $feature_selector => $individual_feature_declarations ) {
$block_rules .= static::to_ruleset( $feature_selector, $individual_feature_declarations );
}
return $block_rules;
}
/**
* Outputs the CSS for layout rules on the root.
*
* @since 6.1.0
*
* @param string $selector The root node selector.
* @param array $block_metadata The metadata for the root block.
* @return string The additional root rules CSS.
*/
public function get_root_layout_rules( $selector, $block_metadata ) {
$css = '';
$settings = _wp_array_get( $this->theme_json, array( 'settings' ) );
$use_root_padding = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments'];
/*
* Reset default browser margin on the root body element.
* This is set on the root selector **before** generating the ruleset
* from the `theme.json`. This is to ensure that if the `theme.json` declares
* `margin` in its `spacing` declaration for the `body` element then these
* user-generated values take precedence in the CSS cascade.
* @link https://github.com/WordPress/gutenberg/issues/36147.
*/
$css .= 'body { margin: 0;';
/*
* If there are content and wide widths in theme.json, output them
* as custom properties on the body element so all blocks can use them.
*/
if ( isset( $settings['layout']['contentSize'] ) || isset( $settings['layout']['wideSize'] ) ) {
$content_size = isset( $settings['layout']['contentSize'] ) ? $settings['layout']['contentSize'] : $settings['layout']['wideSize'];
$content_size = static::is_safe_css_declaration( 'max-width', $content_size ) ? $content_size : 'initial';
$wide_size = isset( $settings['layout']['wideSize'] ) ? $settings['layout']['wideSize'] : $settings['layout']['contentSize'];
$wide_size = static::is_safe_css_declaration( 'max-width', $wide_size ) ? $wide_size : 'initial';
$css .= '--wp--style--global--content-size: ' . $content_size . ';';
$css .= '--wp--style--global--wide-size: ' . $wide_size . ';';
}
$css .= ' }';
if ( $use_root_padding ) {
// Top and bottom padding are applied to the outer block container.
$css .= '.wp-site-blocks { padding-top: var(--wp--style--root--padding-top); padding-bottom: var(--wp--style--root--padding-bottom); }';
// Right and left padding are applied to the first container with `.has-global-padding` class.
$css .= '.has-global-padding { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }';
// Nested containers with `.has-global-padding` class do not get padding.
$css .= '.has-global-padding :where(.has-global-padding) { padding-right: 0; padding-left: 0; }';
// Alignfull children of the container with left and right padding have negative margins so they can still be full width.
$css .= '.has-global-padding > .alignfull { margin-right: calc(var(--wp--style--root--padding-right) * -1); margin-left: calc(var(--wp--style--root--padding-left) * -1); }';
// The above rule is negated for alignfull children of nested containers.
$css .= '.has-global-padding :where(.has-global-padding) > .alignfull { margin-right: 0; margin-left: 0; }';
// Some of the children of alignfull blocks without content width should also get padding: text blocks and non-alignfull container blocks.
$css .= '.has-global-padding > .alignfull:where(:not(.has-global-padding)) > :where([class*="wp-block-"]:not(.alignfull):not([class*="__"]),p,h1,h2,h3,h4,h5,h6,ul,ol) { padding-right: var(--wp--style--root--padding-right); padding-left: var(--wp--style--root--padding-left); }';
// The above rule also has to be negated for blocks inside nested `.has-global-padding` blocks.
$css .= '.has-global-padding :where(.has-global-padding) > .alignfull:where(:not(.has-global-padding)) > :where([class*="wp-block-"]:not(.alignfull):not([class*="__"]),p,h1,h2,h3,h4,h5,h6,ul,ol) { padding-right: 0; padding-left: 0; }';
}
$css .= '.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }';
$css .= '.wp-site-blocks > .alignright { float: right; margin-left: 2em; }';
$css .= '.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }';
$block_gap_value = _wp_array_get( $this->theme_json, array( 'styles', 'spacing', 'blockGap' ), '0.5em' );
$has_block_gap_support = _wp_array_get( $this->theme_json, array( 'settings', 'spacing', 'blockGap' ) ) !== null;
if ( $has_block_gap_support ) {
$block_gap_value = static::get_property_value( $this->theme_json, array( 'styles', 'spacing', 'blockGap' ) );
$css .= '.wp-site-blocks > * { margin-block-start: 0; margin-block-end: 0; }';
$css .= ".wp-site-blocks > * + * { margin-block-start: $block_gap_value; }";
// For backwards compatibility, ensure the legacy block gap CSS variable is still available.
$css .= "$selector { --wp--style--block-gap: $block_gap_value; }";
}
$css .= $this->get_layout_styles( $block_metadata );
return $css;
}
/**
* For metadata values that can either be booleans or paths to booleans, gets the value.
*
* ```php
* $data = array(
* 'color' => array(
* 'defaultPalette' => true
* )
* );
*
* static::get_metadata_boolean( $data, false );
* // => false
*
* static::get_metadata_boolean( $data, array( 'color', 'defaultPalette' ) );
* // => true
* ```
*
* @since 6.0.0
*
* @param array $data The data to inspect.
* @param bool|array $path Boolean or path to a boolean.
* @param bool $default Default value if the referenced path is missing.
* Default false.
* @return bool Value of boolean metadata.
*/
protected static function get_metadata_boolean( $data, $path, $default = false ) {
if ( is_bool( $path ) ) {
return $path;
}
if ( is_array( $path ) ) {
$value = _wp_array_get( $data, $path );
if ( null !== $value ) {
return $value;
}
}
return $default;
}
/**
* Merges new incoming data.
*
* @since 5.8.0
* @since 5.9.0 Duotone preset also has origins.
*
* @param WP_Theme_JSON $incoming Data to merge.
*/
public function merge( $incoming ) {
$incoming_data = $incoming->get_raw_data();
$this->theme_json = array_replace_recursive( $this->theme_json, $incoming_data );
/*
* The array_replace_recursive algorithm merges at the leaf level,
* but we don't want leaf arrays to be merged, so we overwrite it.
*
* For leaf values that are sequential arrays it will use the numeric indexes for replacement.
* We rather replace the existing with the incoming value, if it exists.
* This is the case of spacing.units.
*
* For leaf values that are associative arrays it will merge them as expected.
* This is also not the behavior we want for the current associative arrays (presets).
* We rather replace the existing with the incoming value, if it exists.
* This happens, for example, when we merge data from theme.json upon existing
* theme supports or when we merge anything coming from the same source twice.
* This is the case of color.palette, color.gradients, color.duotone,
* typography.fontSizes, or typography.fontFamilies.
*
* Additionally, for some preset types, we also want to make sure the
* values they introduce don't conflict with default values. We do so
* by checking the incoming slugs for theme presets and compare them
* with the equivalent default presets: if a slug is present as a default
* we remove it from the theme presets.
*/
$nodes = static::get_setting_nodes( $incoming_data );
$slugs_global = static::get_default_slugs( $this->theme_json, array( 'settings' ) );
foreach ( $nodes as $node ) {
$slugs_node = static::get_default_slugs( $this->theme_json, $node['path'] );
$slugs = array_merge_recursive( $slugs_global, $slugs_node );
// Replace the spacing.units.
$path = array_merge( $node['path'], array( 'spacing', 'units' ) );
$content = _wp_array_get( $incoming_data, $path, null );
if ( isset( $content ) ) {
_wp_array_set( $this->theme_json, $path, $content );
}
// Replace the presets.
foreach ( static::PRESETS_METADATA as $preset ) {
$override_preset = ! static::get_metadata_boolean( $this->theme_json['settings'], $preset['prevent_override'], true );
foreach ( static::VALID_ORIGINS as $origin ) {
$base_path = array_merge( $node['path'], $preset['path'] );
$path = array_merge( $base_path, array( $origin ) );
$content = _wp_array_get( $incoming_data, $path, null );
if ( ! isset( $content ) ) {
continue;
}
if ( 'theme' === $origin && $preset['use_default_names'] ) {
foreach ( $content as &$item ) {
if ( ! array_key_exists( 'name', $item ) ) {
$name = static::get_name_from_defaults( $item['slug'], $base_path );
if ( null !== $name ) {
$item['name'] = $name;
}
}
}
}
if (
( 'theme' !== $origin ) ||
( 'theme' === $origin && $override_preset )
) {
_wp_array_set( $this->theme_json, $path, $content );
} else {
$slugs_for_preset = _wp_array_get( $slugs, $preset['path'], array() );
$content = static::filter_slugs( $content, $slugs_for_preset );
_wp_array_set( $this->theme_json, $path, $content );
}
}
}
}
}
/**
* Converts all filter (duotone) presets into SVGs.
*
* @since 5.9.1
*
* @param array $origins List of origins to process.
* @return string SVG filters.
*/
public function get_svg_filters( $origins ) {
$blocks_metadata = static::get_blocks_metadata();
$setting_nodes = static::get_setting_nodes( $this->theme_json, $blocks_metadata );
$filters = '';
foreach ( $setting_nodes as $metadata ) {
$node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
if ( empty( $node['color']['duotone'] ) ) {
continue;
}
$duotone_presets = $node['color']['duotone'];
foreach ( $origins as $origin ) {
if ( ! isset( $duotone_presets[ $origin ] ) ) {
continue;
}
foreach ( $duotone_presets[ $origin ] as $duotone_preset ) {
$filters .= wp_get_duotone_filter_svg( $duotone_preset );
}
}
}
return $filters;
}
/**
* Determines whether a presets should be overridden or not.
*
* @since 5.9.0
* @deprecated 6.0.0 Use {@see 'get_metadata_boolean'} instead.
*
* @param array $theme_json The theme.json like structure to inspect.
* @param array $path Path to inspect.
* @param bool|array $override Data to compute whether to override the preset.
* @return boolean
*/
protected static function should_override_preset( $theme_json, $path, $override ) {
_deprecated_function( __METHOD__, '6.0.0', 'get_metadata_boolean' );
if ( is_bool( $override ) ) {
return $override;
}
/*
* The relationship between whether to override the defaults
* and whether the defaults are enabled is inverse:
*
* - If defaults are enabled => theme presets should not be overridden
* - If defaults are disabled => theme presets should be overridden
*
* For example, a theme sets defaultPalette to false,
* making the default palette hidden from the user.
* In that case, we want all the theme presets to be present,
* so they should override the defaults.
*/
if ( is_array( $override ) ) {
$value = _wp_array_get( $theme_json, array_merge( $path, $override ) );
if ( isset( $value ) ) {
return ! $value;
}
// Search the top-level key if none was found for this node.
$value = _wp_array_get( $theme_json, array_merge( array( 'settings' ), $override ) );
if ( isset( $value ) ) {
return ! $value;
}
return true;
}
}
/**
* Returns the default slugs for all the presets in an associative array
* whose keys are the preset paths and the leafs is the list of slugs.
*
* For example:
*
* array(
* 'color' => array(
* 'palette' => array( 'slug-1', 'slug-2' ),
* 'gradients' => array( 'slug-3', 'slug-4' ),
* ),
* )
*
* @since 5.9.0
*
* @param array $data A theme.json like structure.
* @param array $node_path The path to inspect. It's 'settings' by default.
* @return array
*/
protected static function get_default_slugs( $data, $node_path ) {
$slugs = array();
foreach ( static::PRESETS_METADATA as $metadata ) {
$path = array_merge( $node_path, $metadata['path'], array( 'default' ) );
$preset = _wp_array_get( $data, $path, null );
if ( ! isset( $preset ) ) {
continue;
}
$slugs_for_preset = array();
foreach ( $preset as $item ) {
if ( isset( $item['slug'] ) ) {
$slugs_for_preset[] = $item['slug'];
}
}
_wp_array_set( $slugs, $metadata['path'], $slugs_for_preset );
}
return $slugs;
}
/**
* Gets a `default`'s preset name by a provided slug.
*
* @since 5.9.0
*
* @param string $slug The slug we want to find a match from default presets.
* @param array $base_path The path to inspect. It's 'settings' by default.
* @return string|null
*/
protected function get_name_from_defaults( $slug, $base_path ) {
$path = array_merge( $base_path, array( 'default' ) );
$default_content = _wp_array_get( $this->theme_json, $path, null );
if ( ! $default_content ) {
return null;
}
foreach ( $default_content as $item ) {
if ( $slug === $item['slug'] ) {
return $item['name'];
}
}
return null;
}
/**
* Removes the preset values whose slug is equal to any of given slugs.
*
* @since 5.9.0
*
* @param array $node The node with the presets to validate.
* @param array $slugs The slugs that should not be overridden.
* @return array The new node.
*/
protected static function filter_slugs( $node, $slugs ) {
if ( empty( $slugs ) ) {
return $node;
}
$new_node = array();
foreach ( $node as $value ) {
if ( isset( $value['slug'] ) && ! in_array( $value['slug'], $slugs, true ) ) {
$new_node[] = $value;
}
}
return $new_node;
}
/**
* Removes insecure data from theme.json.
*
* @since 5.9.0
*
* @param array $theme_json Structure to sanitize.
* @return array Sanitized structure.
*/
public static function remove_insecure_properties( $theme_json ) {
$sanitized = array();
$theme_json = WP_Theme_JSON_Schema::migrate( $theme_json );
$valid_block_names = array_keys( static::get_blocks_metadata() );
$valid_element_names = array_keys( static::ELEMENTS );
$theme_json = static::sanitize( $theme_json, $valid_block_names, $valid_element_names );
$blocks_metadata = static::get_blocks_metadata();
$style_nodes = static::get_style_nodes( $theme_json, $blocks_metadata );
foreach ( $style_nodes as $metadata ) {
$input = _wp_array_get( $theme_json, $metadata['path'], array() );
if ( empty( $input ) ) {
continue;
}
$output = static::remove_insecure_styles( $input );
/*
* Get a reference to element name from path.
* $metadata['path'] = array( 'styles', 'elements', 'link' );
*/
$current_element = $metadata['path'][ count( $metadata['path'] ) - 1 ];
/*
* $output is stripped of pseudo selectors. Re-add and process them
* or insecure styles here.
*/
if ( array_key_exists( $current_element, static::VALID_ELEMENT_PSEUDO_SELECTORS ) ) {
foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] as $pseudo_selector ) {
if ( isset( $input[ $pseudo_selector ] ) ) {
$output[ $pseudo_selector ] = static::remove_insecure_styles( $input[ $pseudo_selector ] );
}
}
}
if ( ! empty( $output ) ) {
_wp_array_set( $sanitized, $metadata['path'], $output );
}
}
$setting_nodes = static::get_setting_nodes( $theme_json );
foreach ( $setting_nodes as $metadata ) {
$input = _wp_array_get( $theme_json, $metadata['path'], array() );
if ( empty( $input ) ) {
continue;
}
$output = static::remove_insecure_settings( $input );
if ( ! empty( $output ) ) {
_wp_array_set( $sanitized, $metadata['path'], $output );
}
}
if ( empty( $sanitized['styles'] ) ) {
unset( $theme_json['styles'] );
} else {
$theme_json['styles'] = $sanitized['styles'];
}
if ( empty( $sanitized['settings'] ) ) {
unset( $theme_json['settings'] );
} else {
$theme_json['settings'] = $sanitized['settings'];
}
return $theme_json;
}
/**
* Processes a setting node and returns the same node
* without the insecure settings.
*
* @since 5.9.0
*
* @param array $input Node to process.
* @return array
*/
protected static function remove_insecure_settings( $input ) {
$output = array();
foreach ( static::PRESETS_METADATA as $preset_metadata ) {
foreach ( static::VALID_ORIGINS as $origin ) {
$path_with_origin = array_merge( $preset_metadata['path'], array( $origin ) );
$presets = _wp_array_get( $input, $path_with_origin, null );
if ( null === $presets ) {
continue;
}
$escaped_preset = array();
foreach ( $presets as $preset ) {
if (
esc_attr( esc_html( $preset['name'] ) ) === $preset['name'] &&
sanitize_html_class( $preset['slug'] ) === $preset['slug']
) {
$value = null;
if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) {
$value = $preset[ $preset_metadata['value_key'] ];
} elseif (
isset( $preset_metadata['value_func'] ) &&
is_callable( $preset_metadata['value_func'] )
) {
$value = call_user_func( $preset_metadata['value_func'], $preset );
}
$preset_is_valid = true;
foreach ( $preset_metadata['properties'] as $property ) {
if ( ! static::is_safe_css_declaration( $property, $value ) ) {
$preset_is_valid = false;
break;
}
}
if ( $preset_is_valid ) {
$escaped_preset[] = $preset;
}
}
}
if ( ! empty( $escaped_preset ) ) {
_wp_array_set( $output, $path_with_origin, $escaped_preset );
}
}
}
return $output;
}
/**
* Processes a style node and returns the same node
* without the insecure styles.
*
* @since 5.9.0
*
* @param array $input Node to process.
* @return array
*/
protected static function remove_insecure_styles( $input ) {
$output = array();
$declarations = static::compute_style_properties( $input );
foreach ( $declarations as $declaration ) {
if ( static::is_safe_css_declaration( $declaration['name'], $declaration['value'] ) ) {
$path = static::PROPERTIES_METADATA[ $declaration['name'] ];
// Check the value isn't an array before adding so as to not
// double up shorthand and longhand styles.
$value = _wp_array_get( $input, $path, array() );
if ( ! is_array( $value ) ) {
_wp_array_set( $output, $path, $value );
}
}
}
return $output;
}
/**
* Checks that a declaration provided by the user is safe.
*
* @since 5.9.0
*
* @param string $property_name Property name in a CSS declaration, i.e. the `color` in `color: red`.
* @param string $property_value Value in a CSS declaration, i.e. the `red` in `color: red`.
* @return bool
*/
protected static function is_safe_css_declaration( $property_name, $property_value ) {
$style_to_validate = $property_name . ': ' . $property_value;
$filtered = esc_html( safecss_filter_attr( $style_to_validate ) );
return ! empty( trim( $filtered ) );
}
/**
* Returns the raw data.
*
* @since 5.8.0
*
* @return array Raw data.
*/
public function get_raw_data() {
return $this->theme_json;
}
/**
* Transforms the given editor settings according the
* add_theme_support format to the theme.json format.
*
* @since 5.8.0
*
* @param array $settings Existing editor settings.
* @return array Config that adheres to the theme.json schema.
*/
public static function get_from_editor_settings( $settings ) {
$theme_settings = array(
'version' => static::LATEST_SCHEMA,
'settings' => array(),
);
// Deprecated theme supports.
if ( isset( $settings['disableCustomColors'] ) ) {
if ( ! isset( $theme_settings['settings']['color'] ) ) {
$theme_settings['settings']['color'] = array();
}
$theme_settings['settings']['color']['custom'] = ! $settings['disableCustomColors'];
}
if ( isset( $settings['disableCustomGradients'] ) ) {
if ( ! isset( $theme_settings['settings']['color'] ) ) {
$theme_settings['settings']['color'] = array();
}
$theme_settings['settings']['color']['customGradient'] = ! $settings['disableCustomGradients'];
}
if ( isset( $settings['disableCustomFontSizes'] ) ) {
if ( ! isset( $theme_settings['settings']['typography'] ) ) {
$theme_settings['settings']['typography'] = array();
}
$theme_settings['settings']['typography']['customFontSize'] = ! $settings['disableCustomFontSizes'];
}
if ( isset( $settings['enableCustomLineHeight'] ) ) {
if ( ! isset( $theme_settings['settings']['typography'] ) ) {
$theme_settings['settings']['typography'] = array();
}
$theme_settings['settings']['typography']['lineHeight'] = $settings['enableCustomLineHeight'];
}
if ( isset( $settings['enableCustomUnits'] ) ) {
if ( ! isset( $theme_settings['settings']['spacing'] ) ) {
$theme_settings['settings']['spacing'] = array();
}
$theme_settings['settings']['spacing']['units'] = ( true === $settings['enableCustomUnits'] ) ?
array( 'px', 'em', 'rem', 'vh', 'vw', '%' ) :
$settings['enableCustomUnits'];
}
if ( isset( $settings['colors'] ) ) {
if ( ! isset( $theme_settings['settings']['color'] ) ) {
$theme_settings['settings']['color'] = array();
}
$theme_settings['settings']['color']['palette'] = $settings['colors'];
}
if ( isset( $settings['gradients'] ) ) {
if ( ! isset( $theme_settings['settings']['color'] ) ) {
$theme_settings['settings']['color'] = array();
}
$theme_settings['settings']['color']['gradients'] = $settings['gradients'];
}
if ( isset( $settings['fontSizes'] ) ) {
$font_sizes = $settings['fontSizes'];
// Back-compatibility for presets without units.
foreach ( $font_sizes as $key => $font_size ) {
if ( is_numeric( $font_size['size'] ) ) {
$font_sizes[ $key ]['size'] = $font_size['size'] . 'px';
}
}
if ( ! isset( $theme_settings['settings']['typography'] ) ) {
$theme_settings['settings']['typography'] = array();
}
$theme_settings['settings']['typography']['fontSizes'] = $font_sizes;
}
if ( isset( $settings['enableCustomSpacing'] ) ) {
if ( ! isset( $theme_settings['settings']['spacing'] ) ) {
$theme_settings['settings']['spacing'] = array();
}
$theme_settings['settings']['spacing']['padding'] = $settings['enableCustomSpacing'];
}
return $theme_settings;
}
/**
* Returns the current theme's wanted patterns(slugs) to be
* registered from Pattern Directory.
*
* @since 6.0.0
*
* @return string[]
*/
public function get_patterns() {
if ( isset( $this->theme_json['patterns'] ) && is_array( $this->theme_json['patterns'] ) ) {
return $this->theme_json['patterns'];
}
return array();
}
/**
* Returns a valid theme.json as provided by a theme.
*
* Unlike get_raw_data() this returns the presets flattened, as provided by a theme.
* This also uses appearanceTools instead of their opt-ins if all of them are true.
*
* @since 6.0.0
*
* @return array
*/
public function get_data() {
$output = $this->theme_json;
$nodes = static::get_setting_nodes( $output );
/**
* Flatten the theme & custom origins into a single one.
*
* For example, the following:
*
* {
* "settings": {
* "color": {
* "palette": {
* "theme": [ {} ],
* "custom": [ {} ]
* }
* }
* }
* }
*
* will be converted to:
*
* {
* "settings": {
* "color": {
* "palette": [ {} ]
* }
* }
* }
*/
foreach ( $nodes as $node ) {
foreach ( static::PRESETS_METADATA as $preset_metadata ) {
$path = array_merge( $node['path'], $preset_metadata['path'] );
$preset = _wp_array_get( $output, $path, null );
if ( null === $preset ) {
continue;
}
$items = array();
if ( isset( $preset['theme'] ) ) {
foreach ( $preset['theme'] as $item ) {
$slug = $item['slug'];
unset( $item['slug'] );
$items[ $slug ] = $item;
}
}
if ( isset( $preset['custom'] ) ) {
foreach ( $preset['custom'] as $item ) {
$slug = $item['slug'];
unset( $item['slug'] );
$items[ $slug ] = $item;
}
}
$flattened_preset = array();
foreach ( $items as $slug => $value ) {
$flattened_preset[] = array_merge( array( 'slug' => (string) $slug ), $value );
}
_wp_array_set( $output, $path, $flattened_preset );
}
}
// If all of the static::APPEARANCE_TOOLS_OPT_INS are true,
// this code unsets them and sets 'appearanceTools' instead.
foreach ( $nodes as $node ) {
$all_opt_ins_are_set = true;
foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) {
$full_path = array_merge( $node['path'], $opt_in_path );
// Use "unset prop" as a marker instead of "null" because
// "null" can be a valid value for some props (e.g. blockGap).
$opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' );
if ( 'unset prop' === $opt_in_value ) {
$all_opt_ins_are_set = false;
break;
}
}
if ( $all_opt_ins_are_set ) {
_wp_array_set( $output, array_merge( $node['path'], array( 'appearanceTools' ) ), true );
foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) {
$full_path = array_merge( $node['path'], $opt_in_path );
// Use "unset prop" as a marker instead of "null" because
// "null" can be a valid value for some props (e.g. blockGap).
$opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' );
if ( true !== $opt_in_value ) {
continue;
}
// The following could be improved to be path independent.
// At the moment it relies on a couple of assumptions:
//
// - all opt-ins having a path of size 2.
// - there's two sources of settings: the top-level and the block-level.
if (
( 1 === count( $node['path'] ) ) &&
( 'settings' === $node['path'][0] )
) {
// Top-level settings.
unset( $output['settings'][ $opt_in_path[0] ][ $opt_in_path[1] ] );
if ( empty( $output['settings'][ $opt_in_path[0] ] ) ) {
unset( $output['settings'][ $opt_in_path[0] ] );
}
} elseif (
( 3 === count( $node['path'] ) ) &&
( 'settings' === $node['path'][0] ) &&
( 'blocks' === $node['path'][1] )
) {
// Block-level settings.
$block_name = $node['path'][2];
unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ][ $opt_in_path[1] ] );
if ( empty( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] ) ) {
unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] );
}
}
}
}
}
wp_recursive_ksort( $output );
return $output;
}
/**
* Sets the spacingSizes array based on the spacingScale values from theme.json.
*
* @since 6.1.0
*
* @return null|void
*/
public function set_spacing_sizes() {
$spacing_scale = _wp_array_get( $this->theme_json, array( 'settings', 'spacing', 'spacingScale' ), array() );
if ( ! is_numeric( $spacing_scale['steps'] )
|| ! isset( $spacing_scale['mediumStep'] )
|| ! isset( $spacing_scale['unit'] )
|| ! isset( $spacing_scale['operator'] )
|| ! isset( $spacing_scale['increment'] )
|| ! isset( $spacing_scale['steps'] )
|| ! is_numeric( $spacing_scale['increment'] )
|| ! is_numeric( $spacing_scale['mediumStep'] )
|| ( '+' !== $spacing_scale['operator'] && '*' !== $spacing_scale['operator'] ) ) {
if ( ! empty( $spacing_scale ) ) {
trigger_error( __( 'Some of the theme.json settings.spacing.spacingScale values are invalid' ), E_USER_NOTICE );
}
return null;
}
// If theme authors want to prevent the generation of the core spacing scale they can set their theme.json spacingScale.steps to 0.
if ( 0 === $spacing_scale['steps'] ) {
return null;
}
$unit = '%' === $spacing_scale['unit'] ? '%' : sanitize_title( $spacing_scale['unit'] );
$current_step = $spacing_scale['mediumStep'];
$steps_mid_point = round( $spacing_scale['steps'] / 2, 0 );
$x_small_count = null;
$below_sizes = array();
$slug = 40;
$remainder = 0;
for ( $below_midpoint_count = $steps_mid_point - 1; $spacing_scale['steps'] > 1 && $slug > 0 && $below_midpoint_count > 0; $below_midpoint_count-- ) {
if ( '+' === $spacing_scale['operator'] ) {
$current_step -= $spacing_scale['increment'];
} elseif ( $spacing_scale['increment'] > 1 ) {
$current_step /= $spacing_scale['increment'];
} else {
$current_step *= $spacing_scale['increment'];
}
if ( $current_step <= 0 ) {
$remainder = $below_midpoint_count;
break;
}
$below_sizes[] = array(
/* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Small. */
'name' => $below_midpoint_count === $steps_mid_point - 1 ? __( 'Small' ) : sprintf( __( '%sX-Small' ), (string) $x_small_count ),
'slug' => (string) $slug,
'size' => round( $current_step, 2 ) . $unit,
);
if ( $below_midpoint_count === $steps_mid_point - 2 ) {
$x_small_count = 2;
}
if ( $below_midpoint_count < $steps_mid_point - 2 ) {
$x_small_count++;
}
$slug -= 10;
}
$below_sizes = array_reverse( $below_sizes );
$below_sizes[] = array(
'name' => __( 'Medium' ),
'slug' => '50',
'size' => $spacing_scale['mediumStep'] . $unit,
);
$current_step = $spacing_scale['mediumStep'];
$x_large_count = null;
$above_sizes = array();
$slug = 60;
$steps_above = ( $spacing_scale['steps'] - $steps_mid_point ) + $remainder;
for ( $above_midpoint_count = 0; $above_midpoint_count < $steps_above; $above_midpoint_count++ ) {
$current_step = '+' === $spacing_scale['operator']
? $current_step + $spacing_scale['increment']
: ( $spacing_scale['increment'] >= 1 ? $current_step * $spacing_scale['increment'] : $current_step / $spacing_scale['increment'] );
$above_sizes[] = array(
/* translators: %s: Digit to indicate multiple of sizing, eg. 2X-Large. */
'name' => 0 === $above_midpoint_count ? __( 'Large' ) : sprintf( __( '%sX-Large' ), (string) $x_large_count ),
'slug' => (string) $slug,
'size' => round( $current_step, 2 ) . $unit,
);
if ( 1 === $above_midpoint_count ) {
$x_large_count = 2;
}
if ( $above_midpoint_count > 1 ) {
$x_large_count++;
}
$slug += 10;
}
$spacing_sizes = array_merge( $below_sizes, $above_sizes );
// If there are 7 or less steps in the scale revert to numbers for labels instead of t-shirt sizes.
if ( $spacing_scale['steps'] <= 7 ) {
for ( $spacing_sizes_count = 0; $spacing_sizes_count < count( $spacing_sizes ); $spacing_sizes_count++ ) {
$spacing_sizes[ $spacing_sizes_count ]['name'] = (string) ( $spacing_sizes_count + 1 );
}
}
_wp_array_set( $this->theme_json, array( 'settings', 'spacing', 'spacingSizes', 'default' ), $spacing_sizes );
}
}
```
| programming_docs |
wordpress class WP_Style_Engine_CSS_Declarations {} class WP\_Style\_Engine\_CSS\_Declarations {}
=============================================
Class [WP\_Style\_Engine\_CSS\_Declarations](wp_style_engine_css_declarations).
Holds, sanitizes, processes and prints CSS declarations for the style engine.
* [\_\_construct](wp_style_engine_css_declarations/__construct) — Constructor for this object.
* [add\_declaration](wp_style_engine_css_declarations/add_declaration) — Adds a single declaration.
* [add\_declarations](wp_style_engine_css_declarations/add_declarations) — Adds multiple declarations.
* [filter\_declaration](wp_style_engine_css_declarations/filter_declaration) — Filters a CSS property + value pair.
* [get\_declarations](wp_style_engine_css_declarations/get_declarations) — Gets the declarations array.
* [get\_declarations\_string](wp_style_engine_css_declarations/get_declarations_string) — Filters and compiles the CSS declarations.
* [remove\_declaration](wp_style_engine_css_declarations/remove_declaration) — Removes a single declaration.
* [remove\_declarations](wp_style_engine_css_declarations/remove_declarations) — Removes multiple declarations.
* [sanitize\_property](wp_style_engine_css_declarations/sanitize_property) — Sanitizes property names.
File: `wp-includes/style-engine/class-wp-style-engine-css-declarations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-css-declarations.php/)
```
class WP_Style_Engine_CSS_Declarations {
/**
* An array of CSS declarations (property => value pairs).
*
* @since 6.1.0
*
* @var array
*/
protected $declarations = array();
/**
* Constructor for this object.
*
* If a `$declarations` array is passed, it will be used to populate
* the initial $declarations prop of the object by calling add_declarations().
*
* @since 6.1.0
*
* @param string[] $declarations An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ).
*/
public function __construct( $declarations = array() ) {
$this->add_declarations( $declarations );
}
/**
* Adds a single declaration.
*
* @since 6.1.0
*
* @param string $property The CSS property.
* @param string $value The CSS value.
*
* @return WP_Style_Engine_CSS_Declarations Returns the object to allow chaining methods.
*/
public function add_declaration( $property, $value ) {
// Sanitizes the property.
$property = $this->sanitize_property( $property );
// Bails early if the property is empty.
if ( empty( $property ) ) {
return $this;
}
// Trims the value. If empty, bail early.
$value = trim( $value );
if ( '' === $value ) {
return $this;
}
// Adds the declaration property/value pair.
$this->declarations[ $property ] = $value;
return $this;
}
/**
* Removes a single declaration.
*
* @since 6.1.0
*
* @param string $property The CSS property.
*
* @return WP_Style_Engine_CSS_Declarations Returns the object to allow chaining methods.
*/
public function remove_declaration( $property ) {
unset( $this->declarations[ $property ] );
return $this;
}
/**
* Adds multiple declarations.
*
* @since 6.1.0
*
* @param array $declarations An array of declarations.
*
* @return WP_Style_Engine_CSS_Declarations Returns the object to allow chaining methods.
*/
public function add_declarations( $declarations ) {
foreach ( $declarations as $property => $value ) {
$this->add_declaration( $property, $value );
}
return $this;
}
/**
* Removes multiple declarations.
*
* @since 6.1.0
*
* @param array $properties An array of properties.
*
* @return WP_Style_Engine_CSS_Declarations Returns the object to allow chaining methods.
*/
public function remove_declarations( $properties = array() ) {
foreach ( $properties as $property ) {
$this->remove_declaration( $property );
}
return $this;
}
/**
* Gets the declarations array.
*
* @since 6.1.0
*
* @return array
*/
public function get_declarations() {
return $this->declarations;
}
/**
* Filters a CSS property + value pair.
*
* @since 6.1.0
*
* @param string $property The CSS property.
* @param string $value The value to be filtered.
* @param string $spacer The spacer between the colon and the value. Defaults to an empty string.
*
* @return string The filtered declaration or an empty string.
*/
protected static function filter_declaration( $property, $value, $spacer = '' ) {
$filtered_value = wp_strip_all_tags( $value, true );
if ( '' !== $filtered_value ) {
return safecss_filter_attr( "{$property}:{$spacer}{$filtered_value}" );
}
return '';
}
/**
* Filters and compiles the CSS declarations.
*
* @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 The CSS declarations.
*/
public function get_declarations_string( $should_prettify = false, $indent_count = 0 ) {
$declarations_array = $this->get_declarations();
$declarations_output = '';
$indent = $should_prettify ? str_repeat( "\t", $indent_count ) : '';
$suffix = $should_prettify ? ' ' : '';
$suffix = $should_prettify && $indent_count > 0 ? "\n" : $suffix;
$spacer = $should_prettify ? ' ' : '';
foreach ( $declarations_array as $property => $value ) {
$filtered_declaration = static::filter_declaration( $property, $value, $spacer );
if ( $filtered_declaration ) {
$declarations_output .= "{$indent}{$filtered_declaration};$suffix";
}
}
return rtrim( $declarations_output );
}
/**
* Sanitizes property names.
*
* @since 6.1.0
*
* @param string $property The CSS property.
*
* @return string The sanitized property name.
*/
protected function sanitize_property( $property ) {
return sanitize_key( $property );
}
}
```
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress class WP_Recovery_Mode_Cookie_Service {} class WP\_Recovery\_Mode\_Cookie\_Service {}
============================================
Core class used to set, validate, and clear cookies that identify a Recovery Mode session.
* [clear\_cookie](wp_recovery_mode_cookie_service/clear_cookie) — Clears the recovery mode cookie.
* [generate\_cookie](wp_recovery_mode_cookie_service/generate_cookie) — Generates the recovery mode cookie value.
* [get\_session\_id\_from\_cookie](wp_recovery_mode_cookie_service/get_session_id_from_cookie) — Gets the session identifier from the cookie.
* [is\_cookie\_set](wp_recovery_mode_cookie_service/is_cookie_set) — Checks whether the recovery mode cookie is set.
* [parse\_cookie](wp_recovery_mode_cookie_service/parse_cookie) — Parses the cookie into its four parts.
* [recovery\_mode\_hash](wp_recovery_mode_cookie_service/recovery_mode_hash) — Gets a form of `wp\_hash()` specific to Recovery Mode.
* [set\_cookie](wp_recovery_mode_cookie_service/set_cookie) — Sets the recovery mode cookie.
* [validate\_cookie](wp_recovery_mode_cookie_service/validate_cookie) — Validates the recovery mode cookie.
File: `wp-includes/class-wp-recovery-mode-cookie-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-cookie-service.php/)
```
final class WP_Recovery_Mode_Cookie_Service {
/**
* Checks whether the recovery mode cookie is set.
*
* @since 5.2.0
*
* @return bool True if the cookie is set, false otherwise.
*/
public function is_cookie_set() {
return ! empty( $_COOKIE[ RECOVERY_MODE_COOKIE ] );
}
/**
* Sets the recovery mode cookie.
*
* This must be immediately followed by exiting the request.
*
* @since 5.2.0
*/
public function set_cookie() {
$value = $this->generate_cookie();
/**
* Filters the length of time a Recovery Mode cookie is valid for.
*
* @since 5.2.0
*
* @param int $length Length in seconds.
*/
$length = apply_filters( 'recovery_mode_cookie_length', WEEK_IN_SECONDS );
$expire = time() + $length;
setcookie( RECOVERY_MODE_COOKIE, $value, $expire, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
if ( COOKIEPATH !== SITECOOKIEPATH ) {
setcookie( RECOVERY_MODE_COOKIE, $value, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
}
}
/**
* Clears the recovery mode cookie.
*
* @since 5.2.0
*/
public function clear_cookie() {
setcookie( RECOVERY_MODE_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
setcookie( RECOVERY_MODE_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
}
/**
* Validates the recovery mode cookie.
*
* @since 5.2.0
*
* @param string $cookie Optionally specify the cookie string.
* If omitted, it will be retrieved from the super global.
* @return true|WP_Error True on success, error object on failure.
*/
public function validate_cookie( $cookie = '' ) {
if ( ! $cookie ) {
if ( empty( $_COOKIE[ RECOVERY_MODE_COOKIE ] ) ) {
return new WP_Error( 'no_cookie', __( 'No cookie present.' ) );
}
$cookie = $_COOKIE[ RECOVERY_MODE_COOKIE ];
}
$parts = $this->parse_cookie( $cookie );
if ( is_wp_error( $parts ) ) {
return $parts;
}
list( , $created_at, $random, $signature ) = $parts;
if ( ! ctype_digit( $created_at ) ) {
return new WP_Error( 'invalid_created_at', __( 'Invalid cookie format.' ) );
}
/** This filter is documented in wp-includes/class-wp-recovery-mode-cookie-service.php */
$length = apply_filters( 'recovery_mode_cookie_length', WEEK_IN_SECONDS );
if ( time() > $created_at + $length ) {
return new WP_Error( 'expired', __( 'Cookie expired.' ) );
}
$to_sign = sprintf( 'recovery_mode|%s|%s', $created_at, $random );
$hashed = $this->recovery_mode_hash( $to_sign );
if ( ! hash_equals( $signature, $hashed ) ) {
return new WP_Error( 'signature_mismatch', __( 'Invalid cookie.' ) );
}
return true;
}
/**
* Gets the session identifier from the cookie.
*
* The cookie should be validated before calling this API.
*
* @since 5.2.0
*
* @param string $cookie Optionally specify the cookie string.
* If omitted, it will be retrieved from the super global.
* @return string|WP_Error Session ID on success, or error object on failure.
*/
public function get_session_id_from_cookie( $cookie = '' ) {
if ( ! $cookie ) {
if ( empty( $_COOKIE[ RECOVERY_MODE_COOKIE ] ) ) {
return new WP_Error( 'no_cookie', __( 'No cookie present.' ) );
}
$cookie = $_COOKIE[ RECOVERY_MODE_COOKIE ];
}
$parts = $this->parse_cookie( $cookie );
if ( is_wp_error( $parts ) ) {
return $parts;
}
list( , , $random ) = $parts;
return sha1( $random );
}
/**
* Parses the cookie into its four parts.
*
* @since 5.2.0
*
* @param string $cookie Cookie content.
* @return array|WP_Error Cookie parts array, or error object on failure.
*/
private function parse_cookie( $cookie ) {
$cookie = base64_decode( $cookie );
$parts = explode( '|', $cookie );
if ( 4 !== count( $parts ) ) {
return new WP_Error( 'invalid_format', __( 'Invalid cookie format.' ) );
}
return $parts;
}
/**
* Generates the recovery mode cookie value.
*
* The cookie is a base64 encoded string with the following format:
*
* recovery_mode|iat|rand|signature
*
* Where "recovery_mode" is a constant string,
* iat is the time the cookie was generated at,
* rand is a randomly generated password that is also used as a session identifier
* and signature is an hmac of the preceding 3 parts.
*
* @since 5.2.0
*
* @return string Generated cookie content.
*/
private function generate_cookie() {
$to_sign = sprintf( 'recovery_mode|%s|%s', time(), wp_generate_password( 20, false ) );
$signed = $this->recovery_mode_hash( $to_sign );
return base64_encode( sprintf( '%s|%s', $to_sign, $signed ) );
}
/**
* Gets a form of `wp_hash()` specific to Recovery Mode.
*
* We cannot use `wp_hash()` because it is defined in `pluggable.php` which is not loaded until after plugins are loaded,
* which is too late to verify the recovery mode cookie.
*
* This tries to use the `AUTH` salts first, but if they aren't valid specific salts will be generated and stored.
*
* @since 5.2.0
*
* @param string $data Data to hash.
* @return string|false The hashed $data, or false on failure.
*/
private function recovery_mode_hash( $data ) {
$default_keys = array_unique(
array(
'put your unique phrase here',
/*
* translators: This string should only be translated if wp-config-sample.php is localized.
* You can check the localized release package or
* https://i18n.svn.wordpress.org/<locale code>/branches/<wp version>/dist/wp-config-sample.php
*/
__( 'put your unique phrase here' ),
)
);
if ( ! defined( 'AUTH_KEY' ) || in_array( AUTH_KEY, $default_keys, true ) ) {
$auth_key = get_site_option( 'recovery_mode_auth_key' );
if ( ! $auth_key ) {
if ( ! function_exists( 'wp_generate_password' ) ) {
require_once ABSPATH . WPINC . '/pluggable.php';
}
$auth_key = wp_generate_password( 64, true, true );
update_site_option( 'recovery_mode_auth_key', $auth_key );
}
} else {
$auth_key = AUTH_KEY;
}
if ( ! defined( 'AUTH_SALT' ) || in_array( AUTH_SALT, $default_keys, true ) || AUTH_SALT === $auth_key ) {
$auth_salt = get_site_option( 'recovery_mode_auth_salt' );
if ( ! $auth_salt ) {
if ( ! function_exists( 'wp_generate_password' ) ) {
require_once ABSPATH . WPINC . '/pluggable.php';
}
$auth_salt = wp_generate_password( 64, true, true );
update_site_option( 'recovery_mode_auth_salt', $auth_salt );
}
} else {
$auth_salt = AUTH_SALT;
}
$secret = $auth_key . $auth_salt;
return hash_hmac( 'sha1', $data, $secret );
}
}
```
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress class WP_Widget_RSS {} class WP\_Widget\_RSS {}
========================
Core class used to implement a RSS widget.
* [WP\_Widget](wp_widget)
* [\_\_construct](wp_widget_rss/__construct) — Sets up a new RSS widget instance.
* [form](wp_widget_rss/form) — Outputs the settings form for the RSS widget.
* [update](wp_widget_rss/update) — Handles updating settings for the current RSS widget instance.
* [widget](wp_widget_rss/widget) — Outputs the content for the current RSS widget instance.
File: `wp-includes/widgets/class-wp-widget-rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-rss.php/)
```
class WP_Widget_RSS extends WP_Widget {
/**
* Sets up a new RSS widget instance.
*
* @since 2.8.0
*/
public function __construct() {
$widget_ops = array(
'description' => __( 'Entries from any RSS or Atom feed.' ),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
);
$control_ops = array(
'width' => 400,
'height' => 200,
);
parent::__construct( 'rss', __( 'RSS' ), $widget_ops, $control_ops );
}
/**
* Outputs the content for the current RSS 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 RSS widget instance.
*/
public function widget( $args, $instance ) {
if ( isset( $instance['error'] ) && $instance['error'] ) {
return;
}
$url = ! empty( $instance['url'] ) ? $instance['url'] : '';
while ( ! empty( $url ) && stristr( $url, 'http' ) !== $url ) {
$url = substr( $url, 1 );
}
if ( empty( $url ) ) {
return;
}
// Self-URL destruction sequence.
if ( in_array( untrailingslashit( $url ), array( site_url(), home_url() ), true ) ) {
return;
}
$rss = fetch_feed( $url );
$title = $instance['title'];
$desc = '';
$link = '';
if ( ! is_wp_error( $rss ) ) {
$desc = esc_attr( strip_tags( html_entity_decode( $rss->get_description(), ENT_QUOTES, get_option( 'blog_charset' ) ) ) );
if ( empty( $title ) ) {
$title = strip_tags( $rss->get_title() );
}
$link = strip_tags( $rss->get_permalink() );
while ( ! empty( $link ) && stristr( $link, 'http' ) !== $link ) {
$link = substr( $link, 1 );
}
}
if ( empty( $title ) ) {
$title = ! empty( $desc ) ? $desc : __( 'Unknown Feed' );
}
/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
if ( $title ) {
$feed_link = '';
$feed_url = strip_tags( $url );
$feed_icon = includes_url( 'images/rss.png' );
$feed_link = sprintf(
'<a class="rsswidget rss-widget-feed" href="%1$s"><img class="rss-widget-icon" style="border:0" width="14" height="14" src="%2$s" alt="%3$s"%4$s /></a> ',
esc_url( $feed_url ),
esc_url( $feed_icon ),
esc_attr__( 'RSS' ),
( wp_lazy_loading_enabled( 'img', 'rss_widget_feed_icon' ) ? ' loading="lazy"' : '' )
);
/**
* Filters the classic RSS widget's feed icon link.
*
* Themes can remove the icon link by using `add_filter( 'rss_widget_feed_link', '__return_false' );`.
*
* @since 5.9.0
*
* @param string $feed_link HTML for link to RSS feed.
* @param array $instance Array of settings for the current widget.
*/
$feed_link = apply_filters( 'rss_widget_feed_link', $feed_link, $instance );
$title = $feed_link . '<a class="rsswidget rss-widget-title" href="' . esc_url( $link ) . '">' . esc_html( $title ) . '</a>';
}
echo $args['before_widget'];
if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
}
$format = current_theme_supports( 'html5', 'navigation-widgets' ) ? 'html5' : 'xhtml';
/** This filter is documented in wp-includes/widgets/class-wp-nav-menu-widget.php */
$format = apply_filters( 'navigation_widgets_format', $format );
if ( 'html5' === $format ) {
// The title may be filtered: Strip out HTML and make sure the aria-label is never empty.
$title = trim( strip_tags( $title ) );
$aria_label = $title ? $title : __( 'RSS Feed' );
echo '<nav aria-label="' . esc_attr( $aria_label ) . '">';
}
wp_widget_rss_output( $rss, $instance );
if ( 'html5' === $format ) {
echo '</nav>';
}
echo $args['after_widget'];
if ( ! is_wp_error( $rss ) ) {
$rss->__destruct();
}
unset( $rss );
}
/**
* Handles updating settings for the current RSS 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 ) {
$testurl = ( isset( $new_instance['url'] ) && ( ! isset( $old_instance['url'] ) || ( $new_instance['url'] !== $old_instance['url'] ) ) );
return wp_widget_rss_process( $new_instance, $testurl );
}
/**
* Outputs the settings form for the RSS widget.
*
* @since 2.8.0
*
* @param array $instance Current settings.
*/
public function form( $instance ) {
if ( empty( $instance ) ) {
$instance = array(
'title' => '',
'url' => '',
'items' => 10,
'error' => false,
'show_summary' => 0,
'show_author' => 0,
'show_date' => 0,
);
}
$instance['number'] = $this->number;
wp_widget_rss_form( $instance );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget](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_SimplePie_File {} class WP\_SimplePie\_File {}
============================
Core class for fetching remote files and reading local files with SimplePie.
This uses Core’s HTTP API to make requests, which gives plugins the ability to hook into the process.
* [SimplePie\_File](simplepie_file)
* [\_\_construct](wp_simplepie_file/__construct) — Constructor.
File: `wp-includes/class-wp-simplepie-file.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-simplepie-file.php/)
```
class WP_SimplePie_File extends SimplePie_File {
/**
* Timeout.
*
* @var int How long the connection should stay open in seconds.
*/
public $timeout = 10;
/**
* Constructor.
*
* @since 2.8.0
* @since 3.2.0 Updated to use a PHP5 constructor.
* @since 5.6.1 Multiple headers are concatenated into a comma-separated string,
* rather than remaining an array.
*
* @param string $url Remote file URL.
* @param int $timeout Optional. How long the connection should stay open in seconds.
* Default 10.
* @param int $redirects Optional. The number of allowed redirects. Default 5.
* @param string|array $headers Optional. Array or string of headers to send with the request.
* Default null.
* @param string $useragent Optional. User-agent value sent. Default null.
* @param bool $force_fsockopen Optional. Whether to force opening internet or unix domain socket
* connection or not. Default false.
*/
public function __construct( $url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false ) {
$this->url = $url;
$this->timeout = $timeout;
$this->redirects = $redirects;
$this->headers = $headers;
$this->useragent = $useragent;
$this->method = SIMPLEPIE_FILE_SOURCE_REMOTE;
if ( preg_match( '/^http(s)?:\/\//i', $url ) ) {
$args = array(
'timeout' => $this->timeout,
'redirection' => $this->redirects,
);
if ( ! empty( $this->headers ) ) {
$args['headers'] = $this->headers;
}
if ( SIMPLEPIE_USERAGENT != $this->useragent ) { // Use default WP user agent unless custom has been specified.
$args['user-agent'] = $this->useragent;
}
$res = wp_safe_remote_request( $url, $args );
if ( is_wp_error( $res ) ) {
$this->error = 'WP HTTP Error: ' . $res->get_error_message();
$this->success = false;
} else {
$this->headers = wp_remote_retrieve_headers( $res );
/*
* SimplePie expects multiple headers to be stored as a comma-separated string,
* but `wp_remote_retrieve_headers()` returns them as an array, so they need
* to be converted.
*
* The only exception to that is the `content-type` header, which should ignore
* any previous values and only use the last one.
*
* @see SimplePie_HTTP_Parser::new_line().
*/
foreach ( $this->headers as $name => $value ) {
if ( ! is_array( $value ) ) {
continue;
}
if ( 'content-type' === $name ) {
$this->headers[ $name ] = array_pop( $value );
} else {
$this->headers[ $name ] = implode( ', ', $value );
}
}
$this->body = wp_remote_retrieve_body( $res );
$this->status_code = wp_remote_retrieve_response_code( $res );
}
} else {
$this->error = '';
$this->success = false;
}
}
}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress class WP_Sitemaps_Taxonomies {} class WP\_Sitemaps\_Taxonomies {}
=================================
Taxonomies XML sitemap provider.
* [\_\_construct](wp_sitemaps_taxonomies/__construct) — WP\_Sitemaps\_Taxonomies constructor.
* [get\_max\_num\_pages](wp_sitemaps_taxonomies/get_max_num_pages) — Gets the max number of pages available for the object type.
* [get\_object\_subtypes](wp_sitemaps_taxonomies/get_object_subtypes) — Returns all public, registered taxonomies.
* [get\_taxonomies\_query\_args](wp_sitemaps_taxonomies/get_taxonomies_query_args) — Returns the query args for retrieving taxonomy terms to list in the sitemap.
* [get\_url\_list](wp_sitemaps_taxonomies/get_url_list) — Gets a URL list for a taxonomy sitemap.
File: `wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php/)
```
class WP_Sitemaps_Taxonomies extends WP_Sitemaps_Provider {
/**
* WP_Sitemaps_Taxonomies constructor.
*
* @since 5.5.0
*/
public function __construct() {
$this->name = 'taxonomies';
$this->object_type = 'term';
}
/**
* Returns all public, registered taxonomies.
*
* @since 5.5.0
*
* @return WP_Taxonomy[] Array of registered taxonomy objects keyed by their name.
*/
public function get_object_subtypes() {
$taxonomies = get_taxonomies( array( 'public' => true ), 'objects' );
$taxonomies = array_filter( $taxonomies, 'is_taxonomy_viewable' );
/**
* Filters the list of taxonomy object subtypes available within the sitemap.
*
* @since 5.5.0
*
* @param WP_Taxonomy[] $taxonomies Array of registered taxonomy objects keyed by their name.
*/
return apply_filters( 'wp_sitemaps_taxonomies', $taxonomies );
}
/**
* Gets a URL list for a taxonomy sitemap.
*
* @since 5.5.0
* @since 5.9.0 Renamed `$taxonomy` 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. Taxonomy 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.
$taxonomy = $object_subtype;
$supported_types = $this->get_object_subtypes();
// Bail early if the queried taxonomy is not supported.
if ( ! isset( $supported_types[ $taxonomy ] ) ) {
return array();
}
/**
* Filters the taxonomies URL list before it is generated.
*
* Returning a non-null value will effectively short-circuit the generation,
* returning that value instead.
*
* @since 5.5.0
*
* @param array[]|null $url_list The URL list. Default null.
* @param string $taxonomy Taxonomy name.
* @param int $page_num Page of results.
*/
$url_list = apply_filters(
'wp_sitemaps_taxonomies_pre_url_list',
null,
$taxonomy,
$page_num
);
if ( null !== $url_list ) {
return $url_list;
}
$url_list = array();
// Offset by how many terms should be included in previous pages.
$offset = ( $page_num - 1 ) * wp_sitemaps_get_max_urls( $this->object_type );
$args = $this->get_taxonomies_query_args( $taxonomy );
$args['fields'] = 'all';
$args['offset'] = $offset;
$taxonomy_terms = new WP_Term_Query( $args );
if ( ! empty( $taxonomy_terms->terms ) ) {
foreach ( $taxonomy_terms->terms as $term ) {
$term_link = get_term_link( $term, $taxonomy );
if ( is_wp_error( $term_link ) ) {
continue;
}
$sitemap_entry = array(
'loc' => $term_link,
);
/**
* Filters the sitemap entry for an individual term.
*
* @since 5.5.0
* @since 6.0.0 Added `$term` argument containing the term object.
*
* @param array $sitemap_entry Sitemap entry for the term.
* @param int $term_id Term ID.
* @param string $taxonomy Taxonomy name.
* @param WP_Term $term Term object.
*/
$sitemap_entry = apply_filters( 'wp_sitemaps_taxonomies_entry', $sitemap_entry, $term->term_id, $taxonomy, $term );
$url_list[] = $sitemap_entry;
}
}
return $url_list;
}
/**
* Gets the max number of pages available for the object type.
*
* @since 5.5.0
* @since 5.9.0 Renamed `$taxonomy` to `$object_subtype` to match parent class
* for PHP 8 named parameter support.
*
* @param string $object_subtype Optional. Taxonomy 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.
$taxonomy = $object_subtype;
/**
* Filters the max number of pages for a taxonomy sitemap before it is generated.
*
* Passing a non-null value will short-circuit the generation,
* returning that value instead.
*
* @since 5.5.0
*
* @param int|null $max_num_pages The maximum number of pages. Default null.
* @param string $taxonomy Taxonomy name.
*/
$max_num_pages = apply_filters( 'wp_sitemaps_taxonomies_pre_max_num_pages', null, $taxonomy );
if ( null !== $max_num_pages ) {
return $max_num_pages;
}
$term_count = wp_count_terms( $this->get_taxonomies_query_args( $taxonomy ) );
return (int) ceil( $term_count / wp_sitemaps_get_max_urls( $this->object_type ) );
}
/**
* Returns the query args for retrieving taxonomy terms to list in the sitemap.
*
* @since 5.5.0
*
* @param string $taxonomy Taxonomy name.
* @return array Array of WP_Term_Query arguments.
*/
protected function get_taxonomies_query_args( $taxonomy ) {
/**
* Filters the taxonomy terms query arguments.
*
* Allows modification of the taxonomy query arguments before querying.
*
* @see WP_Term_Query for a full list of arguments
*
* @since 5.5.0
*
* @param array $args Array of WP_Term_Query arguments.
* @param string $taxonomy Taxonomy name.
*/
$args = apply_filters(
'wp_sitemaps_taxonomies_query_args',
array(
'taxonomy' => $taxonomy,
'orderby' => 'term_order',
'number' => wp_sitemaps_get_max_urls( $this->object_type ),
'hide_empty' => true,
'hierarchical' => false,
'update_term_meta_cache' => false,
),
$taxonomy
);
return $args;
}
}
```
| 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 WP_Block_Styles_Registry {} class WP\_Block\_Styles\_Registry {}
====================================
Class used for interacting with block styles.
* [get\_all\_registered](wp_block_styles_registry/get_all_registered) — Retrieves all registered block styles.
* [get\_instance](wp_block_styles_registry/get_instance) — Utility method to retrieve the main instance of the class.
* [get\_registered](wp_block_styles_registry/get_registered) — Retrieves the properties of a registered block style for the given block type.
* [get\_registered\_styles\_for\_block](wp_block_styles_registry/get_registered_styles_for_block) — Retrieves registered block styles for a specific block type.
* [is\_registered](wp_block_styles_registry/is_registered) — Checks if a block style is registered for the given block type.
* [register](wp_block_styles_registry/register) — Registers a block style for the given block type.
* [unregister](wp_block_styles_registry/unregister) — Unregisters a block style of the given block type.
File: `wp-includes/class-wp-block-styles-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-styles-registry.php/)
```
final class WP_Block_Styles_Registry {
/**
* Registered block styles, as `$block_name => $block_style_name => $block_style_properties` multidimensional arrays.
*
* @since 5.3.0
*
* @var array[]
*/
private $registered_block_styles = array();
/**
* Container for the main instance of the class.
*
* @since 5.3.0
*
* @var WP_Block_Styles_Registry|null
*/
private static $instance = null;
/**
* Registers a block style for the given block type.
*
* If the block styles are present in a standalone stylesheet, register it and pass
* its handle as the `style_handle` argument. If the block styles should be inline,
* use the `inline_style` argument. Usually, one of them would be used to pass CSS
* styles. However, you could also skip them and provide CSS styles in any stylesheet
* or with an inline tag.
*
* @since 5.3.0
*
* @link https://developer.wordpress.org/block-editor/reference-guides/block-api/block-styles/
*
* @param string $block_name Block type name including namespace.
* @param array $style_properties {
* Array containing the properties of the style.
*
* @type string $name The identifier of the style used to compute a CSS class.
* @type string $label A human-readable label for the style.
* @type string $inline_style Inline CSS code that registers the CSS class required
* for the style.
* @type string $style_handle The handle to an already registered style that should be
* enqueued in places where block styles are needed.
* @type bool $is_default Whether this is the default style for the block type.
* }
* @return bool True if the block style was registered with success and false otherwise.
*/
public function register( $block_name, $style_properties ) {
if ( ! isset( $block_name ) || ! is_string( $block_name ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Block name must be a string.' ),
'5.3.0'
);
return false;
}
if ( ! isset( $style_properties['name'] ) || ! is_string( $style_properties['name'] ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Block style name must be a string.' ),
'5.3.0'
);
return false;
}
if ( str_contains( $style_properties['name'], ' ' ) ) {
_doing_it_wrong(
__METHOD__,
__( 'Block style name must not contain any spaces.' ),
'5.9.0'
);
return false;
}
$block_style_name = $style_properties['name'];
if ( ! isset( $this->registered_block_styles[ $block_name ] ) ) {
$this->registered_block_styles[ $block_name ] = array();
}
$this->registered_block_styles[ $block_name ][ $block_style_name ] = $style_properties;
return true;
}
/**
* Unregisters a block style of the given block type.
*
* @since 5.3.0
*
* @param string $block_name Block type name including namespace.
* @param string $block_style_name Block style name.
* @return bool True if the block style was unregistered with success and false otherwise.
*/
public function unregister( $block_name, $block_style_name ) {
if ( ! $this->is_registered( $block_name, $block_style_name ) ) {
_doing_it_wrong(
__METHOD__,
/* translators: 1: Block name, 2: Block style name. */
sprintf( __( 'Block "%1$s" does not contain a style named "%2$s".' ), $block_name, $block_style_name ),
'5.3.0'
);
return false;
}
unset( $this->registered_block_styles[ $block_name ][ $block_style_name ] );
return true;
}
/**
* Retrieves the properties of a registered block style for the given block type.
*
* @since 5.3.0
*
* @param string $block_name Block type name including namespace.
* @param string $block_style_name Block style name.
* @return array Registered block style properties.
*/
public function get_registered( $block_name, $block_style_name ) {
if ( ! $this->is_registered( $block_name, $block_style_name ) ) {
return null;
}
return $this->registered_block_styles[ $block_name ][ $block_style_name ];
}
/**
* Retrieves all registered block styles.
*
* @since 5.3.0
*
* @return array[] Array of arrays containing the registered block styles properties grouped by block type.
*/
public function get_all_registered() {
return $this->registered_block_styles;
}
/**
* Retrieves registered block styles for a specific block type.
*
* @since 5.3.0
*
* @param string $block_name Block type name including namespace.
* @return array[] Array whose keys are block style names and whose values are block style properties.
*/
public function get_registered_styles_for_block( $block_name ) {
if ( isset( $this->registered_block_styles[ $block_name ] ) ) {
return $this->registered_block_styles[ $block_name ];
}
return array();
}
/**
* Checks if a block style is registered for the given block type.
*
* @since 5.3.0
*
* @param string $block_name Block type name including namespace.
* @param string $block_style_name Block style name.
* @return bool True if the block style is registered, false otherwise.
*/
public function is_registered( $block_name, $block_style_name ) {
return isset( $this->registered_block_styles[ $block_name ][ $block_style_name ] );
}
/**
* Utility method to retrieve the main instance of the class.
*
* The instance will be created if it does not exist yet.
*
* @since 5.3.0
*
* @return WP_Block_Styles_Registry The main instance.
*/
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
}
```
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress class WP_Customize_Themes_Section {} class WP\_Customize\_Themes\_Section {}
=======================================
Customize Themes Section class.
A UI container for theme controls, which are displayed within sections.
* [WP\_Customize\_Section](wp_customize_section)
* [filter\_bar\_content\_template](wp_customize_themes_section/filter_bar_content_template) — Render the filter bar portion of a themes section as a JS template.
* [filter\_drawer\_content\_template](wp_customize_themes_section/filter_drawer_content_template) — Render the filter drawer portion of a themes section as a JS template.
* [json](wp_customize_themes_section/json) — Get section parameters for JS.
* [render](wp_customize_themes_section/render) — Render the themes section, which behaves like a panel.
* [render\_template](wp_customize_themes_section/render_template) — Render a themes section as a JS template.
File: `wp-includes/customize/class-wp-customize-themes-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-themes-section.php/)
```
class WP_Customize_Themes_Section extends WP_Customize_Section {
/**
* Section type.
*
* @since 4.2.0
* @var string
*/
public $type = 'themes';
/**
* Theme section action.
*
* Defines the type of themes to load (installed, wporg, etc.).
*
* @since 4.9.0
* @var string
*/
public $action = '';
/**
* Theme section filter type.
*
* Determines whether filters are applied to loaded (local) themes or by initiating a new remote query (remote).
* When filtering is local, the initial themes query is not paginated by default.
*
* @since 4.9.0
* @var string
*/
public $filter_type = 'local';
/**
* Get section parameters for JS.
*
* @since 4.9.0
* @return array Exported parameters.
*/
public function json() {
$exported = parent::json();
$exported['action'] = $this->action;
$exported['filter_type'] = $this->filter_type;
return $exported;
}
/**
* Render a themes section as a JS template.
*
* The template is only rendered by PHP once, so all actions are prepared at once on the server side.
*
* @since 4.9.0
*/
protected function render_template() {
?>
<li id="accordion-section-{{ data.id }}" class="theme-section">
<button type="button" class="customize-themes-section-title themes-section-{{ data.id }}">{{ data.title }}</button>
<?php if ( current_user_can( 'install_themes' ) || is_multisite() ) : // @todo Upload support. ?>
<?php endif; ?>
<div class="customize-themes-section themes-section-{{ data.id }} control-section-content themes-php">
<div class="theme-overlay" tabindex="0" role="dialog" aria-label="<?php esc_attr_e( 'Theme Details' ); ?>"></div>
<div class="theme-browser rendered">
<div class="customize-preview-header themes-filter-bar">
<?php $this->filter_bar_content_template(); ?>
</div>
<?php $this->filter_drawer_content_template(); ?>
<div class="error unexpected-error" style="display: none; ">
<p>
<?php
printf(
/* translators: %s: Support forums URL. */
__( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the <a href="%s">support forums</a>.' ),
__( 'https://wordpress.org/support/forums/' )
);
?>
</p>
</div>
<ul class="themes">
</ul>
<p class="no-themes"><?php _e( 'No themes found. Try a different search.' ); ?></p>
<p class="no-themes-local">
<?php
printf(
/* translators: %s: "Search WordPress.org themes" button text. */
__( 'No themes found. Try a different search, or %s.' ),
sprintf( '<button type="button" class="button-link search-dotorg-themes">%s</button>', __( 'Search WordPress.org themes' ) )
);
?>
</p>
<p class="spinner"></p>
</div>
</div>
</li>
<?php
}
/**
* Render the filter bar portion of a themes section as a JS template.
*
* The template is only rendered by PHP once, so all actions are prepared at once on the server side.
* The filter bar container is rendered by @see `render_template()`.
*
* @since 4.9.0
*/
protected function filter_bar_content_template() {
?>
<button type="button" class="button button-primary customize-section-back customize-themes-mobile-back"><?php _e( 'Go to theme sources' ); ?></button>
<# if ( 'wporg' === data.action ) { #>
<div class="search-form">
<label for="wp-filter-search-input-{{ data.id }}" class="screen-reader-text"><?php _e( 'Search themes…' ); ?></label>
<input type="search" id="wp-filter-search-input-{{ data.id }}" placeholder="<?php esc_attr_e( 'Search themes…' ); ?>" aria-describedby="{{ data.id }}-live-search-desc" class="wp-filter-search">
<div class="search-icon" aria-hidden="true"></div>
<span id="{{ data.id }}-live-search-desc" class="screen-reader-text"><?php _e( 'The search results will be updated as you type.' ); ?></span>
</div>
<button type="button" class="button feature-filter-toggle">
<span class="filter-count-0"><?php _e( 'Filter themes' ); ?></span><span class="filter-count-filters">
<?php
/* translators: %s: Number of filters selected. */
printf( __( 'Filter themes (%s)' ), '<span class="theme-filter-count">0</span>' );
?>
</span>
</button>
<# } else { #>
<div class="themes-filter-container">
<label for="{{ data.id }}-themes-filter" class="screen-reader-text"><?php _e( 'Search themes…' ); ?></label>
<input type="search" id="{{ data.id }}-themes-filter" placeholder="<?php esc_attr_e( 'Search themes…' ); ?>" aria-describedby="{{ data.id }}-live-search-desc" class="wp-filter-search wp-filter-search-themes" />
<div class="search-icon" aria-hidden="true"></div>
<span id="{{ data.id }}-live-search-desc" class="screen-reader-text"><?php _e( 'The search results will be updated as you type.' ); ?></span>
</div>
<# } #>
<div class="filter-themes-count">
<span class="themes-displayed">
<?php
/* translators: %s: Number of themes displayed. */
printf( __( '%s themes' ), '<span class="theme-count">0</span>' );
?>
</span>
</div>
<?php
}
/**
* Render the filter drawer portion of a themes section as a JS template.
*
* The filter bar container is rendered by @see `render_template()`.
*
* @since 4.9.0
*/
protected function filter_drawer_content_template() {
// @todo Use the .org API instead of the local core feature list.
// The .org API is currently outdated and will be reconciled when the .org themes directory is next redesigned.
$feature_list = get_theme_feature_list( false );
?>
<# if ( 'wporg' === data.action ) { #>
<div class="filter-drawer filter-details">
<?php foreach ( $feature_list as $feature_name => $features ) : ?>
<fieldset class="filter-group">
<legend><?php echo esc_html( $feature_name ); ?></legend>
<div class="filter-group-feature">
<?php foreach ( $features as $feature => $feature_name ) : ?>
<input type="checkbox" id="filter-id-<?php echo esc_attr( $feature ); ?>" value="<?php echo esc_attr( $feature ); ?>" />
<label for="filter-id-<?php echo esc_attr( $feature ); ?>"><?php echo esc_html( $feature_name ); ?></label>
<?php endforeach; ?>
</div>
</fieldset>
<?php endforeach; ?>
</div>
<# } #>
<?php
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Section](wp_customize_section) wp-includes/class-wp-customize-section.php | Customize Section class. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
| programming_docs |
wordpress class WP_Widget_Block {} class WP\_Widget\_Block {}
==========================
Core class used to implement a Block widget.
* [WP\_Widget](wp_widget)
* [\_\_construct](wp_widget_block/__construct) — Sets up a new Block widget instance.
* [form](wp_widget_block/form) — Outputs the Block widget settings form.
* [get\_dynamic\_classname](wp_widget_block/get_dynamic_classname) — Calculates the classname to use in the block widget's container HTML.
* [set\_is\_wide\_widget\_in\_customizer](wp_widget_block/set_is_wide_widget_in_customizer) — Makes sure no block widget is considered to be wide.
* [update](wp_widget_block/update) — Handles updating settings for the current Block widget instance.
* [widget](wp_widget_block/widget) — Outputs the content for the current Block widget instance.
File: `wp-includes/widgets/class-wp-widget-block.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-block.php/)
```
class WP_Widget_Block extends WP_Widget {
/**
* Default instance.
*
* @since 5.8.0
* @var array
*/
protected $default_instance = array(
'content' => '',
);
/**
* Sets up a new Block widget instance.
*
* @since 5.8.0
*/
public function __construct() {
$widget_ops = array(
'classname' => 'widget_block',
'description' => __( 'A widget containing a block.' ),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
);
$control_ops = array(
'width' => 400,
'height' => 350,
);
parent::__construct( 'block', __( 'Block' ), $widget_ops, $control_ops );
add_filter( 'is_wide_widget_in_customizer', array( $this, 'set_is_wide_widget_in_customizer' ), 10, 2 );
}
/**
* Outputs the content for the current Block widget instance.
*
* @since 5.8.0
*
* @param array $args Display arguments including 'before_title', 'after_title',
* 'before_widget', and 'after_widget'.
* @param array $instance Settings for the current Block widget instance.
*/
public function widget( $args, $instance ) {
$instance = wp_parse_args( $instance, $this->default_instance );
echo str_replace(
'widget_block',
$this->get_dynamic_classname( $instance['content'] ),
$args['before_widget']
);
/**
* Filters the content of the Block widget before output.
*
* @since 5.8.0
*
* @param string $content The widget content.
* @param array $instance Array of settings for the current widget.
* @param WP_Widget_Block $widget Current Block widget instance.
*/
echo apply_filters(
'widget_block_content',
$instance['content'],
$instance,
$this
);
echo $args['after_widget'];
}
/**
* Calculates the classname to use in the block widget's container HTML.
*
* Usually this is set to `$this->widget_options['classname']` by
* dynamic_sidebar(). In this case, however, we want to set the classname
* dynamically depending on the block contained by this block widget.
*
* If a block widget contains a block that has an equivalent legacy widget,
* we display that legacy widget's class name. This helps with theme
* backwards compatibility.
*
* @since 5.8.0
*
* @param string $content The HTML content of the current block widget.
* @return string The classname to use in the block widget's container HTML.
*/
private function get_dynamic_classname( $content ) {
$blocks = parse_blocks( $content );
$block_name = isset( $blocks[0] ) ? $blocks[0]['blockName'] : null;
switch ( $block_name ) {
case 'core/paragraph':
$classname = 'widget_block widget_text';
break;
case 'core/calendar':
$classname = 'widget_block widget_calendar';
break;
case 'core/search':
$classname = 'widget_block widget_search';
break;
case 'core/html':
$classname = 'widget_block widget_custom_html';
break;
case 'core/archives':
$classname = 'widget_block widget_archive';
break;
case 'core/latest-posts':
$classname = 'widget_block widget_recent_entries';
break;
case 'core/latest-comments':
$classname = 'widget_block widget_recent_comments';
break;
case 'core/tag-cloud':
$classname = 'widget_block widget_tag_cloud';
break;
case 'core/categories':
$classname = 'widget_block widget_categories';
break;
case 'core/audio':
$classname = 'widget_block widget_media_audio';
break;
case 'core/video':
$classname = 'widget_block widget_media_video';
break;
case 'core/image':
$classname = 'widget_block widget_media_image';
break;
case 'core/gallery':
$classname = 'widget_block widget_media_gallery';
break;
case 'core/rss':
$classname = 'widget_block widget_rss';
break;
default:
$classname = 'widget_block';
}
/**
* The classname used in the block widget's container HTML.
*
* This can be set according to the name of the block contained by the block widget.
*
* @since 5.8.0
*
* @param string $classname The classname to be used in the block widget's container HTML,
* e.g. 'widget_block widget_text'.
* @param string $block_name The name of the block contained by the block widget,
* e.g. 'core/paragraph'.
*/
return apply_filters( 'widget_block_dynamic_classname', $classname, $block_name );
}
/**
* Handles updating settings for the current Block widget instance.
*
* @since 5.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 ) {
$instance = array_merge( $this->default_instance, $old_instance );
if ( current_user_can( 'unfiltered_html' ) ) {
$instance['content'] = $new_instance['content'];
} else {
$instance['content'] = wp_kses_post( $new_instance['content'] );
}
return $instance;
}
/**
* Outputs the Block widget settings form.
*
* @since 5.8.0
*
* @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 );
?>
<p>
<label for="<?php echo $this->get_field_id( 'content' ); ?>">
<?php
/* translators: HTML code of the block, not an option that blocks HTML. */
_e( 'Block HTML:' );
?>
</label>
<textarea id="<?php echo $this->get_field_id( 'content' ); ?>" name="<?php echo $this->get_field_name( 'content' ); ?>" rows="6" cols="50" class="widefat code"><?php echo esc_textarea( $instance['content'] ); ?></textarea>
</p>
<?php
}
/**
* Makes sure no block widget is considered to be wide.
*
* @since 5.8.0
*
* @param bool $is_wide Whether the widget is considered wide.
* @param string $widget_id Widget ID.
* @return bool Updated `is_wide` value.
*/
public function set_is_wide_widget_in_customizer( $is_wide, $widget_id ) {
if ( strpos( $widget_id, 'block-' ) === 0 ) {
return false;
}
return $is_wide;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget](wp_widget) wp-includes/class-wp-widget.php | Core base class extended to register widgets. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress class WP_Recovery_Mode_Email_Service {} class WP\_Recovery\_Mode\_Email\_Service {}
===========================================
Core class used to send an email with a link to begin Recovery Mode.
* [\_\_construct](wp_recovery_mode_email_service/__construct) — WP\_Recovery\_Mode\_Email\_Service constructor.
* [clear\_rate\_limit](wp_recovery_mode_email_service/clear_rate_limit) — Clears the rate limit, allowing a new recovery mode email to be sent immediately.
* [get\_cause](wp_recovery_mode_email_service/get_cause) — Gets the description indicating the possible cause for the error.
* [get\_debug](wp_recovery_mode_email_service/get_debug) — Return debug information in an easy to manipulate format.
* [get\_plugin](wp_recovery_mode_email_service/get_plugin) — Return the details for a single plugin based on the extension data from an error.
* [get\_recovery\_mode\_email\_address](wp_recovery_mode_email_service/get_recovery_mode_email_address) — Gets the email address to send the recovery mode link to.
* [maybe\_send\_recovery\_mode\_email](wp_recovery_mode_email_service/maybe_send_recovery_mode_email) — Sends the recovery mode email if the rate limit has not been sent.
* [send\_recovery\_mode\_email](wp_recovery_mode_email_service/send_recovery_mode_email) — Sends the Recovery Mode email to the site admin email address.
File: `wp-includes/class-wp-recovery-mode-email-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-email-service.php/)
```
final class WP_Recovery_Mode_Email_Service {
const RATE_LIMIT_OPTION = 'recovery_mode_email_last_sent';
/**
* Service to generate recovery mode URLs.
*
* @since 5.2.0
* @var WP_Recovery_Mode_Link_Service
*/
private $link_service;
/**
* WP_Recovery_Mode_Email_Service constructor.
*
* @since 5.2.0
*
* @param WP_Recovery_Mode_Link_Service $link_service
*/
public function __construct( WP_Recovery_Mode_Link_Service $link_service ) {
$this->link_service = $link_service;
}
/**
* Sends the recovery mode email if the rate limit has not been sent.
*
* @since 5.2.0
*
* @param int $rate_limit Number of seconds before another email can be sent.
* @param array $error Error details from `error_get_last()`.
* @param array $extension {
* The extension that caused the error.
*
* @type string $slug The extension slug. The plugin or theme's directory.
* @type string $type The extension type. Either 'plugin' or 'theme'.
* }
* @return true|WP_Error True if email sent, WP_Error otherwise.
*/
public function maybe_send_recovery_mode_email( $rate_limit, $error, $extension ) {
$last_sent = get_option( self::RATE_LIMIT_OPTION );
if ( ! $last_sent || time() > $last_sent + $rate_limit ) {
if ( ! update_option( self::RATE_LIMIT_OPTION, time() ) ) {
return new WP_Error( 'storage_error', __( 'Could not update the email last sent time.' ) );
}
$sent = $this->send_recovery_mode_email( $rate_limit, $error, $extension );
if ( $sent ) {
return true;
}
return new WP_Error(
'email_failed',
sprintf(
/* translators: %s: mail() */
__( 'The email could not be sent. Possible reason: your host may have disabled the %s function.' ),
'mail()'
)
);
}
$err_message = sprintf(
/* translators: 1: Last sent as a human time diff, 2: Wait time as a human time diff. */
__( 'A recovery link was already sent %1$s ago. Please wait another %2$s before requesting a new email.' ),
human_time_diff( $last_sent ),
human_time_diff( $last_sent + $rate_limit )
);
return new WP_Error( 'email_sent_already', $err_message );
}
/**
* Clears the rate limit, allowing a new recovery mode email to be sent immediately.
*
* @since 5.2.0
*
* @return bool True on success, false on failure.
*/
public function clear_rate_limit() {
return delete_option( self::RATE_LIMIT_OPTION );
}
/**
* Sends the Recovery Mode email to the site admin email address.
*
* @since 5.2.0
*
* @param int $rate_limit Number of seconds before another email can be sent.
* @param array $error Error details from `error_get_last()`.
* @param array $extension {
* The extension that caused the error.
*
* @type string $slug The extension slug. The directory of the plugin or theme.
* @type string $type The extension type. Either 'plugin' or 'theme'.
* }
* @return bool Whether the email was sent successfully.
*/
private function send_recovery_mode_email( $rate_limit, $error, $extension ) {
$url = $this->link_service->generate_url();
$blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
$switched_locale = false;
// The switch_to_locale() function is loaded before it can actually be used.
if ( function_exists( 'switch_to_locale' ) && isset( $GLOBALS['wp_locale_switcher'] ) ) {
$switched_locale = switch_to_locale( get_locale() );
}
if ( $extension ) {
$cause = $this->get_cause( $extension );
$details = wp_strip_all_tags( wp_get_extension_error_description( $error ) );
if ( $details ) {
$header = __( 'Error Details' );
$details = "\n\n" . $header . "\n" . str_pad( '', strlen( $header ), '=' ) . "\n" . $details;
}
} else {
$cause = '';
$details = '';
}
/**
* Filters the support message sent with the the fatal error protection email.
*
* @since 5.2.0
*
* @param string $message The Message to include in the email.
*/
$support = apply_filters( 'recovery_email_support_info', __( 'Please contact your host for assistance with investigating this issue further.' ) );
/**
* Filters the debug information included in the fatal error protection email.
*
* @since 5.3.0
*
* @param array $message An associative array of debug information.
*/
$debug = apply_filters( 'recovery_email_debug_info', $this->get_debug( $extension ) );
/* translators: Do not translate LINK, EXPIRES, CAUSE, DETAILS, SITEURL, PAGEURL, SUPPORT. DEBUG: those are placeholders. */
$message = __(
'Howdy!
Since WordPress 5.2 there is a built-in feature that detects when a plugin or theme causes a fatal error on your site, and notifies you with this automated email.
###CAUSE###
First, visit your website (###SITEURL###) and check for any visible issues. Next, visit the page where the error was caught (###PAGEURL###) and check for any visible issues.
###SUPPORT###
If your site appears broken and you can\'t access your dashboard normally, WordPress now has a special "recovery mode". This lets you safely login to your dashboard and investigate further.
###LINK###
To keep your site safe, this link will expire in ###EXPIRES###. Don\'t worry about that, though: a new link will be emailed to you if the error occurs again after it expires.
When seeking help with this issue, you may be asked for some of the following information:
###DEBUG###
###DETAILS###'
);
$message = str_replace(
array(
'###LINK###',
'###EXPIRES###',
'###CAUSE###',
'###DETAILS###',
'###SITEURL###',
'###PAGEURL###',
'###SUPPORT###',
'###DEBUG###',
),
array(
$url,
human_time_diff( time() + $rate_limit ),
$cause ? "\n{$cause}\n" : "\n",
$details,
home_url( '/' ),
home_url( $_SERVER['REQUEST_URI'] ),
$support,
implode( "\r\n", $debug ),
),
$message
);
$email = array(
'to' => $this->get_recovery_mode_email_address(),
/* translators: %s: Site title. */
'subject' => __( '[%s] Your Site is Experiencing a Technical Issue' ),
'message' => $message,
'headers' => '',
'attachments' => '',
);
/**
* Filters the contents of the Recovery Mode email.
*
* @since 5.2.0
* @since 5.6.0 The `$email` argument includes the `attachments` key.
*
* @param array $email {
* Used to build a call to wp_mail().
*
* @type string|array $to Array or comma-separated list of email addresses to send message.
* @type string $subject Email subject
* @type string $message Message contents
* @type string|array $headers Optional. Additional headers.
* @type string|array $attachments Optional. Files to attach.
* }
* @param string $url URL to enter recovery mode.
*/
$email = apply_filters( 'recovery_mode_email', $email, $url );
$sent = wp_mail(
$email['to'],
wp_specialchars_decode( sprintf( $email['subject'], $blogname ) ),
$email['message'],
$email['headers'],
$email['attachments']
);
if ( $switched_locale ) {
restore_previous_locale();
}
return $sent;
}
/**
* Gets the email address to send the recovery mode link to.
*
* @since 5.2.0
*
* @return string Email address to send recovery mode link to.
*/
private function get_recovery_mode_email_address() {
if ( defined( 'RECOVERY_MODE_EMAIL' ) && is_email( RECOVERY_MODE_EMAIL ) ) {
return RECOVERY_MODE_EMAIL;
}
return get_option( 'admin_email' );
}
/**
* Gets the description indicating the possible cause for the error.
*
* @since 5.2.0
*
* @param array $extension {
* The extension that caused the error.
*
* @type string $slug The extension slug. The directory of the plugin or theme.
* @type string $type The extension type. Either 'plugin' or 'theme'.
* }
* @return string Message about which extension caused the error.
*/
private function get_cause( $extension ) {
if ( 'plugin' === $extension['type'] ) {
$plugin = $this->get_plugin( $extension );
if ( false === $plugin ) {
$name = $extension['slug'];
} else {
$name = $plugin['Name'];
}
/* translators: %s: Plugin name. */
$cause = sprintf( __( 'In this case, WordPress caught an error with one of your plugins, %s.' ), $name );
} else {
$theme = wp_get_theme( $extension['slug'] );
$name = $theme->exists() ? $theme->display( 'Name' ) : $extension['slug'];
/* translators: %s: Theme name. */
$cause = sprintf( __( 'In this case, WordPress caught an error with your theme, %s.' ), $name );
}
return $cause;
}
/**
* Return the details for a single plugin based on the extension data from an error.
*
* @since 5.3.0
*
* @param array $extension {
* The extension that caused the error.
*
* @type string $slug The extension slug. The directory of the plugin or theme.
* @type string $type The extension type. Either 'plugin' or 'theme'.
* }
* @return array|false A plugin array {@see get_plugins()} or `false` if no plugin was found.
*/
private function get_plugin( $extension ) {
if ( ! function_exists( 'get_plugins' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$plugins = get_plugins();
// Assume plugin main file name first since it is a common convention.
if ( isset( $plugins[ "{$extension['slug']}/{$extension['slug']}.php" ] ) ) {
return $plugins[ "{$extension['slug']}/{$extension['slug']}.php" ];
} else {
foreach ( $plugins as $file => $plugin_data ) {
if ( 0 === strpos( $file, "{$extension['slug']}/" ) || $file === $extension['slug'] ) {
return $plugin_data;
}
}
}
return false;
}
/**
* Return debug information in an easy to manipulate format.
*
* @since 5.3.0
*
* @param array $extension {
* The extension that caused the error.
*
* @type string $slug The extension slug. The directory of the plugin or theme.
* @type string $type The extension type. Either 'plugin' or 'theme'.
* }
* @return array An associative array of debug information.
*/
private function get_debug( $extension ) {
$theme = wp_get_theme();
$wp_version = get_bloginfo( 'version' );
if ( $extension ) {
$plugin = $this->get_plugin( $extension );
} else {
$plugin = null;
}
$debug = array(
'wp' => sprintf(
/* translators: %s: Current WordPress version number. */
__( 'WordPress version %s' ),
$wp_version
),
'theme' => sprintf(
/* translators: 1: Current active theme name. 2: Current active theme version. */
__( 'Active theme: %1$s (version %2$s)' ),
$theme->get( 'Name' ),
$theme->get( 'Version' )
),
);
if ( null !== $plugin ) {
$debug['plugin'] = sprintf(
/* translators: 1: The failing plugins name. 2: The failing plugins version. */
__( 'Current plugin: %1$s (version %2$s)' ),
$plugin['Name'],
$plugin['Version']
);
}
$debug['php'] = sprintf(
/* translators: %s: The currently used PHP version. */
__( 'PHP version %s' ),
PHP_VERSION
);
return $debug;
}
}
```
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
| programming_docs |
wordpress class WP_Widget_Archives {} class WP\_Widget\_Archives {}
=============================
Core class used to implement the Archives widget.
* [WP\_Widget](wp_widget)
* [\_\_construct](wp_widget_archives/__construct) — Sets up a new Archives widget instance.
* [form](wp_widget_archives/form) — Outputs the settings form for the Archives widget.
* [update](wp_widget_archives/update) — Handles updating settings for the current Archives widget instance.
* [widget](wp_widget_archives/widget) — Outputs the content for the current Archives widget instance.
File: `wp-includes/widgets/class-wp-widget-archives.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-archives.php/)
```
class WP_Widget_Archives extends WP_Widget {
/**
* Sets up a new Archives widget instance.
*
* @since 2.8.0
*/
public function __construct() {
$widget_ops = array(
'classname' => 'widget_archive',
'description' => __( 'A monthly archive of your site’s Posts.' ),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
);
parent::__construct( 'archives', __( 'Archives' ), $widget_ops );
}
/**
* Outputs the content for the current Archives 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 Archives widget instance.
*/
public function widget( $args, $instance ) {
$default_title = __( 'Archives' );
$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';
$dropdown = ! empty( $instance['dropdown'] ) ? '1' : '0';
echo $args['before_widget'];
if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
}
if ( $dropdown ) {
$dropdown_id = "{$this->id_base}-dropdown-{$this->number}";
?>
<label class="screen-reader-text" for="<?php echo esc_attr( $dropdown_id ); ?>"><?php echo $title; ?></label>
<select id="<?php echo esc_attr( $dropdown_id ); ?>" name="archive-dropdown">
<?php
/**
* Filters the arguments for the Archives widget drop-down.
*
* @since 2.8.0
* @since 4.9.0 Added the `$instance` parameter.
*
* @see wp_get_archives()
*
* @param array $args An array of Archives widget drop-down arguments.
* @param array $instance Settings for the current Archives widget instance.
*/
$dropdown_args = apply_filters(
'widget_archives_dropdown_args',
array(
'type' => 'monthly',
'format' => 'option',
'show_post_count' => $count,
),
$instance
);
switch ( $dropdown_args['type'] ) {
case 'yearly':
$label = __( 'Select Year' );
break;
case 'monthly':
$label = __( 'Select Month' );
break;
case 'daily':
$label = __( 'Select Day' );
break;
case 'weekly':
$label = __( 'Select Week' );
break;
default:
$label = __( 'Select Post' );
break;
}
$type_attr = current_theme_supports( 'html5', 'script' ) ? '' : ' type="text/javascript"';
?>
<option value=""><?php echo esc_html( $label ); ?></option>
<?php wp_get_archives( $dropdown_args ); ?>
</select>
<script<?php echo $type_attr; ?>>
/* <![CDATA[ */
(function() {
var dropdown = document.getElementById( "<?php echo esc_js( $dropdown_id ); ?>" );
function onSelectChange() {
if ( dropdown.options[ dropdown.selectedIndex ].value !== '' ) {
document.location.href = this.options[ this.selectedIndex ].value;
}
}
dropdown.onchange = onSelectChange;
})();
/* ]]> */
</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
wp_get_archives(
/**
* Filters the arguments for the Archives widget.
*
* @since 2.8.0
* @since 4.9.0 Added the `$instance` parameter.
*
* @see wp_get_archives()
*
* @param array $args An array of Archives option arguments.
* @param array $instance Array of settings for the current widget.
*/
apply_filters(
'widget_archives_args',
array(
'type' => 'monthly',
'show_post_count' => $count,
),
$instance
)
);
?>
</ul>
<?php
if ( 'html5' === $format ) {
echo '</nav>';
}
}
echo $args['after_widget'];
}
/**
* Handles updating settings for the current Archives widget instance.
*
* @since 2.8.0
*
* @param array $new_instance New settings for this instance as input by the user via
* WP_Widget_Archives::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;
$new_instance = wp_parse_args(
(array) $new_instance,
array(
'title' => '',
'count' => 0,
'dropdown' => '',
)
);
$instance['title'] = sanitize_text_field( $new_instance['title'] );
$instance['count'] = $new_instance['count'] ? 1 : 0;
$instance['dropdown'] = $new_instance['dropdown'] ? 1 : 0;
return $instance;
}
/**
* Outputs the settings form for the Archives widget.
*
* @since 2.8.0
*
* @param array $instance Current settings.
*/
public function form( $instance ) {
$instance = wp_parse_args(
(array) $instance,
array(
'title' => '',
'count' => 0,
'dropdown' => '',
)
);
?>
<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 class="checkbox" type="checkbox"<?php checked( $instance['dropdown'] ); ?> id="<?php echo $this->get_field_id( 'dropdown' ); ?>" name="<?php echo $this->get_field_name( 'dropdown' ); ?>" />
<label for="<?php echo $this->get_field_id( 'dropdown' ); ?>"><?php _e( 'Display as dropdown' ); ?></label>
<br />
<input class="checkbox" type="checkbox"<?php checked( $instance['count'] ); ?> id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>" />
<label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php _e( 'Show post counts' ); ?></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_Automatic_Updater {} class WP\_Automatic\_Updater {}
===============================
Core class used for handling automatic background updates.
* [after\_core\_update](wp_automatic_updater/after_core_update) — If we tried to perform a core update, check if we should send an email, and if we need to avoid processing future updates.
* [after\_plugin\_theme\_update](wp_automatic_updater/after_plugin_theme_update) — If we tried to perform plugin or theme updates, check if we should send an email.
* [is\_disabled](wp_automatic_updater/is_disabled) — Determines whether the entire automatic updater is disabled.
* [is\_vcs\_checkout](wp_automatic_updater/is_vcs_checkout) — Checks for version control checkouts.
* [run](wp_automatic_updater/run) — Kicks off the background update process, looping through all pending updates.
* [send\_core\_update\_notification\_email](wp_automatic_updater/send_core_update_notification_email) — Notifies an administrator of a core update.
* [send\_debug\_email](wp_automatic_updater/send_debug_email) — Prepares and sends an email of a full log of background update results, useful for debugging and geekery.
* [send\_email](wp_automatic_updater/send_email) — Sends an email upon the completion or failure of a background core update.
* [send\_plugin\_theme\_email](wp_automatic_updater/send_plugin_theme_email) — Sends an email upon the completion or failure of a plugin or theme background update.
* [should\_update](wp_automatic_updater/should_update) — Tests to see if we can and should update a specific item.
* [update](wp_automatic_updater/update) — Updates an item, if appropriate.
File: `wp-admin/includes/class-wp-automatic-updater.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-automatic-updater.php/)
```
class WP_Automatic_Updater {
/**
* Tracks update results during processing.
*
* @var array
*/
protected $update_results = array();
/**
* Determines whether the entire automatic updater is disabled.
*
* @since 3.7.0
*/
public function is_disabled() {
// Background updates are disabled if you don't want file changes.
if ( ! wp_is_file_mod_allowed( 'automatic_updater' ) ) {
return true;
}
if ( wp_installing() ) {
return true;
}
// More fine grained control can be done through the WP_AUTO_UPDATE_CORE constant and filters.
$disabled = defined( 'AUTOMATIC_UPDATER_DISABLED' ) && AUTOMATIC_UPDATER_DISABLED;
/**
* Filters whether to entirely disable background updates.
*
* There are more fine-grained filters and controls for selective disabling.
* This filter parallels the AUTOMATIC_UPDATER_DISABLED constant in name.
*
* This also disables update notification emails. That may change in the future.
*
* @since 3.7.0
*
* @param bool $disabled Whether the updater should be disabled.
*/
return apply_filters( 'automatic_updater_disabled', $disabled );
}
/**
* Checks for version control checkouts.
*
* Checks for Subversion, Git, Mercurial, and Bazaar. It recursively looks up the
* filesystem to the top of the drive, erring on the side of detecting a VCS
* checkout somewhere.
*
* ABSPATH is always checked in addition to whatever `$context` is (which may be the
* wp-content directory, for example). The underlying assumption is that if you are
* using version control *anywhere*, then you should be making decisions for
* how things get updated.
*
* @since 3.7.0
*
* @param string $context The filesystem path to check, in addition to ABSPATH.
* @return bool True if a VCS checkout was discovered at `$context` or ABSPATH,
* or anywhere higher. False otherwise.
*/
public function is_vcs_checkout( $context ) {
$context_dirs = array( untrailingslashit( $context ) );
if ( ABSPATH !== $context ) {
$context_dirs[] = untrailingslashit( ABSPATH );
}
$vcs_dirs = array( '.svn', '.git', '.hg', '.bzr' );
$check_dirs = array();
foreach ( $context_dirs as $context_dir ) {
// Walk up from $context_dir to the root.
do {
$check_dirs[] = $context_dir;
// Once we've hit '/' or 'C:\', we need to stop. dirname will keep returning the input here.
if ( dirname( $context_dir ) === $context_dir ) {
break;
}
// Continue one level at a time.
} while ( $context_dir = dirname( $context_dir ) );
}
$check_dirs = array_unique( $check_dirs );
// Search all directories we've found for evidence of version control.
foreach ( $vcs_dirs as $vcs_dir ) {
foreach ( $check_dirs as $check_dir ) {
$checkout = @is_dir( rtrim( $check_dir, '\\/' ) . "/$vcs_dir" );
if ( $checkout ) {
break 2;
}
}
}
/**
* Filters whether the automatic updater should consider a filesystem
* location to be potentially managed by a version control system.
*
* @since 3.7.0
*
* @param bool $checkout Whether a VCS checkout was discovered at `$context`
* or ABSPATH, or anywhere higher.
* @param string $context The filesystem context (a path) against which
* filesystem status should be checked.
*/
return apply_filters( 'automatic_updates_is_vcs_checkout', $checkout, $context );
}
/**
* Tests to see if we can and should update a specific item.
*
* @since 3.7.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $type The type of update being checked: 'core', 'theme',
* 'plugin', 'translation'.
* @param object $item The update offer.
* @param string $context The filesystem context (a path) against which filesystem
* access and status should be checked.
* @return bool True if the item should be updated, false otherwise.
*/
public function should_update( $type, $item, $context ) {
// Used to see if WP_Filesystem is set up to allow unattended updates.
$skin = new Automatic_Upgrader_Skin;
if ( $this->is_disabled() ) {
return false;
}
// Only relax the filesystem checks when the update doesn't include new files.
$allow_relaxed_file_ownership = false;
if ( 'core' === $type && isset( $item->new_files ) && ! $item->new_files ) {
$allow_relaxed_file_ownership = true;
}
// If we can't do an auto core update, we may still be able to email the user.
if ( ! $skin->request_filesystem_credentials( false, $context, $allow_relaxed_file_ownership )
|| $this->is_vcs_checkout( $context )
) {
if ( 'core' === $type ) {
$this->send_core_update_notification_email( $item );
}
return false;
}
// Next up, is this an item we can update?
if ( 'core' === $type ) {
$update = Core_Upgrader::should_update_to_version( $item->current );
} elseif ( 'plugin' === $type || 'theme' === $type ) {
$update = ! empty( $item->autoupdate );
if ( ! $update && wp_is_auto_update_enabled_for_type( $type ) ) {
// Check if the site admin has enabled auto-updates by default for the specific item.
$auto_updates = (array) get_site_option( "auto_update_{$type}s", array() );
$update = in_array( $item->{$type}, $auto_updates, true );
}
} else {
$update = ! empty( $item->autoupdate );
}
// If the `disable_autoupdate` flag is set, override any user-choice, but allow filters.
if ( ! empty( $item->disable_autoupdate ) ) {
$update = $item->disable_autoupdate;
}
/**
* Filters whether to automatically update core, a plugin, a theme, or a language.
*
* The dynamic portion of the hook name, `$type`, refers to the type of update
* being checked.
*
* Possible hook names include:
*
* - `auto_update_core`
* - `auto_update_plugin`
* - `auto_update_theme`
* - `auto_update_translation`
*
* Since WordPress 3.7, minor and development versions of core, and translations have
* been auto-updated by default. New installs on WordPress 5.6 or higher will also
* auto-update major versions by default. Starting in 5.6, older sites can opt-in to
* major version auto-updates, and auto-updates for plugins and themes.
*
* See the {@see 'allow_dev_auto_core_updates'}, {@see 'allow_minor_auto_core_updates'},
* and {@see 'allow_major_auto_core_updates'} filters for a more straightforward way to
* adjust core updates.
*
* @since 3.7.0
* @since 5.5.0 The `$update` parameter accepts the value of null.
*
* @param bool|null $update Whether to update. The value of null is internally used
* to detect whether nothing has hooked into this filter.
* @param object $item The update offer.
*/
$update = apply_filters( "auto_update_{$type}", $update, $item );
if ( ! $update ) {
if ( 'core' === $type ) {
$this->send_core_update_notification_email( $item );
}
return false;
}
// If it's a core update, are we actually compatible with its requirements?
if ( 'core' === $type ) {
global $wpdb;
$php_compat = version_compare( PHP_VERSION, $item->php_version, '>=' );
if ( file_exists( WP_CONTENT_DIR . '/db.php' ) && empty( $wpdb->is_mysql ) ) {
$mysql_compat = true;
} else {
$mysql_compat = version_compare( $wpdb->db_version(), $item->mysql_version, '>=' );
}
if ( ! $php_compat || ! $mysql_compat ) {
return false;
}
}
// If updating a plugin or theme, ensure the minimum PHP version requirements are satisfied.
if ( in_array( $type, array( 'plugin', 'theme' ), true ) ) {
if ( ! empty( $item->requires_php ) && version_compare( PHP_VERSION, $item->requires_php, '<' ) ) {
return false;
}
}
return true;
}
/**
* Notifies an administrator of a core update.
*
* @since 3.7.0
*
* @param object $item The update offer.
* @return bool True if the site administrator is notified of a core update,
* false otherwise.
*/
protected function send_core_update_notification_email( $item ) {
$notified = get_site_option( 'auto_core_update_notified' );
// Don't notify if we've already notified the same email address of the same version.
if ( $notified
&& get_site_option( 'admin_email' ) === $notified['email']
&& $notified['version'] === $item->current
) {
return false;
}
// See if we need to notify users of a core update.
$notify = ! empty( $item->notify_email );
/**
* Filters whether to notify the site administrator of a new core update.
*
* By default, administrators are notified when the update offer received
* from WordPress.org sets a particular flag. This allows some discretion
* in if and when to notify.
*
* This filter is only evaluated once per release. If the same email address
* was already notified of the same new version, WordPress won't repeatedly
* email the administrator.
*
* This filter is also used on about.php to check if a plugin has disabled
* these notifications.
*
* @since 3.7.0
*
* @param bool $notify Whether the site administrator is notified.
* @param object $item The update offer.
*/
if ( ! apply_filters( 'send_core_update_notification_email', $notify, $item ) ) {
return false;
}
$this->send_email( 'manual', $item );
return true;
}
/**
* Updates an item, if appropriate.
*
* @since 3.7.0
*
* @param string $type The type of update being checked: 'core', 'theme', 'plugin', 'translation'.
* @param object $item The update offer.
* @return null|WP_Error
*/
public function update( $type, $item ) {
$skin = new Automatic_Upgrader_Skin;
switch ( $type ) {
case 'core':
// The Core upgrader doesn't use the Upgrader's skin during the actual main part of the upgrade, instead, firing a filter.
add_filter( 'update_feedback', array( $skin, 'feedback' ) );
$upgrader = new Core_Upgrader( $skin );
$context = ABSPATH;
break;
case 'plugin':
$upgrader = new Plugin_Upgrader( $skin );
$context = WP_PLUGIN_DIR; // We don't support custom Plugin directories, or updates for WPMU_PLUGIN_DIR.
break;
case 'theme':
$upgrader = new Theme_Upgrader( $skin );
$context = get_theme_root( $item->theme );
break;
case 'translation':
$upgrader = new Language_Pack_Upgrader( $skin );
$context = WP_CONTENT_DIR; // WP_LANG_DIR;
break;
}
// Determine whether we can and should perform this update.
if ( ! $this->should_update( $type, $item, $context ) ) {
return false;
}
/**
* Fires immediately prior to an auto-update.
*
* @since 4.4.0
*
* @param string $type The type of update being checked: 'core', 'theme', 'plugin', or 'translation'.
* @param object $item The update offer.
* @param string $context The filesystem context (a path) against which filesystem access and status
* should be checked.
*/
do_action( 'pre_auto_update', $type, $item, $context );
$upgrader_item = $item;
switch ( $type ) {
case 'core':
/* translators: %s: WordPress version. */
$skin->feedback( __( 'Updating to WordPress %s' ), $item->version );
/* translators: %s: WordPress version. */
$item_name = sprintf( __( 'WordPress %s' ), $item->version );
break;
case 'theme':
$upgrader_item = $item->theme;
$theme = wp_get_theme( $upgrader_item );
$item_name = $theme->Get( 'Name' );
// Add the current version so that it can be reported in the notification email.
$item->current_version = $theme->get( 'Version' );
if ( empty( $item->current_version ) ) {
$item->current_version = false;
}
/* translators: %s: Theme name. */
$skin->feedback( __( 'Updating theme: %s' ), $item_name );
break;
case 'plugin':
$upgrader_item = $item->plugin;
$plugin_data = get_plugin_data( $context . '/' . $upgrader_item );
$item_name = $plugin_data['Name'];
// Add the current version so that it can be reported in the notification email.
$item->current_version = $plugin_data['Version'];
if ( empty( $item->current_version ) ) {
$item->current_version = false;
}
/* translators: %s: Plugin name. */
$skin->feedback( __( 'Updating plugin: %s' ), $item_name );
break;
case 'translation':
$language_item_name = $upgrader->get_name_for_update( $item );
/* translators: %s: Project name (plugin, theme, or WordPress). */
$item_name = sprintf( __( 'Translations for %s' ), $language_item_name );
/* translators: 1: Project name (plugin, theme, or WordPress), 2: Language. */
$skin->feedback( sprintf( __( 'Updating translations for %1$s (%2$s)…' ), $language_item_name, $item->language ) );
break;
}
$allow_relaxed_file_ownership = false;
if ( 'core' === $type && isset( $item->new_files ) && ! $item->new_files ) {
$allow_relaxed_file_ownership = true;
}
// Boom, this site's about to get a whole new splash of paint!
$upgrade_result = $upgrader->upgrade(
$upgrader_item,
array(
'clear_update_cache' => false,
// Always use partial builds if possible for core updates.
'pre_check_md5' => false,
// Only available for core updates.
'attempt_rollback' => true,
// Allow relaxed file ownership in some scenarios.
'allow_relaxed_file_ownership' => $allow_relaxed_file_ownership,
)
);
// If the filesystem is unavailable, false is returned.
if ( false === $upgrade_result ) {
$upgrade_result = new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) );
}
if ( 'core' === $type ) {
if ( is_wp_error( $upgrade_result )
&& ( 'up_to_date' === $upgrade_result->get_error_code()
|| 'locked' === $upgrade_result->get_error_code() )
) {
// These aren't actual errors, treat it as a skipped-update instead
// to avoid triggering the post-core update failure routines.
return false;
}
// Core doesn't output this, so let's append it, so we don't get confused.
if ( is_wp_error( $upgrade_result ) ) {
$upgrade_result->add( 'installation_failed', __( 'Installation failed.' ) );
$skin->error( $upgrade_result );
} else {
$skin->feedback( __( 'WordPress updated successfully.' ) );
}
}
$this->update_results[ $type ][] = (object) array(
'item' => $item,
'result' => $upgrade_result,
'name' => $item_name,
'messages' => $skin->get_upgrade_messages(),
);
return $upgrade_result;
}
/**
* Kicks off the background update process, looping through all pending updates.
*
* @since 3.7.0
*/
public function run() {
if ( $this->is_disabled() ) {
return;
}
if ( ! is_main_network() || ! is_main_site() ) {
return;
}
if ( ! WP_Upgrader::create_lock( 'auto_updater' ) ) {
return;
}
// Don't automatically run these things, as we'll handle it ourselves.
remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
remove_action( 'upgrader_process_complete', 'wp_version_check' );
remove_action( 'upgrader_process_complete', 'wp_update_plugins' );
remove_action( 'upgrader_process_complete', 'wp_update_themes' );
// Next, plugins.
wp_update_plugins(); // Check for plugin updates.
$plugin_updates = get_site_transient( 'update_plugins' );
if ( $plugin_updates && ! empty( $plugin_updates->response ) ) {
foreach ( $plugin_updates->response as $plugin ) {
$this->update( 'plugin', $plugin );
}
// Force refresh of plugin update information.
wp_clean_plugins_cache();
}
// Next, those themes we all love.
wp_update_themes(); // Check for theme updates.
$theme_updates = get_site_transient( 'update_themes' );
if ( $theme_updates && ! empty( $theme_updates->response ) ) {
foreach ( $theme_updates->response as $theme ) {
$this->update( 'theme', (object) $theme );
}
// Force refresh of theme update information.
wp_clean_themes_cache();
}
// Next, process any core update.
wp_version_check(); // Check for core updates.
$core_update = find_core_auto_update();
if ( $core_update ) {
$this->update( 'core', $core_update );
}
// Clean up, and check for any pending translations.
// (Core_Upgrader checks for core updates.)
$theme_stats = array();
if ( isset( $this->update_results['theme'] ) ) {
foreach ( $this->update_results['theme'] as $upgrade ) {
$theme_stats[ $upgrade->item->theme ] = ( true === $upgrade->result );
}
}
wp_update_themes( $theme_stats ); // Check for theme updates.
$plugin_stats = array();
if ( isset( $this->update_results['plugin'] ) ) {
foreach ( $this->update_results['plugin'] as $upgrade ) {
$plugin_stats[ $upgrade->item->plugin ] = ( true === $upgrade->result );
}
}
wp_update_plugins( $plugin_stats ); // Check for plugin updates.
// Finally, process any new translations.
$language_updates = wp_get_translation_updates();
if ( $language_updates ) {
foreach ( $language_updates as $update ) {
$this->update( 'translation', $update );
}
// Clear existing caches.
wp_clean_update_cache();
wp_version_check(); // Check for core updates.
wp_update_themes(); // Check for theme updates.
wp_update_plugins(); // Check for plugin updates.
}
// Send debugging email to admin for all development installations.
if ( ! empty( $this->update_results ) ) {
$development_version = false !== strpos( get_bloginfo( 'version' ), '-' );
/**
* Filters whether to send a debugging email for each automatic background update.
*
* @since 3.7.0
*
* @param bool $development_version By default, emails are sent if the
* install is a development version.
* Return false to avoid the email.
*/
if ( apply_filters( 'automatic_updates_send_debug_email', $development_version ) ) {
$this->send_debug_email();
}
if ( ! empty( $this->update_results['core'] ) ) {
$this->after_core_update( $this->update_results['core'][0] );
} elseif ( ! empty( $this->update_results['plugin'] ) || ! empty( $this->update_results['theme'] ) ) {
$this->after_plugin_theme_update( $this->update_results );
}
/**
* Fires after all automatic updates have run.
*
* @since 3.8.0
*
* @param array $update_results The results of all attempted updates.
*/
do_action( 'automatic_updates_complete', $this->update_results );
}
WP_Upgrader::release_lock( 'auto_updater' );
}
/**
* If we tried to perform a core update, check if we should send an email,
* and if we need to avoid processing future updates.
*
* @since 3.7.0
*
* @param object $update_result The result of the core update. Includes the update offer and result.
*/
protected function after_core_update( $update_result ) {
$wp_version = get_bloginfo( 'version' );
$core_update = $update_result->item;
$result = $update_result->result;
if ( ! is_wp_error( $result ) ) {
$this->send_email( 'success', $core_update );
return;
}
$error_code = $result->get_error_code();
// Any of these WP_Error codes are critical failures, as in they occurred after we started to copy core files.
// We should not try to perform a background update again until there is a successful one-click update performed by the user.
$critical = false;
if ( 'disk_full' === $error_code || false !== strpos( $error_code, '__copy_dir' ) ) {
$critical = true;
} elseif ( 'rollback_was_required' === $error_code && is_wp_error( $result->get_error_data()->rollback ) ) {
// A rollback is only critical if it failed too.
$critical = true;
$rollback_result = $result->get_error_data()->rollback;
} elseif ( false !== strpos( $error_code, 'do_rollback' ) ) {
$critical = true;
}
if ( $critical ) {
$critical_data = array(
'attempted' => $core_update->current,
'current' => $wp_version,
'error_code' => $error_code,
'error_data' => $result->get_error_data(),
'timestamp' => time(),
'critical' => true,
);
if ( isset( $rollback_result ) ) {
$critical_data['rollback_code'] = $rollback_result->get_error_code();
$critical_data['rollback_data'] = $rollback_result->get_error_data();
}
update_site_option( 'auto_core_update_failed', $critical_data );
$this->send_email( 'critical', $core_update, $result );
return;
}
/*
* Any other WP_Error code (like download_failed or files_not_writable) occurs before
* we tried to copy over core files. Thus, the failures are early and graceful.
*
* We should avoid trying to perform a background update again for the same version.
* But we can try again if another version is released.
*
* For certain 'transient' failures, like download_failed, we should allow retries.
* In fact, let's schedule a special update for an hour from now. (It's possible
* the issue could actually be on WordPress.org's side.) If that one fails, then email.
*/
$send = true;
$transient_failures = array( 'incompatible_archive', 'download_failed', 'insane_distro', 'locked' );
if ( in_array( $error_code, $transient_failures, true ) && ! get_site_option( 'auto_core_update_failed' ) ) {
wp_schedule_single_event( time() + HOUR_IN_SECONDS, 'wp_maybe_auto_update' );
$send = false;
}
$notified = get_site_option( 'auto_core_update_notified' );
// Don't notify if we've already notified the same email address of the same version of the same notification type.
if ( $notified
&& 'fail' === $notified['type']
&& get_site_option( 'admin_email' ) === $notified['email']
&& $notified['version'] === $core_update->current
) {
$send = false;
}
update_site_option(
'auto_core_update_failed',
array(
'attempted' => $core_update->current,
'current' => $wp_version,
'error_code' => $error_code,
'error_data' => $result->get_error_data(),
'timestamp' => time(),
'retry' => in_array( $error_code, $transient_failures, true ),
)
);
if ( $send ) {
$this->send_email( 'fail', $core_update, $result );
}
}
/**
* Sends an email upon the completion or failure of a background core update.
*
* @since 3.7.0
*
* @param string $type The type of email to send. Can be one of 'success', 'fail', 'manual', 'critical'.
* @param object $core_update The update offer that was attempted.
* @param mixed $result Optional. The result for the core update. Can be WP_Error.
*/
protected function send_email( $type, $core_update, $result = null ) {
update_site_option(
'auto_core_update_notified',
array(
'type' => $type,
'email' => get_site_option( 'admin_email' ),
'version' => $core_update->current,
'timestamp' => time(),
)
);
$next_user_core_update = get_preferred_from_update_core();
// If the update transient is empty, use the update we just performed.
if ( ! $next_user_core_update ) {
$next_user_core_update = $core_update;
}
if ( 'upgrade' === $next_user_core_update->response
&& version_compare( $next_user_core_update->version, $core_update->version, '>' )
) {
$newer_version_available = true;
} else {
$newer_version_available = false;
}
/**
* Filters whether to send an email following an automatic background core update.
*
* @since 3.7.0
*
* @param bool $send Whether to send the email. Default true.
* @param string $type The type of email to send. Can be one of
* 'success', 'fail', 'critical'.
* @param object $core_update The update offer that was attempted.
* @param mixed $result The result for the core update. Can be WP_Error.
*/
if ( 'manual' !== $type && ! apply_filters( 'auto_core_update_send_email', true, $type, $core_update, $result ) ) {
return;
}
switch ( $type ) {
case 'success': // We updated.
/* translators: Site updated notification email subject. 1: Site title, 2: WordPress version. */
$subject = __( '[%1$s] Your site has updated to WordPress %2$s' );
break;
case 'fail': // We tried to update but couldn't.
case 'manual': // We can't update (and made no attempt).
/* translators: Update available notification email subject. 1: Site title, 2: WordPress version. */
$subject = __( '[%1$s] WordPress %2$s is available. Please update!' );
break;
case 'critical': // We tried to update, started to copy files, then things went wrong.
/* translators: Site down notification email subject. 1: Site title. */
$subject = __( '[%1$s] URGENT: Your site may be down due to a failed update' );
break;
default:
return;
}
// If the auto-update is not to the latest version, say that the current version of WP is available instead.
$version = 'success' === $type ? $core_update->current : $next_user_core_update->current;
$subject = sprintf( $subject, wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ), $version );
$body = '';
switch ( $type ) {
case 'success':
$body .= sprintf(
/* translators: 1: Home URL, 2: WordPress version. */
__( 'Howdy! Your site at %1$s has been updated automatically to WordPress %2$s.' ),
home_url(),
$core_update->current
);
$body .= "\n\n";
if ( ! $newer_version_available ) {
$body .= __( 'No further action is needed on your part.' ) . ' ';
}
// Can only reference the About screen if their update was successful.
list( $about_version ) = explode( '-', $core_update->current, 2 );
/* translators: %s: WordPress version. */
$body .= sprintf( __( 'For more on version %s, see the About WordPress screen:' ), $about_version );
$body .= "\n" . admin_url( 'about.php' );
if ( $newer_version_available ) {
/* translators: %s: WordPress latest version. */
$body .= "\n\n" . sprintf( __( 'WordPress %s is also now available.' ), $next_user_core_update->current ) . ' ';
$body .= __( 'Updating is easy and only takes a few moments:' );
$body .= "\n" . network_admin_url( 'update-core.php' );
}
break;
case 'fail':
case 'manual':
$body .= sprintf(
/* translators: 1: Home URL, 2: WordPress version. */
__( 'Please update your site at %1$s to WordPress %2$s.' ),
home_url(),
$next_user_core_update->current
);
$body .= "\n\n";
// Don't show this message if there is a newer version available.
// Potential for confusion, and also not useful for them to know at this point.
if ( 'fail' === $type && ! $newer_version_available ) {
$body .= __( 'An attempt was made, but your site could not be updated automatically.' ) . ' ';
}
$body .= __( 'Updating is easy and only takes a few moments:' );
$body .= "\n" . network_admin_url( 'update-core.php' );
break;
case 'critical':
if ( $newer_version_available ) {
$body .= sprintf(
/* translators: 1: Home URL, 2: WordPress version. */
__( 'Your site at %1$s experienced a critical failure while trying to update WordPress to version %2$s.' ),
home_url(),
$core_update->current
);
} else {
$body .= sprintf(
/* translators: 1: Home URL, 2: WordPress latest version. */
__( 'Your site at %1$s experienced a critical failure while trying to update to the latest version of WordPress, %2$s.' ),
home_url(),
$core_update->current
);
}
$body .= "\n\n" . __( "This means your site may be offline or broken. Don't panic; this can be fixed." );
$body .= "\n\n" . __( "Please check out your site now. It's possible that everything is working. If it says you need to update, you should do so:" );
$body .= "\n" . network_admin_url( 'update-core.php' );
break;
}
$critical_support = 'critical' === $type && ! empty( $core_update->support_email );
if ( $critical_support ) {
// Support offer if available.
$body .= "\n\n" . sprintf(
/* translators: %s: Support email address. */
__( 'The WordPress team is willing to help you. Forward this email to %s and the team will work with you to make sure your site is working.' ),
$core_update->support_email
);
} else {
// Add a note about the support forums.
$body .= "\n\n" . __( 'If you experience any issues or need support, the volunteers in the WordPress.org support forums may be able to help.' );
$body .= "\n" . __( 'https://wordpress.org/support/forums/' );
}
// Updates are important!
if ( 'success' !== $type || $newer_version_available ) {
$body .= "\n\n" . __( 'Keeping your site updated is important for security. It also makes the internet a safer place for you and your readers.' );
}
if ( $critical_support ) {
$body .= ' ' . __( "Reach out to WordPress Core developers to ensure you'll never have this problem again." );
}
// If things are successful and we're now on the latest, mention plugins and themes if any are out of date.
if ( 'success' === $type && ! $newer_version_available && ( get_plugin_updates() || get_theme_updates() ) ) {
$body .= "\n\n" . __( 'You also have some plugins or themes with updates available. Update them now:' );
$body .= "\n" . network_admin_url();
}
$body .= "\n\n" . __( 'The WordPress Team' ) . "\n";
if ( 'critical' === $type && is_wp_error( $result ) ) {
$body .= "\n***\n\n";
/* translators: %s: WordPress version. */
$body .= sprintf( __( 'Your site was running version %s.' ), get_bloginfo( 'version' ) );
$body .= ' ' . __( 'Some data that describes the error your site encountered has been put together.' );
$body .= ' ' . __( 'Your hosting company, support forum volunteers, or a friendly developer may be able to use this information to help you:' );
// If we had a rollback and we're still critical, then the rollback failed too.
// Loop through all errors (the main WP_Error, the update result, the rollback result) for code, data, etc.
if ( 'rollback_was_required' === $result->get_error_code() ) {
$errors = array( $result, $result->get_error_data()->update, $result->get_error_data()->rollback );
} else {
$errors = array( $result );
}
foreach ( $errors as $error ) {
if ( ! is_wp_error( $error ) ) {
continue;
}
$error_code = $error->get_error_code();
/* translators: %s: Error code. */
$body .= "\n\n" . sprintf( __( 'Error code: %s' ), $error_code );
if ( 'rollback_was_required' === $error_code ) {
continue;
}
if ( $error->get_error_message() ) {
$body .= "\n" . $error->get_error_message();
}
$error_data = $error->get_error_data();
if ( $error_data ) {
$body .= "\n" . implode( ', ', (array) $error_data );
}
}
$body .= "\n";
}
$to = get_site_option( 'admin_email' );
$headers = '';
$email = compact( 'to', 'subject', 'body', 'headers' );
/**
* Filters the email sent following an automatic background core update.
*
* @since 3.7.0
*
* @param array $email {
* Array of email arguments that will be passed to wp_mail().
*
* @type string $to The email recipient. An array of emails
* can be returned, as handled by wp_mail().
* @type string $subject The email's subject.
* @type string $body The email message body.
* @type string $headers Any email headers, defaults to no headers.
* }
* @param string $type The type of email being sent. Can be one of
* 'success', 'fail', 'manual', 'critical'.
* @param object $core_update The update offer that was attempted.
* @param mixed $result The result for the core update. Can be WP_Error.
*/
$email = apply_filters( 'auto_core_update_email', $email, $type, $core_update, $result );
wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] );
}
/**
* If we tried to perform plugin or theme updates, check if we should send an email.
*
* @since 5.5.0
*
* @param array $update_results The results of update tasks.
*/
protected function after_plugin_theme_update( $update_results ) {
$successful_updates = array();
$failed_updates = array();
if ( ! empty( $update_results['plugin'] ) ) {
/**
* Filters whether to send an email following an automatic background plugin update.
*
* @since 5.5.0
* @since 5.5.1 Added the `$update_results` parameter.
*
* @param bool $enabled True if plugin update notifications are enabled, false otherwise.
* @param array $update_results The results of plugins update tasks.
*/
$notifications_enabled = apply_filters( 'auto_plugin_update_send_email', true, $update_results['plugin'] );
if ( $notifications_enabled ) {
foreach ( $update_results['plugin'] as $update_result ) {
if ( true === $update_result->result ) {
$successful_updates['plugin'][] = $update_result;
} else {
$failed_updates['plugin'][] = $update_result;
}
}
}
}
if ( ! empty( $update_results['theme'] ) ) {
/**
* Filters whether to send an email following an automatic background theme update.
*
* @since 5.5.0
* @since 5.5.1 Added the `$update_results` parameter.
*
* @param bool $enabled True if theme update notifications are enabled, false otherwise.
* @param array $update_results The results of theme update tasks.
*/
$notifications_enabled = apply_filters( 'auto_theme_update_send_email', true, $update_results['theme'] );
if ( $notifications_enabled ) {
foreach ( $update_results['theme'] as $update_result ) {
if ( true === $update_result->result ) {
$successful_updates['theme'][] = $update_result;
} else {
$failed_updates['theme'][] = $update_result;
}
}
}
}
if ( empty( $successful_updates ) && empty( $failed_updates ) ) {
return;
}
if ( empty( $failed_updates ) ) {
$this->send_plugin_theme_email( 'success', $successful_updates, $failed_updates );
} elseif ( empty( $successful_updates ) ) {
$this->send_plugin_theme_email( 'fail', $successful_updates, $failed_updates );
} else {
$this->send_plugin_theme_email( 'mixed', $successful_updates, $failed_updates );
}
}
/**
* Sends an email upon the completion or failure of a plugin or theme background update.
*
* @since 5.5.0
*
* @param string $type The type of email to send. Can be one of 'success', 'fail', 'mixed'.
* @param array $successful_updates A list of updates that succeeded.
* @param array $failed_updates A list of updates that failed.
*/
protected function send_plugin_theme_email( $type, $successful_updates, $failed_updates ) {
// No updates were attempted.
if ( empty( $successful_updates ) && empty( $failed_updates ) ) {
return;
}
$unique_failures = false;
$past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() );
/*
* When only failures have occurred, an email should only be sent if there are unique failures.
* A failure is considered unique if an email has not been sent for an update attempt failure
* to a plugin or theme with the same new_version.
*/
if ( 'fail' === $type ) {
foreach ( $failed_updates as $update_type => $failures ) {
foreach ( $failures as $failed_update ) {
if ( ! isset( $past_failure_emails[ $failed_update->item->{$update_type} ] ) ) {
$unique_failures = true;
continue;
}
// Check that the failure represents a new failure based on the new_version.
if ( version_compare( $past_failure_emails[ $failed_update->item->{$update_type} ], $failed_update->item->new_version, '<' ) ) {
$unique_failures = true;
}
}
}
if ( ! $unique_failures ) {
return;
}
}
$body = array();
$successful_plugins = ( ! empty( $successful_updates['plugin'] ) );
$successful_themes = ( ! empty( $successful_updates['theme'] ) );
$failed_plugins = ( ! empty( $failed_updates['plugin'] ) );
$failed_themes = ( ! empty( $failed_updates['theme'] ) );
switch ( $type ) {
case 'success':
if ( $successful_plugins && $successful_themes ) {
/* translators: %s: Site title. */
$subject = __( '[%s] Some plugins and themes have automatically updated' );
$body[] = sprintf(
/* translators: %s: Home URL. */
__( 'Howdy! Some plugins and themes have automatically updated to their latest versions on your site at %s. No further action is needed on your part.' ),
home_url()
);
} elseif ( $successful_plugins ) {
/* translators: %s: Site title. */
$subject = __( '[%s] Some plugins were automatically updated' );
$body[] = sprintf(
/* translators: %s: Home URL. */
__( 'Howdy! Some plugins have automatically updated to their latest versions on your site at %s. No further action is needed on your part.' ),
home_url()
);
} else {
/* translators: %s: Site title. */
$subject = __( '[%s] Some themes were automatically updated' );
$body[] = sprintf(
/* translators: %s: Home URL. */
__( 'Howdy! Some themes have automatically updated to their latest versions on your site at %s. No further action is needed on your part.' ),
home_url()
);
}
break;
case 'fail':
case 'mixed':
if ( $failed_plugins && $failed_themes ) {
/* translators: %s: Site title. */
$subject = __( '[%s] Some plugins and themes have failed to update' );
$body[] = sprintf(
/* translators: %s: Home URL. */
__( 'Howdy! Plugins and themes failed to update on your site at %s.' ),
home_url()
);
} elseif ( $failed_plugins ) {
/* translators: %s: Site title. */
$subject = __( '[%s] Some plugins have failed to update' );
$body[] = sprintf(
/* translators: %s: Home URL. */
__( 'Howdy! Plugins failed to update on your site at %s.' ),
home_url()
);
} else {
/* translators: %s: Site title. */
$subject = __( '[%s] Some themes have failed to update' );
$body[] = sprintf(
/* translators: %s: Home URL. */
__( 'Howdy! Themes failed to update on your site at %s.' ),
home_url()
);
}
break;
}
if ( in_array( $type, array( 'fail', 'mixed' ), true ) ) {
$body[] = "\n";
$body[] = __( 'Please check your site now. It’s possible that everything is working. If there are updates available, you should update.' );
$body[] = "\n";
// List failed plugin updates.
if ( ! empty( $failed_updates['plugin'] ) ) {
$body[] = __( 'These plugins failed to update:' );
foreach ( $failed_updates['plugin'] as $item ) {
$body_message = '';
$item_url = '';
if ( ! empty( $item->item->url ) ) {
$item_url = ' : ' . esc_url( $item->item->url );
}
if ( $item->item->current_version ) {
$body_message .= sprintf(
/* translators: 1: Plugin name, 2: Current version number, 3: New version number, 4: Plugin URL. */
__( '- %1$s (from version %2$s to %3$s)%4$s' ),
$item->name,
$item->item->current_version,
$item->item->new_version,
$item_url
);
} else {
$body_message .= sprintf(
/* translators: 1: Plugin name, 2: Version number, 3: Plugin URL. */
__( '- %1$s version %2$s%3$s' ),
$item->name,
$item->item->new_version,
$item_url
);
}
$body[] = $body_message;
$past_failure_emails[ $item->item->plugin ] = $item->item->new_version;
}
$body[] = "\n";
}
// List failed theme updates.
if ( ! empty( $failed_updates['theme'] ) ) {
$body[] = __( 'These themes failed to update:' );
foreach ( $failed_updates['theme'] as $item ) {
if ( $item->item->current_version ) {
$body[] = sprintf(
/* translators: 1: Theme name, 2: Current version number, 3: New version number. */
__( '- %1$s (from version %2$s to %3$s)' ),
$item->name,
$item->item->current_version,
$item->item->new_version
);
} else {
$body[] = sprintf(
/* translators: 1: Theme name, 2: Version number. */
__( '- %1$s version %2$s' ),
$item->name,
$item->item->new_version
);
}
$past_failure_emails[ $item->item->theme ] = $item->item->new_version;
}
$body[] = "\n";
}
}
// List successful updates.
if ( in_array( $type, array( 'success', 'mixed' ), true ) ) {
$body[] = "\n";
// List successful plugin updates.
if ( ! empty( $successful_updates['plugin'] ) ) {
$body[] = __( 'These plugins are now up to date:' );
foreach ( $successful_updates['plugin'] as $item ) {
$body_message = '';
$item_url = '';
if ( ! empty( $item->item->url ) ) {
$item_url = ' : ' . esc_url( $item->item->url );
}
if ( $item->item->current_version ) {
$body_message .= sprintf(
/* translators: 1: Plugin name, 2: Current version number, 3: New version number, 4: Plugin URL. */
__( '- %1$s (from version %2$s to %3$s)%4$s' ),
$item->name,
$item->item->current_version,
$item->item->new_version,
$item_url
);
} else {
$body_message .= sprintf(
/* translators: 1: Plugin name, 2: Version number, 3: Plugin URL. */
__( '- %1$s version %2$s%3$s' ),
$item->name,
$item->item->new_version,
$item_url
);
}
$body[] = $body_message;
unset( $past_failure_emails[ $item->item->plugin ] );
}
$body[] = "\n";
}
// List successful theme updates.
if ( ! empty( $successful_updates['theme'] ) ) {
$body[] = __( 'These themes are now up to date:' );
foreach ( $successful_updates['theme'] as $item ) {
if ( $item->item->current_version ) {
$body[] = sprintf(
/* translators: 1: Theme name, 2: Current version number, 3: New version number. */
__( '- %1$s (from version %2$s to %3$s)' ),
$item->name,
$item->item->current_version,
$item->item->new_version
);
} else {
$body[] = sprintf(
/* translators: 1: Theme name, 2: Version number. */
__( '- %1$s version %2$s' ),
$item->name,
$item->item->new_version
);
}
unset( $past_failure_emails[ $item->item->theme ] );
}
$body[] = "\n";
}
}
if ( $failed_plugins ) {
$body[] = sprintf(
/* translators: %s: Plugins screen URL. */
__( 'To manage plugins on your site, visit the Plugins page: %s' ),
admin_url( 'plugins.php' )
);
$body[] = "\n";
}
if ( $failed_themes ) {
$body[] = sprintf(
/* translators: %s: Themes screen URL. */
__( 'To manage themes on your site, visit the Themes page: %s' ),
admin_url( 'themes.php' )
);
$body[] = "\n";
}
// Add a note about the support forums.
$body[] = __( 'If you experience any issues or need support, the volunteers in the WordPress.org support forums may be able to help.' );
$body[] = __( 'https://wordpress.org/support/forums/' );
$body[] = "\n" . __( 'The WordPress Team' );
if ( '' !== get_option( 'blogname' ) ) {
$site_title = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
} else {
$site_title = parse_url( home_url(), PHP_URL_HOST );
}
$body = implode( "\n", $body );
$to = get_site_option( 'admin_email' );
$subject = sprintf( $subject, $site_title );
$headers = '';
$email = compact( 'to', 'subject', 'body', 'headers' );
/**
* Filters the email sent following an automatic background update for plugins and themes.
*
* @since 5.5.0
*
* @param array $email {
* Array of email arguments that will be passed to wp_mail().
*
* @type string $to The email recipient. An array of emails
* can be returned, as handled by wp_mail().
* @type string $subject The email's subject.
* @type string $body The email message body.
* @type string $headers Any email headers, defaults to no headers.
* }
* @param string $type The type of email being sent. Can be one of 'success', 'fail', 'mixed'.
* @param array $successful_updates A list of updates that succeeded.
* @param array $failed_updates A list of updates that failed.
*/
$email = apply_filters( 'auto_plugin_theme_update_email', $email, $type, $successful_updates, $failed_updates );
$result = wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] );
if ( $result ) {
update_option( 'auto_plugin_theme_update_emails', $past_failure_emails );
}
}
/**
* Prepares and sends an email of a full log of background update results, useful for debugging and geekery.
*
* @since 3.7.0
*/
protected function send_debug_email() {
$update_count = 0;
foreach ( $this->update_results as $type => $updates ) {
$update_count += count( $updates );
}
$body = array();
$failures = 0;
/* translators: %s: Network home URL. */
$body[] = sprintf( __( 'WordPress site: %s' ), network_home_url( '/' ) );
// Core.
if ( isset( $this->update_results['core'] ) ) {
$result = $this->update_results['core'][0];
if ( $result->result && ! is_wp_error( $result->result ) ) {
/* translators: %s: WordPress version. */
$body[] = sprintf( __( 'SUCCESS: WordPress was successfully updated to %s' ), $result->name );
} else {
/* translators: %s: WordPress version. */
$body[] = sprintf( __( 'FAILED: WordPress failed to update to %s' ), $result->name );
$failures++;
}
$body[] = '';
}
// Plugins, Themes, Translations.
foreach ( array( 'plugin', 'theme', 'translation' ) as $type ) {
if ( ! isset( $this->update_results[ $type ] ) ) {
continue;
}
$success_items = wp_list_filter( $this->update_results[ $type ], array( 'result' => true ) );
if ( $success_items ) {
$messages = array(
'plugin' => __( 'The following plugins were successfully updated:' ),
'theme' => __( 'The following themes were successfully updated:' ),
'translation' => __( 'The following translations were successfully updated:' ),
);
$body[] = $messages[ $type ];
foreach ( wp_list_pluck( $success_items, 'name' ) as $name ) {
/* translators: %s: Name of plugin / theme / translation. */
$body[] = ' * ' . sprintf( __( 'SUCCESS: %s' ), $name );
}
}
if ( $success_items !== $this->update_results[ $type ] ) {
// Failed updates.
$messages = array(
'plugin' => __( 'The following plugins failed to update:' ),
'theme' => __( 'The following themes failed to update:' ),
'translation' => __( 'The following translations failed to update:' ),
);
$body[] = $messages[ $type ];
foreach ( $this->update_results[ $type ] as $item ) {
if ( ! $item->result || is_wp_error( $item->result ) ) {
/* translators: %s: Name of plugin / theme / translation. */
$body[] = ' * ' . sprintf( __( 'FAILED: %s' ), $item->name );
$failures++;
}
}
}
$body[] = '';
}
if ( '' !== get_bloginfo( 'name' ) ) {
$site_title = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
} else {
$site_title = parse_url( home_url(), PHP_URL_HOST );
}
if ( $failures ) {
$body[] = trim(
__(
"BETA TESTING?
=============
This debugging email is sent when you are using a development version of WordPress.
If you think these failures might be due to a bug in WordPress, could you report it?
* Open a thread in the support forums: https://wordpress.org/support/forum/alphabeta
* Or, if you're comfortable writing a bug report: https://core.trac.wordpress.org/
Thanks! -- The WordPress Team"
)
);
$body[] = '';
/* translators: Background update failed notification email subject. %s: Site title. */
$subject = sprintf( __( '[%s] Background Update Failed' ), $site_title );
} else {
/* translators: Background update finished notification email subject. %s: Site title. */
$subject = sprintf( __( '[%s] Background Update Finished' ), $site_title );
}
$body[] = trim(
__(
'UPDATE LOG
=========='
)
);
$body[] = '';
foreach ( array( 'core', 'plugin', 'theme', 'translation' ) as $type ) {
if ( ! isset( $this->update_results[ $type ] ) ) {
continue;
}
foreach ( $this->update_results[ $type ] as $update ) {
$body[] = $update->name;
$body[] = str_repeat( '-', strlen( $update->name ) );
foreach ( $update->messages as $message ) {
$body[] = ' ' . html_entity_decode( str_replace( '…', '...', $message ) );
}
if ( is_wp_error( $update->result ) ) {
$results = array( 'update' => $update->result );
// If we rolled back, we want to know an error that occurred then too.
if ( 'rollback_was_required' === $update->result->get_error_code() ) {
$results = (array) $update->result->get_error_data();
}
foreach ( $results as $result_type => $result ) {
if ( ! is_wp_error( $result ) ) {
continue;
}
if ( 'rollback' === $result_type ) {
/* translators: 1: Error code, 2: Error message. */
$body[] = ' ' . sprintf( __( 'Rollback Error: [%1$s] %2$s' ), $result->get_error_code(), $result->get_error_message() );
} else {
/* translators: 1: Error code, 2: Error message. */
$body[] = ' ' . sprintf( __( 'Error: [%1$s] %2$s' ), $result->get_error_code(), $result->get_error_message() );
}
if ( $result->get_error_data() ) {
$body[] = ' ' . implode( ', ', (array) $result->get_error_data() );
}
}
}
$body[] = '';
}
}
$email = array(
'to' => get_site_option( 'admin_email' ),
'subject' => $subject,
'body' => implode( "\n", $body ),
'headers' => '',
);
/**
* Filters the debug email that can be sent following an automatic
* background core update.
*
* @since 3.8.0
*
* @param array $email {
* Array of email arguments that will be passed to wp_mail().
*
* @type string $to The email recipient. An array of emails
* can be returned, as handled by wp_mail().
* @type string $subject Email subject.
* @type string $body Email message body.
* @type string $headers Any email headers. Default empty.
* }
* @param int $failures The number of failures encountered while upgrading.
* @param mixed $results The results of all attempted updates.
*/
$email = apply_filters( 'automatic_updates_debug_email', $email, $failures, $this->update_results );
wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] );
}
}
```
| 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. |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
| programming_docs |
wordpress class WP_Widget_Tag_Cloud {} class WP\_Widget\_Tag\_Cloud {}
===============================
Core class used to implement a Tag cloud widget.
* [WP\_Widget](wp_widget)
* [\_\_construct](wp_widget_tag_cloud/__construct) — Sets up a new Tag Cloud widget instance.
* [\_get\_current\_taxonomy](wp_widget_tag_cloud/_get_current_taxonomy) — Retrieves the taxonomy for the current Tag cloud widget instance.
* [form](wp_widget_tag_cloud/form) — Outputs the Tag Cloud widget settings form.
* [update](wp_widget_tag_cloud/update) — Handles updating settings for the current Tag Cloud widget instance.
* [widget](wp_widget_tag_cloud/widget) — Outputs the content for the current Tag Cloud widget instance.
File: `wp-includes/widgets/class-wp-widget-tag-cloud.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-tag-cloud.php/)
```
class WP_Widget_Tag_Cloud extends WP_Widget {
/**
* Sets up a new Tag Cloud widget instance.
*
* @since 2.8.0
*/
public function __construct() {
$widget_ops = array(
'description' => __( 'A cloud of your most used tags.' ),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
);
parent::__construct( 'tag_cloud', __( 'Tag Cloud' ), $widget_ops );
}
/**
* Outputs the content for the current Tag Cloud 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 Tag Cloud widget instance.
*/
public function widget( $args, $instance ) {
$current_taxonomy = $this->_get_current_taxonomy( $instance );
if ( ! empty( $instance['title'] ) ) {
$title = $instance['title'];
} else {
if ( 'post_tag' === $current_taxonomy ) {
$title = __( 'Tags' );
} else {
$tax = get_taxonomy( $current_taxonomy );
$title = $tax->labels->name;
}
}
$default_title = $title;
$show_count = ! empty( $instance['count'] );
$tag_cloud = wp_tag_cloud(
/**
* Filters the taxonomy used in the Tag Cloud widget.
*
* @since 2.8.0
* @since 3.0.0 Added taxonomy drop-down.
* @since 4.9.0 Added the `$instance` parameter.
*
* @see wp_tag_cloud()
*
* @param array $args Args used for the tag cloud widget.
* @param array $instance Array of settings for the current widget.
*/
apply_filters(
'widget_tag_cloud_args',
array(
'taxonomy' => $current_taxonomy,
'echo' => false,
'show_count' => $show_count,
),
$instance
)
);
if ( empty( $tag_cloud ) ) {
return;
}
/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
echo $args['before_widget'];
if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
}
$format = current_theme_supports( 'html5', 'navigation-widgets' ) ? 'html5' : 'xhtml';
/** This filter is documented in wp-includes/widgets/class-wp-nav-menu-widget.php */
$format = apply_filters( 'navigation_widgets_format', $format );
if ( 'html5' === $format ) {
// The title may be filtered: Strip out HTML and make sure the aria-label is never empty.
$title = trim( strip_tags( $title ) );
$aria_label = $title ? $title : $default_title;
echo '<nav aria-label="' . esc_attr( $aria_label ) . '">';
}
echo '<div class="tagcloud">';
echo $tag_cloud;
echo "</div>\n";
if ( 'html5' === $format ) {
echo '</nav>';
}
echo $args['after_widget'];
}
/**
* Handles updating settings for the current Tag Cloud 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 Settings to save or bool false to cancel saving.
*/
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = sanitize_text_field( $new_instance['title'] );
$instance['count'] = ! empty( $new_instance['count'] ) ? 1 : 0;
$instance['taxonomy'] = stripslashes( $new_instance['taxonomy'] );
return $instance;
}
/**
* Outputs the Tag Cloud widget settings form.
*
* @since 2.8.0
*
* @param array $instance Current settings.
*/
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : '';
$count = isset( $instance['count'] ) ? (bool) $instance['count'] : false;
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input type="text" class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php
$taxonomies = get_taxonomies( array( 'show_tagcloud' => true ), 'object' );
$current_taxonomy = $this->_get_current_taxonomy( $instance );
switch ( count( $taxonomies ) ) {
// No tag cloud supporting taxonomies found, display error message.
case 0:
?>
<input type="hidden" id="<?php echo $this->get_field_id( 'taxonomy' ); ?>" name="<?php echo $this->get_field_name( 'taxonomy' ); ?>" value="" />
<p>
<?php _e( 'The tag cloud will not be displayed since there are no taxonomies that support the tag cloud widget.' ); ?>
</p>
<?php
break;
// Just a single tag cloud supporting taxonomy found, no need to display a select.
case 1:
$keys = array_keys( $taxonomies );
$taxonomy = reset( $keys );
?>
<input type="hidden" id="<?php echo $this->get_field_id( 'taxonomy' ); ?>" name="<?php echo $this->get_field_name( 'taxonomy' ); ?>" value="<?php echo esc_attr( $taxonomy ); ?>" />
<?php
break;
// More than one tag cloud supporting taxonomy found, display a select.
default:
?>
<p>
<label for="<?php echo $this->get_field_id( 'taxonomy' ); ?>"><?php _e( 'Taxonomy:' ); ?></label>
<select class="widefat" id="<?php echo $this->get_field_id( 'taxonomy' ); ?>" name="<?php echo $this->get_field_name( 'taxonomy' ); ?>">
<?php foreach ( $taxonomies as $taxonomy => $tax ) : ?>
<option value="<?php echo esc_attr( $taxonomy ); ?>" <?php selected( $taxonomy, $current_taxonomy ); ?>>
<?php echo esc_html( $tax->labels->name ); ?>
</option>
<?php endforeach; ?>
</select>
</p>
<?php
}
if ( count( $taxonomies ) > 0 ) {
?>
<p>
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>" <?php checked( $count, true ); ?> />
<label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php _e( 'Show tag counts' ); ?></label>
</p>
<?php
}
}
/**
* Retrieves the taxonomy for the current Tag cloud widget instance.
*
* @since 4.4.0
*
* @param array $instance Current settings.
* @return string Name of the current taxonomy if set, otherwise 'post_tag'.
*/
public function _get_current_taxonomy( $instance ) {
if ( ! empty( $instance['taxonomy'] ) && taxonomy_exists( $instance['taxonomy'] ) ) {
return $instance['taxonomy'];
}
return 'post_tag';
}
}
```
| 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_Community_Events {} class WP\_Community\_Events {}
==============================
Class [WP\_Community\_Events](wp_community_events).
A client for api.wordpress.org/events.
* [\_\_construct](wp_community_events/__construct) — Constructor for WP\_Community\_Events.
* [cache\_events](wp_community_events/cache_events) — Caches an array of events data from the Events API.
* [coordinates\_match](wp_community_events/coordinates_match) — Test if two pairs of latitude/longitude coordinates match each other.
* [format\_event\_data\_time](wp_community_events/format_event_data_time) — Adds formatted date and time items for each event in an API response. — deprecated
* [get\_cached\_events](wp_community_events/get_cached_events) — Gets cached events.
* [get\_events](wp_community_events/get_events) — Gets data about events near a particular location.
* [get\_events\_transient\_key](wp_community_events/get_events_transient_key) — Generates a transient key based on user location.
* [get\_request\_args](wp_community_events/get_request_args) — Builds an array of args to use in an HTTP request to the w.org Events API.
* [get\_unsafe\_client\_ip](wp_community_events/get_unsafe_client_ip) — Determines the user's actual IP address and attempts to partially anonymize an IP address by converting it to a network ID.
* [maybe\_log\_events\_response](wp_community_events/maybe_log_events_response) — Logs responses to Events API requests. — deprecated
* [trim\_events](wp_community_events/trim_events) — Prepares the event list for presentation.
File: `wp-admin/includes/class-wp-community-events.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-community-events.php/)
```
class WP_Community_Events {
/**
* ID for a WordPress user account.
*
* @since 4.8.0
*
* @var int
*/
protected $user_id = 0;
/**
* Stores location data for the user.
*
* @since 4.8.0
*
* @var false|array
*/
protected $user_location = false;
/**
* Constructor for WP_Community_Events.
*
* @since 4.8.0
*
* @param int $user_id WP user ID.
* @param false|array $user_location {
* Stored location data for the user. false to pass no location.
*
* @type string $description The name of the location
* @type string $latitude The latitude in decimal degrees notation, without the degree
* symbol. e.g.: 47.615200.
* @type string $longitude The longitude in decimal degrees notation, without the degree
* symbol. e.g.: -122.341100.
* @type string $country The ISO 3166-1 alpha-2 country code. e.g.: BR
* }
*/
public function __construct( $user_id, $user_location = false ) {
$this->user_id = absint( $user_id );
$this->user_location = $user_location;
}
/**
* Gets data about events near a particular location.
*
* Cached events will be immediately returned if the `user_location` property
* is set for the current user, and cached events exist for that location.
*
* Otherwise, this method sends a request to the w.org Events API with location
* data. The API will send back a recognized location based on the data, along
* with nearby events.
*
* The browser's request for events is proxied with this method, rather
* than having the browser make the request directly to api.wordpress.org,
* because it allows results to be cached server-side and shared with other
* users and sites in the network. This makes the process more efficient,
* since increasing the number of visits that get cached data means users
* don't have to wait as often; if the user's browser made the request
* directly, it would also need to make a second request to WP in order to
* pass the data for caching. Having WP make the request also introduces
* the opportunity to anonymize the IP before sending it to w.org, which
* mitigates possible privacy concerns.
*
* @since 4.8.0
* @since 5.5.2 Response no longer contains formatted date field. They're added
* in `wp.communityEvents.populateDynamicEventFields()` now.
*
* @param string $location_search Optional. City name to help determine the location.
* e.g., "Seattle". Default empty string.
* @param string $timezone Optional. Timezone to help determine the location.
* Default empty string.
* @return array|WP_Error A WP_Error on failure; an array with location and events on
* success.
*/
public function get_events( $location_search = '', $timezone = '' ) {
$cached_events = $this->get_cached_events();
if ( ! $location_search && $cached_events ) {
return $cached_events;
}
// Include an unmodified $wp_version.
require ABSPATH . WPINC . '/version.php';
$api_url = 'http://api.wordpress.org/events/1.0/';
$request_args = $this->get_request_args( $location_search, $timezone );
$request_args['user-agent'] = 'WordPress/' . $wp_version . '; ' . home_url( '/' );
if ( wp_http_supports( array( 'ssl' ) ) ) {
$api_url = set_url_scheme( $api_url, 'https' );
}
$response = wp_remote_get( $api_url, $request_args );
$response_code = wp_remote_retrieve_response_code( $response );
$response_body = json_decode( wp_remote_retrieve_body( $response ), true );
$response_error = null;
if ( is_wp_error( $response ) ) {
$response_error = $response;
} elseif ( 200 !== $response_code ) {
$response_error = new WP_Error(
'api-error',
/* translators: %d: Numeric HTTP status code, e.g. 400, 403, 500, 504, etc. */
sprintf( __( 'Invalid API response code (%d).' ), $response_code )
);
} elseif ( ! isset( $response_body['location'], $response_body['events'] ) ) {
$response_error = new WP_Error(
'api-invalid-response',
isset( $response_body['error'] ) ? $response_body['error'] : __( 'Unknown API error.' )
);
}
if ( is_wp_error( $response_error ) ) {
return $response_error;
} else {
$expiration = false;
if ( isset( $response_body['ttl'] ) ) {
$expiration = $response_body['ttl'];
unset( $response_body['ttl'] );
}
/*
* The IP in the response is usually the same as the one that was sent
* in the request, but in some cases it is different. In those cases,
* it's important to reset it back to the IP from the request.
*
* For example, if the IP sent in the request is private (e.g., 192.168.1.100),
* then the API will ignore that and use the corresponding public IP instead,
* and the public IP will get returned. If the public IP were saved, though,
* then get_cached_events() would always return `false`, because the transient
* would be generated based on the public IP when saving the cache, but generated
* based on the private IP when retrieving the cache.
*/
if ( ! empty( $response_body['location']['ip'] ) ) {
$response_body['location']['ip'] = $request_args['body']['ip'];
}
/*
* The API doesn't return a description for latitude/longitude requests,
* but the description is already saved in the user location, so that
* one can be used instead.
*/
if ( $this->coordinates_match( $request_args['body'], $response_body['location'] ) && empty( $response_body['location']['description'] ) ) {
$response_body['location']['description'] = $this->user_location['description'];
}
/*
* Store the raw response, because events will expire before the cache does.
* The response will need to be processed every page load.
*/
$this->cache_events( $response_body, $expiration );
$response_body['events'] = $this->trim_events( $response_body['events'] );
return $response_body;
}
}
/**
* Builds an array of args to use in an HTTP request to the w.org Events API.
*
* @since 4.8.0
*
* @param string $search Optional. City search string. Default empty string.
* @param string $timezone Optional. Timezone string. Default empty string.
* @return array The request args.
*/
protected function get_request_args( $search = '', $timezone = '' ) {
$args = array(
'number' => 5, // Get more than three in case some get trimmed out.
'ip' => self::get_unsafe_client_ip(),
);
/*
* Include the minimal set of necessary arguments, in order to increase the
* chances of a cache-hit on the API side.
*/
if ( empty( $search ) && isset( $this->user_location['latitude'], $this->user_location['longitude'] ) ) {
$args['latitude'] = $this->user_location['latitude'];
$args['longitude'] = $this->user_location['longitude'];
} else {
$args['locale'] = get_user_locale( $this->user_id );
if ( $timezone ) {
$args['timezone'] = $timezone;
}
if ( $search ) {
$args['location'] = $search;
}
}
// Wrap the args in an array compatible with the second parameter of `wp_remote_get()`.
return array(
'body' => $args,
);
}
/**
* Determines the user's actual IP address and attempts to partially
* anonymize an IP address by converting it to a network ID.
*
* Geolocating the network ID usually returns a similar location as the
* actual IP, but provides some privacy for the user.
*
* $_SERVER['REMOTE_ADDR'] cannot be used in all cases, such as when the user
* is making their request through a proxy, or when the web server is behind
* a proxy. In those cases, $_SERVER['REMOTE_ADDR'] is set to the proxy address rather
* than the user's actual address.
*
* Modified from https://stackoverflow.com/a/2031935/450127, MIT license.
* Modified from https://github.com/geertw/php-ip-anonymizer, MIT license.
*
* SECURITY WARNING: This function is _NOT_ intended to be used in
* circumstances where the authenticity of the IP address matters. This does
* _NOT_ guarantee that the returned address is valid or accurate, and it can
* be easily spoofed.
*
* @since 4.8.0
*
* @return string|false The anonymized address on success; the given address
* or false on failure.
*/
public static function get_unsafe_client_ip() {
$client_ip = false;
// In order of preference, with the best ones for this purpose first.
$address_headers = array(
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR',
);
foreach ( $address_headers as $header ) {
if ( array_key_exists( $header, $_SERVER ) ) {
/*
* HTTP_X_FORWARDED_FOR can contain a chain of comma-separated
* addresses. The first one is the original client. It can't be
* trusted for authenticity, but we don't need to for this purpose.
*/
$address_chain = explode( ',', $_SERVER[ $header ] );
$client_ip = trim( $address_chain[0] );
break;
}
}
if ( ! $client_ip ) {
return false;
}
$anon_ip = wp_privacy_anonymize_ip( $client_ip, true );
if ( '0.0.0.0' === $anon_ip || '::' === $anon_ip ) {
return false;
}
return $anon_ip;
}
/**
* Test if two pairs of latitude/longitude coordinates match each other.
*
* @since 4.8.0
*
* @param array $a The first pair, with indexes 'latitude' and 'longitude'.
* @param array $b The second pair, with indexes 'latitude' and 'longitude'.
* @return bool True if they match, false if they don't.
*/
protected function coordinates_match( $a, $b ) {
if ( ! isset( $a['latitude'], $a['longitude'], $b['latitude'], $b['longitude'] ) ) {
return false;
}
return $a['latitude'] === $b['latitude'] && $a['longitude'] === $b['longitude'];
}
/**
* Generates a transient key based on user location.
*
* This could be reduced to a one-liner in the calling functions, but it's
* intentionally a separate function because it's called from multiple
* functions, and having it abstracted keeps the logic consistent and DRY,
* which is less prone to errors.
*
* @since 4.8.0
*
* @param array $location Should contain 'latitude' and 'longitude' indexes.
* @return string|false Transient key on success, false on failure.
*/
protected function get_events_transient_key( $location ) {
$key = false;
if ( isset( $location['ip'] ) ) {
$key = 'community-events-' . md5( $location['ip'] );
} elseif ( isset( $location['latitude'], $location['longitude'] ) ) {
$key = 'community-events-' . md5( $location['latitude'] . $location['longitude'] );
}
return $key;
}
/**
* Caches an array of events data from the Events API.
*
* @since 4.8.0
*
* @param array $events Response body from the API request.
* @param int|false $expiration Optional. Amount of time to cache the events. Defaults to false.
* @return bool true if events were cached; false if not.
*/
protected function cache_events( $events, $expiration = false ) {
$set = false;
$transient_key = $this->get_events_transient_key( $events['location'] );
$cache_expiration = $expiration ? absint( $expiration ) : HOUR_IN_SECONDS * 12;
if ( $transient_key ) {
$set = set_site_transient( $transient_key, $events, $cache_expiration );
}
return $set;
}
/**
* Gets cached events.
*
* @since 4.8.0
* @since 5.5.2 Response no longer contains formatted date field. They're added
* in `wp.communityEvents.populateDynamicEventFields()` now.
*
* @return array|false An array containing `location` and `events` items
* on success, false on failure.
*/
public function get_cached_events() {
$transient_key = $this->get_events_transient_key( $this->user_location );
if ( ! $transient_key ) {
return false;
}
$cached_response = get_site_transient( $transient_key );
if ( isset( $cached_response['events'] ) ) {
$cached_response['events'] = $this->trim_events( $cached_response['events'] );
}
return $cached_response;
}
/**
* Adds formatted date and time items for each event in an API response.
*
* This has to be called after the data is pulled from the cache, because
* the cached events are shared by all users. If it was called before storing
* the cache, then all users would see the events in the localized data/time
* of the user who triggered the cache refresh, rather than their own.
*
* @since 4.8.0
* @deprecated 5.6.0 No longer used in core.
*
* @param array $response_body The response which contains the events.
* @return array The response with dates and times formatted.
*/
protected function format_event_data_time( $response_body ) {
_deprecated_function(
__METHOD__,
'5.5.2',
'This is no longer used by core, and only kept for backward compatibility.'
);
if ( isset( $response_body['events'] ) ) {
foreach ( $response_body['events'] as $key => $event ) {
$timestamp = strtotime( $event['date'] );
/*
* The `date_format` option is not used because it's important
* in this context to keep the day of the week in the formatted date,
* so that users can tell at a glance if the event is on a day they
* are available, without having to open the link.
*/
/* translators: Date format for upcoming events on the dashboard. Include the day of the week. See https://www.php.net/manual/datetime.format.php */
$formatted_date = date_i18n( __( 'l, M j, Y' ), $timestamp );
$formatted_time = date_i18n( get_option( 'time_format' ), $timestamp );
if ( isset( $event['end_date'] ) ) {
$end_timestamp = strtotime( $event['end_date'] );
$formatted_end_date = date_i18n( __( 'l, M j, Y' ), $end_timestamp );
if ( 'meetup' !== $event['type'] && $formatted_end_date !== $formatted_date ) {
/* translators: Upcoming events month format. See https://www.php.net/manual/datetime.format.php */
$start_month = date_i18n( _x( 'F', 'upcoming events month format' ), $timestamp );
$end_month = date_i18n( _x( 'F', 'upcoming events month format' ), $end_timestamp );
if ( $start_month === $end_month ) {
$formatted_date = sprintf(
/* translators: Date string for upcoming events. 1: Month, 2: Starting day, 3: Ending day, 4: Year. */
__( '%1$s %2$d–%3$d, %4$d' ),
$start_month,
/* translators: Upcoming events day format. See https://www.php.net/manual/datetime.format.php */
date_i18n( _x( 'j', 'upcoming events day format' ), $timestamp ),
date_i18n( _x( 'j', 'upcoming events day format' ), $end_timestamp ),
/* translators: Upcoming events year format. See https://www.php.net/manual/datetime.format.php */
date_i18n( _x( 'Y', 'upcoming events year format' ), $timestamp )
);
} else {
$formatted_date = sprintf(
/* translators: Date string for upcoming events. 1: Starting month, 2: Starting day, 3: Ending month, 4: Ending day, 5: Year. */
__( '%1$s %2$d – %3$s %4$d, %5$d' ),
$start_month,
date_i18n( _x( 'j', 'upcoming events day format' ), $timestamp ),
$end_month,
date_i18n( _x( 'j', 'upcoming events day format' ), $end_timestamp ),
date_i18n( _x( 'Y', 'upcoming events year format' ), $timestamp )
);
}
$formatted_date = wp_maybe_decline_date( $formatted_date, 'F j, Y' );
}
}
$response_body['events'][ $key ]['formatted_date'] = $formatted_date;
$response_body['events'][ $key ]['formatted_time'] = $formatted_time;
}
}
return $response_body;
}
/**
* Prepares the event list for presentation.
*
* Discards expired events, and makes WordCamps "sticky." Attendees need more
* advanced notice about WordCamps than they do for meetups, so camps should
* appear in the list sooner. If a WordCamp is coming up, the API will "stick"
* it in the response, even if it wouldn't otherwise appear. When that happens,
* the event will be at the end of the list, and will need to be moved into a
* higher position, so that it doesn't get trimmed off.
*
* @since 4.8.0
* @since 4.9.7 Stick a WordCamp to the final list.
* @since 5.5.2 Accepts and returns only the events, rather than an entire HTTP response.
* @since 6.0.0 Decode HTML entities from the event title.
*
* @param array $events The events that will be prepared.
* @return array The response body with events trimmed.
*/
protected function trim_events( array $events ) {
$future_events = array();
foreach ( $events as $event ) {
/*
* The API's `date` and `end_date` fields are in the _event's_ local timezone, but UTC is needed so
* it can be converted to the _user's_ local time.
*/
$end_time = (int) $event['end_unix_timestamp'];
if ( time() < $end_time ) {
// Decode HTML entities from the event title.
$event['title'] = html_entity_decode( $event['title'], ENT_QUOTES, 'UTF-8' );
array_push( $future_events, $event );
}
}
$future_wordcamps = array_filter(
$future_events,
static function( $wordcamp ) {
return 'wordcamp' === $wordcamp['type'];
}
);
$future_wordcamps = array_values( $future_wordcamps ); // Remove gaps in indices.
$trimmed_events = array_slice( $future_events, 0, 3 );
$trimmed_event_types = wp_list_pluck( $trimmed_events, 'type' );
// Make sure the soonest upcoming WordCamp is pinned in the list.
if ( $future_wordcamps && ! in_array( 'wordcamp', $trimmed_event_types, true ) ) {
array_pop( $trimmed_events );
array_push( $trimmed_events, $future_wordcamps[0] );
}
return $trimmed_events;
}
/**
* Logs responses to Events API requests.
*
* @since 4.8.0
* @deprecated 4.9.0 Use a plugin instead. See #41217 for an example.
*
* @param string $message A description of what occurred.
* @param array $details Details that provide more context for the
* log entry.
*/
protected function maybe_log_events_response( $message, $details ) {
_deprecated_function( __METHOD__, '4.9.0' );
if ( ! WP_DEBUG_LOG ) {
return;
}
error_log(
sprintf(
'%s: %s. Details: %s',
__METHOD__,
trim( $message, '.' ),
wp_json_encode( $details )
)
);
}
}
```
| Version | Description |
| --- | --- |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced. |
| programming_docs |
wordpress class Translations {} class Translations {}
=====================
* [add\_entry](translations/add_entry) — Add entry to the PO structure
* [add\_entry\_or\_merge](translations/add_entry_or_merge)
* [get\_header](translations/get_header)
* [get\_plural\_forms\_count](translations/get_plural_forms_count)
* [merge\_originals\_with](translations/merge_originals_with)
* [merge\_with](translations/merge_with) — Merge $other in the current object.
* [select\_plural\_form](translations/select_plural_form) — Given the number of items, returns the 0-based index of the plural form to use
* [set\_header](translations/set_header) — Sets $header PO header to $value
* [set\_headers](translations/set_headers)
* [translate](translations/translate)
* [translate\_entry](translations/translate_entry)
* [translate\_plural](translations/translate_plural)
File: `wp-includes/pomo/translations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/translations.php/)
```
class Translations {
public $entries = array();
public $headers = array();
/**
* Add entry to the PO structure
*
* @param array|Translation_Entry $entry
* @return bool true on success, false if the entry doesn't have a key
*/
public function add_entry( $entry ) {
if ( is_array( $entry ) ) {
$entry = new Translation_Entry( $entry );
}
$key = $entry->key();
if ( false === $key ) {
return false;
}
$this->entries[ $key ] = &$entry;
return true;
}
/**
* @param array|Translation_Entry $entry
* @return bool
*/
public function add_entry_or_merge( $entry ) {
if ( is_array( $entry ) ) {
$entry = new Translation_Entry( $entry );
}
$key = $entry->key();
if ( false === $key ) {
return false;
}
if ( isset( $this->entries[ $key ] ) ) {
$this->entries[ $key ]->merge_with( $entry );
} else {
$this->entries[ $key ] = &$entry;
}
return true;
}
/**
* Sets $header PO header to $value
*
* If the header already exists, it will be overwritten
*
* TODO: this should be out of this class, it is gettext specific
*
* @param string $header header name, without trailing :
* @param string $value header value, without trailing \n
*/
public function set_header( $header, $value ) {
$this->headers[ $header ] = $value;
}
/**
* @param array $headers
*/
public function set_headers( $headers ) {
foreach ( $headers as $header => $value ) {
$this->set_header( $header, $value );
}
}
/**
* @param string $header
*/
public function get_header( $header ) {
return isset( $this->headers[ $header ] ) ? $this->headers[ $header ] : false;
}
/**
* @param Translation_Entry $entry
*/
public function translate_entry( &$entry ) {
$key = $entry->key();
return isset( $this->entries[ $key ] ) ? $this->entries[ $key ] : false;
}
/**
* @param string $singular
* @param string $context
* @return string
*/
public function translate( $singular, $context = null ) {
$entry = new Translation_Entry(
array(
'singular' => $singular,
'context' => $context,
)
);
$translated = $this->translate_entry( $entry );
return ( $translated && ! empty( $translated->translations ) ) ? $translated->translations[0] : $singular;
}
/**
* Given the number of items, returns the 0-based index of the plural form to use
*
* Here, in the base Translations class, the common logic for English is implemented:
* 0 if there is one element, 1 otherwise
*
* This function should be overridden by the subclasses. For example MO/PO can derive the logic
* from their headers.
*
* @param int $count number of items
*/
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 ) {
$entry = new Translation_Entry(
array(
'singular' => $singular,
'plural' => $plural,
'context' => $context,
)
);
$translated = $this->translate_entry( $entry );
$index = $this->select_plural_form( $count );
$total_plural_forms = $this->get_plural_forms_count();
if ( $translated && 0 <= $index && $index < $total_plural_forms &&
is_array( $translated->translations ) &&
isset( $translated->translations[ $index ] ) ) {
return $translated->translations[ $index ];
} else {
return 1 == $count ? $singular : $plural;
}
}
/**
* Merge $other in the current object.
*
* @param Object $other Another Translation object, whose translations will be merged in this one (passed by reference).
*/
public function merge_with( &$other ) {
foreach ( $other->entries as $entry ) {
$this->entries[ $entry->key() ] = $entry;
}
}
/**
* @param object $other
*/
public function merge_originals_with( &$other ) {
foreach ( $other->entries as $entry ) {
if ( ! isset( $this->entries[ $entry->key() ] ) ) {
$this->entries[ $entry->key() ] = $entry;
} else {
$this->entries[ $entry->key() ]->merge_with( $entry );
}
}
}
}
```
| Used By | Description |
| --- | --- |
| [Gettext\_Translations](gettext_translations) wp-includes/pomo/translations.php | |
wordpress class Requests_Exception_HTTP_402 {} class Requests\_Exception\_HTTP\_402 {}
=======================================
Exception for 402 Payment Required responses
File: `wp-includes/Requests/Exception/HTTP/402.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/402.php/)
```
class Requests_Exception_HTTP_402 extends Requests_Exception_HTTP {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 402;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Payment Required';
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response |
wordpress class WP_Upgrader_Skin {} class WP\_Upgrader\_Skin {}
===========================
Generic Skin for the WordPress Upgrader classes. This skin is designed to be extended for specific purposes.
* [\_\_construct](wp_upgrader_skin/__construct) — Constructor.
* [add\_strings](wp_upgrader_skin/add_strings)
* [after](wp_upgrader_skin/after) — Action to perform following an update.
* [before](wp_upgrader_skin/before) — Action to perform before an update.
* [bulk\_footer](wp_upgrader_skin/bulk_footer)
* [bulk\_header](wp_upgrader_skin/bulk_header)
* [decrement\_update\_count](wp_upgrader_skin/decrement_update_count) — Output JavaScript that calls function to decrement the update counts.
* [error](wp_upgrader_skin/error)
* [feedback](wp_upgrader_skin/feedback)
* [footer](wp_upgrader_skin/footer)
* [header](wp_upgrader_skin/header)
* [hide\_process\_failed](wp_upgrader_skin/hide_process_failed) — Hides the `process\_failed` error message when updating by uploading a zip file.
* [request\_filesystem\_credentials](wp_upgrader_skin/request_filesystem_credentials) — Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem.
* [set\_result](wp_upgrader_skin/set_result) — Sets the result of an upgrade.
* [set\_upgrader](wp_upgrader_skin/set_upgrader)
File: `wp-admin/includes/class-wp-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-upgrader-skin.php/)
```
class WP_Upgrader_Skin {
/**
* Holds the upgrader data.
*
* @since 2.8.0
*
* @var WP_Upgrader
*/
public $upgrader;
/**
* Whether header is done.
*
* @since 2.8.0
*
* @var bool
*/
public $done_header = false;
/**
* Whether footer is done.
*
* @since 2.8.0
*
* @var bool
*/
public $done_footer = false;
/**
* Holds the result of an upgrade.
*
* @since 2.8.0
*
* @var string|bool|WP_Error
*/
public $result = false;
/**
* Holds the options of an upgrade.
*
* @since 2.8.0
*
* @var array
*/
public $options = array();
/**
* Constructor.
*
* Sets up the generic skin for the WordPress Upgrader classes.
*
* @since 2.8.0
*
* @param array $args Optional. The WordPress upgrader skin arguments to
* override default options. Default empty array.
*/
public function __construct( $args = array() ) {
$defaults = array(
'url' => '',
'nonce' => '',
'title' => '',
'context' => false,
);
$this->options = wp_parse_args( $args, $defaults );
}
/**
* @since 2.8.0
*
* @param WP_Upgrader $upgrader
*/
public function set_upgrader( &$upgrader ) {
if ( is_object( $upgrader ) ) {
$this->upgrader =& $upgrader;
}
$this->add_strings();
}
/**
* @since 3.0.0
*/
public function add_strings() {
}
/**
* Sets the result of an upgrade.
*
* @since 2.8.0
*
* @param string|bool|WP_Error $result The result of an upgrade.
*/
public function set_result( $result ) {
$this->result = $result;
}
/**
* Displays a form to the user to request for their FTP/SSH details in order
* to connect to the filesystem.
*
* @since 2.8.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 ) {
$url = $this->options['url'];
if ( ! $context ) {
$context = $this->options['context'];
}
if ( ! empty( $this->options['nonce'] ) ) {
$url = wp_nonce_url( $url, $this->options['nonce'] );
}
$extra_fields = array();
return request_filesystem_credentials( $url, '', $error, $context, $extra_fields, $allow_relaxed_file_ownership );
}
/**
* @since 2.8.0
*/
public function header() {
if ( $this->done_header ) {
return;
}
$this->done_header = true;
echo '<div class="wrap">';
echo '<h1>' . $this->options['title'] . '</h1>';
}
/**
* @since 2.8.0
*/
public function footer() {
if ( $this->done_footer ) {
return;
}
$this->done_footer = true;
echo '</div>';
}
/**
* @since 2.8.0
*
* @param string|WP_Error $errors Errors.
*/
public function error( $errors ) {
if ( ! $this->done_header ) {
$this->header();
}
if ( is_string( $errors ) ) {
$this->feedback( $errors );
} elseif ( is_wp_error( $errors ) && $errors->has_errors() ) {
foreach ( $errors->get_error_messages() as $message ) {
if ( $errors->get_error_data() && is_string( $errors->get_error_data() ) ) {
$this->feedback( $message . ' ' . esc_html( strip_tags( $errors->get_error_data() ) ) );
} else {
$this->feedback( $message );
}
}
}
}
/**
* @since 2.8.0
* @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;
}
show_message( $feedback );
}
/**
* Action to perform before an update.
*
* @since 2.8.0
*/
public function before() {}
/**
* Action to perform following an update.
*
* @since 2.8.0
*/
public function after() {}
/**
* Output JavaScript that calls function to decrement the update counts.
*
* @since 3.9.0
*
* @param string $type Type of update count to decrement. Likely values include 'plugin',
* 'theme', 'translation', etc.
*/
protected function decrement_update_count( $type ) {
if ( ! $this->result || is_wp_error( $this->result ) || 'up_to_date' === $this->result ) {
return;
}
if ( defined( 'IFRAME_REQUEST' ) ) {
echo '<script type="text/javascript">
if ( window.postMessage && JSON ) {
window.parent.postMessage( JSON.stringify( { action: "decrementUpdateCount", upgradeType: "' . $type . '" } ), window.location.protocol + "//" + window.location.hostname );
}
</script>';
} else {
echo '<script type="text/javascript">
(function( wp ) {
if ( wp && wp.updates && wp.updates.decrementCount ) {
wp.updates.decrementCount( "' . $type . '" );
}
})( window.wp );
</script>';
}
}
/**
* @since 3.0.0
*/
public function bulk_header() {}
/**
* @since 3.0.0
*/
public function bulk_footer() {}
/**
* Hides the `process_failed` error message when updating 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 ) {
return false;
}
}
```
| Used By | Description |
| --- | --- |
| [Theme\_Upgrader\_Skin](theme_upgrader_skin) wp-admin/includes/class-theme-upgrader-skin.php | Theme Upgrader Skin for WordPress Theme Upgrades. |
| [Language\_Pack\_Upgrader\_Skin](language_pack_upgrader_skin) wp-admin/includes/class-language-pack-upgrader-skin.php | Translation Upgrader Skin for WordPress Translation Upgrades. |
| [Automatic\_Upgrader\_Skin](automatic_upgrader_skin) wp-admin/includes/class-automatic-upgrader-skin.php | Upgrader Skin for Automatic WordPress Upgrades. |
| [Plugin\_Installer\_Skin](plugin_installer_skin) wp-admin/includes/class-plugin-installer-skin.php | Plugin Installer Skin for WordPress Plugin Installer. |
| [Theme\_Installer\_Skin](theme_installer_skin) wp-admin/includes/class-theme-installer-skin.php | Theme Installer Skin for the WordPress Theme Installer. |
| [Plugin\_Upgrader\_Skin](plugin_upgrader_skin) wp-admin/includes/class-plugin-upgrader-skin.php | Plugin Upgrader Skin for WordPress Plugin Upgrades. |
| [Bulk\_Upgrader\_Skin](bulk_upgrader_skin) wp-admin/includes/class-bulk-upgrader-skin.php | Generic Bulk Upgrader Skin for 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. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress class WP_REST_Blocks_Controller {} class WP\_REST\_Blocks\_Controller {}
=====================================
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\_Posts\_Controller](wp_rest_posts_controller)
* [WP\_REST\_Controller](wp_rest_controller)
* [check\_read\_permission](wp_rest_blocks_controller/check_read_permission) — Checks if a block can be read.
* [filter\_response\_by\_context](wp_rest_blocks_controller/filter_response_by_context) — Filters a response based on the context defined in the schema.
* [get\_item\_schema](wp_rest_blocks_controller/get_item_schema) — Retrieves the block's schema, conforming to JSON Schema.
File: `wp-includes/rest-api/endpoints/class-wp-rest-blocks-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-blocks-controller.php/)
```
class WP_REST_Blocks_Controller extends WP_REST_Posts_Controller {
/**
* Checks if a block can be read.
*
* @since 5.0.0
*
* @param WP_Post $post Post object that backs the block.
* @return bool Whether the block can be read.
*/
public function check_read_permission( $post ) {
// By default the read_post capability is mapped to edit_posts.
if ( ! current_user_can( 'read_post', $post->ID ) ) {
return false;
}
return parent::check_read_permission( $post );
}
/**
* Filters a response based on the context defined in the schema.
*
* @since 5.0.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 ) {
$data = parent::filter_response_by_context( $data, $context );
/*
* Remove `title.rendered` and `content.rendered` from the response. It
* doesn't make sense for a reusable block to have rendered content on its
* own, since rendering a block requires it to be inside a post or a page.
*/
unset( $data['title']['rendered'] );
unset( $data['content']['rendered'] );
return $data;
}
/**
* Retrieves the block's schema, conforming to JSON Schema.
*
* @since 5.0.0
*
* @return array Item schema data.
*/
public function get_item_schema() {
// Do not cache this schema because all properties are derived from parent controller.
$schema = parent::get_item_schema();
/*
* Allow all contexts to access `title.raw` and `content.raw`. Clients always
* need the raw markup of a reusable block to do anything useful, e.g. parse
* it or display it in an editor.
*/
$schema['properties']['title']['properties']['raw']['context'] = array( 'view', 'edit' );
$schema['properties']['content']['properties']['raw']['context'] = array( 'view', 'edit' );
/*
* Remove `title.rendered` and `content.rendered` from the schema. It doesn’t
* make sense for a reusable block to have rendered content on its own, since
* rendering a block requires it to be inside a post or a page.
*/
unset( $schema['properties']['title']['properties']['rendered'] );
unset( $schema['properties']['content']['properties']['rendered'] );
return $schema;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller](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 |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress class WP_Metadata_Lazyloader {} class WP\_Metadata\_Lazyloader {}
=================================
Core class used for lazy-loading object metadata.
When loading many objects of a given type, such as posts in a [WP\_Query](wp_query) loop, it often makes sense to prime various metadata caches at the beginning of the loop. This means fetching all relevant metadata with a single database query, a technique that has the potential to improve performance dramatically in some cases.
In cases where the given metadata may not even be used in the loop, we can improve performance even more by only priming the metadata cache for affected items the first time a piece of metadata is requested – ie, by lazy-loading it. So, for example, comment meta may not be loaded into the cache in the comments section of a post until the first time [get\_comment\_meta()](../functions/get_comment_meta) is called in the context of the comment loop.
WP uses the [WP\_Metadata\_Lazyloader](wp_metadata_lazyloader) class to queue objects for metadata cache priming. The class then detects the relevant get\_\*\_meta() function call, and queries the metadata of all queued objects.
Do not access this class directly. Use the [wp\_metadata\_lazyloader()](../functions/wp_metadata_lazyloader) function.
* [\_\_construct](wp_metadata_lazyloader/__construct) — Constructor.
* [lazyload\_comment\_meta](wp_metadata_lazyloader/lazyload_comment_meta) — Lazy-loads comment meta for queued comments.
* [lazyload\_term\_meta](wp_metadata_lazyloader/lazyload_term_meta) — Lazy-loads term meta for queued terms.
* [queue\_objects](wp_metadata_lazyloader/queue_objects) — Adds objects to the metadata lazy-load queue.
* [reset\_queue](wp_metadata_lazyloader/reset_queue) — Resets lazy-load queue for a given object type.
File: `wp-includes/class-wp-metadata-lazyloader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-metadata-lazyloader.php/)
```
class WP_Metadata_Lazyloader {
/**
* Pending objects queue.
*
* @since 4.5.0
* @var array
*/
protected $pending_objects;
/**
* Settings for supported object types.
*
* @since 4.5.0
* @var array
*/
protected $settings = array();
/**
* Constructor.
*
* @since 4.5.0
*/
public function __construct() {
$this->settings = array(
'term' => array(
'filter' => 'get_term_metadata',
'callback' => array( $this, 'lazyload_term_meta' ),
),
'comment' => array(
'filter' => 'get_comment_metadata',
'callback' => array( $this, 'lazyload_comment_meta' ),
),
);
}
/**
* Adds objects to the metadata lazy-load queue.
*
* @since 4.5.0
*
* @param string $object_type Type of object whose meta is to be lazy-loaded. Accepts 'term' or 'comment'.
* @param array $object_ids Array of object IDs.
* @return void|WP_Error WP_Error on failure.
*/
public function queue_objects( $object_type, $object_ids ) {
if ( ! isset( $this->settings[ $object_type ] ) ) {
return new WP_Error( 'invalid_object_type', __( 'Invalid object type.' ) );
}
$type_settings = $this->settings[ $object_type ];
if ( ! isset( $this->pending_objects[ $object_type ] ) ) {
$this->pending_objects[ $object_type ] = array();
}
foreach ( $object_ids as $object_id ) {
// Keyed by ID for faster lookup.
if ( ! isset( $this->pending_objects[ $object_type ][ $object_id ] ) ) {
$this->pending_objects[ $object_type ][ $object_id ] = 1;
}
}
add_filter( $type_settings['filter'], $type_settings['callback'] );
/**
* Fires after objects are added to the metadata lazy-load queue.
*
* @since 4.5.0
*
* @param array $object_ids Array of object IDs.
* @param string $object_type Type of object being queued.
* @param WP_Metadata_Lazyloader $lazyloader The lazy-loader object.
*/
do_action( 'metadata_lazyloader_queued_objects', $object_ids, $object_type, $this );
}
/**
* Resets lazy-load queue for a given object type.
*
* @since 4.5.0
*
* @param string $object_type Object type. Accepts 'comment' or 'term'.
* @return void|WP_Error WP_Error on failure.
*/
public function reset_queue( $object_type ) {
if ( ! isset( $this->settings[ $object_type ] ) ) {
return new WP_Error( 'invalid_object_type', __( 'Invalid object type.' ) );
}
$type_settings = $this->settings[ $object_type ];
$this->pending_objects[ $object_type ] = array();
remove_filter( $type_settings['filter'], $type_settings['callback'] );
}
/**
* Lazy-loads term meta for queued terms.
*
* This method is public so that it can be used as a filter callback. As a rule, there
* is no need to invoke it directly.
*
* @since 4.5.0
*
* @param mixed $check The `$check` param passed from the 'get_term_metadata' hook.
* @return mixed In order not to short-circuit `get_metadata()`. Generally, this is `null`, but it could be
* another value if filtered by a plugin.
*/
public function lazyload_term_meta( $check ) {
if ( ! empty( $this->pending_objects['term'] ) ) {
update_termmeta_cache( array_keys( $this->pending_objects['term'] ) );
// No need to run again for this set of terms.
$this->reset_queue( 'term' );
}
return $check;
}
/**
* Lazy-loads comment meta for queued comments.
*
* This method is public so that it can be used as a filter callback. As a rule, there is no need to invoke it
* directly, from either inside or outside the `WP_Query` object.
*
* @since 4.5.0
*
* @param mixed $check The `$check` param passed from the {@see 'get_comment_metadata'} hook.
* @return mixed The original value of `$check`, so as not to short-circuit `get_comment_metadata()`.
*/
public function lazyload_comment_meta( $check ) {
if ( ! empty( $this->pending_objects['comment'] ) ) {
update_meta_cache( 'comment', array_keys( $this->pending_objects['comment'] ) );
// No need to run again for this set of comments.
$this->reset_queue( 'comment' );
}
return $check;
}
}
```
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
| programming_docs |
wordpress class WP_Customize_Section {} class WP\_Customize\_Section {}
===============================
Customize Section class.
A UI container for controls, managed by the [WP\_Customize\_Manager](wp_customize_manager) class.
* [WP\_Customize\_Manager](wp_customize_manager)
* [\_\_construct](wp_customize_section/__construct) — Constructor.
* [active](wp_customize_section/active) — Check whether section is active to current Customizer preview.
* [active\_callback](wp_customize_section/active_callback) — Default callback used when invoking WP\_Customize\_Section::active().
* [check\_capabilities](wp_customize_section/check_capabilities) — Checks required user capabilities and whether the theme has the feature support required by the section.
* [get\_content](wp_customize_section/get_content) — Get the section's content for insertion into the Customizer pane.
* [json](wp_customize_section/json) — Gather the parameters passed to client JavaScript via JSON.
* [maybe\_render](wp_customize_section/maybe_render) — Check capabilities and render the section.
* [print\_template](wp_customize_section/print_template) — Render the section's JS template.
* [render](wp_customize_section/render) — Render the section UI in a subclass.
* [render\_template](wp_customize_section/render_template) — An Underscore (JS) template for rendering this section.
File: `wp-includes/class-wp-customize-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-section.php/)
```
class WP_Customize_Section {
/**
* 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;
/**
* WP_Customize_Manager instance.
*
* @since 3.4.0
* @var WP_Customize_Manager
*/
public $manager;
/**
* Unique identifier.
*
* @since 3.4.0
* @var string
*/
public $id;
/**
* Priority of the section which informs load order of sections.
*
* @since 3.4.0
* @var int
*/
public $priority = 160;
/**
* Panel in which to show the section, making it a sub-section.
*
* @since 4.0.0
* @var string
*/
public $panel = '';
/**
* Capability required for the section.
*
* @since 3.4.0
* @var string
*/
public $capability = 'edit_theme_options';
/**
* Theme features required to support the section.
*
* @since 3.4.0
* @var string|string[]
*/
public $theme_supports = '';
/**
* Title of the section to show in UI.
*
* @since 3.4.0
* @var string
*/
public $title = '';
/**
* Description to show in the UI.
*
* @since 3.4.0
* @var string
*/
public $description = '';
/**
* Customizer controls for this section.
*
* @since 3.4.0
* @var array
*/
public $controls;
/**
* Type of this section.
*
* @since 4.1.0
* @var string
*/
public $type = 'default';
/**
* Active callback.
*
* @since 4.1.0
*
* @see WP_Customize_Section::active()
*
* @var callable Callback is called with one argument, the instance of
* WP_Customize_Section, and returns bool to indicate whether
* the section is active (such as it relates to the URL currently
* being previewed).
*/
public $active_callback = '';
/**
* Show the description or hide it behind the help icon.
*
* @since 4.7.0
*
* @var bool Indicates whether the Section's description should be
* hidden behind a help icon ("?") in the Section header,
* similar to how help icons are displayed on Panels.
*/
public $description_hidden = 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 section.
* @param array $args {
* Optional. Array of properties for the new Section object. Default empty array.
*
* @type int $priority Priority of the section, defining the display order
* of panels and sections. Default 160.
* @type string $panel The panel this section belongs to (if any).
* Default empty.
* @type string $capability Capability required for the section.
* Default 'edit_theme_options'
* @type string|string[] $theme_supports Theme features required to support the section.
* @type string $title Title of the section to show in UI.
* @type string $description Description to show in the UI.
* @type string $type Type of the section.
* @type callable $active_callback Active callback.
* @type bool $description_hidden Hide the description behind a help icon,
* instead of inline above the first control.
* Default false.
* }
*/
public function __construct( $manager, $id, $args = array() ) {
$keys = array_keys( get_object_vars( $this ) );
foreach ( $keys as $key ) {
if ( isset( $args[ $key ] ) ) {
$this->$key = $args[ $key ];
}
}
$this->manager = $manager;
$this->id = $id;
if ( empty( $this->active_callback ) ) {
$this->active_callback = array( $this, 'active_callback' );
}
self::$instance_count += 1;
$this->instance_number = self::$instance_count;
$this->controls = array(); // Users cannot customize the $controls array.
}
/**
* Check whether section is active to current Customizer preview.
*
* @since 4.1.0
*
* @return bool Whether the section is active to the current preview.
*/
final public function active() {
$section = $this;
$active = call_user_func( $this->active_callback, $this );
/**
* Filters response of WP_Customize_Section::active().
*
* @since 4.1.0
*
* @param bool $active Whether the Customizer section is active.
* @param WP_Customize_Section $section WP_Customize_Section instance.
*/
$active = apply_filters( 'customize_section_active', $active, $section );
return $active;
}
/**
* Default callback used when invoking WP_Customize_Section::active().
*
* Subclasses can override this with their specific logic, or they may provide
* an 'active_callback' argument to the constructor.
*
* @since 4.1.0
*
* @return true Always true.
*/
public function active_callback() {
return true;
}
/**
* Gather the parameters passed to client JavaScript via JSON.
*
* @since 4.1.0
*
* @return array The array to be exported to the client as JSON.
*/
public function json() {
$array = wp_array_slice_assoc( (array) $this, array( 'id', 'description', 'priority', 'panel', 'type', 'description_hidden' ) );
$array['title'] = html_entity_decode( $this->title, ENT_QUOTES, get_bloginfo( 'charset' ) );
$array['content'] = $this->get_content();
$array['active'] = $this->active();
$array['instanceNumber'] = $this->instance_number;
if ( $this->panel ) {
/* translators: ▸ is the unicode right-pointing triangle. %s: Section title in the Customizer. */
$array['customizeAction'] = sprintf( __( 'Customizing ▸ %s' ), esc_html( $this->manager->get_panel( $this->panel )->title ) );
} else {
$array['customizeAction'] = __( 'Customizing' );
}
return $array;
}
/**
* Checks required user capabilities and whether the theme has the
* feature support required by the section.
*
* @since 3.4.0
*
* @return bool False if theme doesn't support the section or user doesn't have the capability.
*/
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;
}
/**
* Get the section's content for insertion into the Customizer pane.
*
* @since 4.1.0
*
* @return string Contents of the section.
*/
final public function get_content() {
ob_start();
$this->maybe_render();
return trim( ob_get_clean() );
}
/**
* Check capabilities and render the section.
*
* @since 3.4.0
*/
final public function maybe_render() {
if ( ! $this->check_capabilities() ) {
return;
}
/**
* Fires before rendering a Customizer section.
*
* @since 3.4.0
*
* @param WP_Customize_Section $section WP_Customize_Section instance.
*/
do_action( 'customize_render_section', $this );
/**
* Fires before rendering a specific Customizer section.
*
* The dynamic portion of the hook name, `$this->id`, refers to the ID
* of the specific Customizer section to be rendered.
*
* @since 3.4.0
*/
do_action( "customize_render_section_{$this->id}" );
$this->render();
}
/**
* Render the section UI in a subclass.
*
* Sections are now rendered in JS by default, see WP_Customize_Section::print_template().
*
* @since 3.4.0
*/
protected function render() {}
/**
* Render the section's JS template.
*
* This function is only run for section types that have been registered with
* WP_Customize_Manager::register_section_type().
*
* @since 4.3.0
*
* @see WP_Customize_Manager::render_template()
*/
public function print_template() {
?>
<script type="text/html" id="tmpl-customize-section-<?php echo $this->type; ?>">
<?php $this->render_template(); ?>
</script>
<?php
}
/**
* An Underscore (JS) template for rendering this section.
*
* Class variables for this section class are available in the `data` JS object;
* export custom variables by overriding WP_Customize_Section::json().
*
* @since 4.3.0
*
* @see WP_Customize_Section::print_template()
*/
protected function render_template() {
?>
<li id="accordion-section-{{ data.id }}" class="accordion-section control-section control-section-{{ data.type }}">
<h3 class="accordion-section-title" tabindex="0">
{{ data.title }}
<span class="screen-reader-text"><?php _e( 'Press return or enter to open this section' ); ?></span>
</h3>
<ul class="accordion-section-content">
<li class="customize-section-description-container section-meta <# if ( data.description_hidden ) { #>customize-info<# } #>">
<div class="customize-section-title">
<button class="customize-section-back" tabindex="-1">
<span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
</button>
<h3>
<span class="customize-action">
{{{ data.customizeAction }}}
</span>
{{ data.title }}
</h3>
<# if ( data.description && data.description_hidden ) { #>
<button type="button" class="customize-help-toggle dashicons dashicons-editor-help" aria-expanded="false"><span class="screen-reader-text"><?php _e( 'Help' ); ?></span></button>
<div class="description customize-section-description">
{{{ data.description }}}
</div>
<# } #>
<div class="customize-control-notifications-container"></div>
</div>
<# if ( data.description && ! data.description_hidden ) { #>
<div class="description customize-section-description">
{{{ data.description }}}
</div>
<# } #>
</li>
</ul>
</li>
<?php
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Section](wp_customize_nav_menu_section) wp-includes/customize/class-wp-customize-nav-menu-section.php | Customize Menu Section Class |
| [WP\_Customize\_New\_Menu\_Section](wp_customize_new_menu_section) wp-includes/customize/class-wp-customize-new-menu-section.php | Customize Menu Section Class |
| [WP\_Customize\_Themes\_Section](wp_customize_themes_section) wp-includes/customize/class-wp-customize-themes-section.php | Customize Themes Section class. |
| [WP\_Customize\_Sidebar\_Section](wp_customize_sidebar_section) wp-includes/customize/class-wp-customize-sidebar-section.php | Customizer section representing widget area (sidebar). |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress class WP_MS_Themes_List_Table {} class WP\_MS\_Themes\_List\_Table {}
====================================
Core class used to implement displaying themes in a list table for the network admin.
* [WP\_List\_Table](wp_list_table)
* [\_\_construct](wp_ms_themes_list_table/__construct) — Constructor.
* [\_order\_callback](wp_ms_themes_list_table/_order_callback)
* [\_search\_callback](wp_ms_themes_list_table/_search_callback)
* [ajax\_user\_can](wp_ms_themes_list_table/ajax_user_can)
* [column\_autoupdates](wp_ms_themes_list_table/column_autoupdates) — Handles the auto-updates column output.
* [column\_cb](wp_ms_themes_list_table/column_cb) — Handles the checkbox column output.
* [column\_default](wp_ms_themes_list_table/column_default) — Handles default column output.
* [column\_description](wp_ms_themes_list_table/column_description) — Handles the description column output.
* [column\_name](wp_ms_themes_list_table/column_name) — Handles the name column output.
* [display\_rows](wp_ms_themes_list_table/display_rows)
* [get\_bulk\_actions](wp_ms_themes_list_table/get_bulk_actions)
* [get\_columns](wp_ms_themes_list_table/get_columns)
* [get\_primary\_column\_name](wp_ms_themes_list_table/get_primary_column_name) — Gets the name of the primary column.
* [get\_sortable\_columns](wp_ms_themes_list_table/get_sortable_columns)
* [get\_table\_classes](wp_ms_themes_list_table/get_table_classes)
* [get\_views](wp_ms_themes_list_table/get_views)
* [no\_items](wp_ms_themes_list_table/no_items)
* [prepare\_items](wp_ms_themes_list_table/prepare_items)
* [single\_row](wp_ms_themes_list_table/single_row)
* [single\_row\_columns](wp_ms_themes_list_table/single_row_columns) — Handles the output for a single table row.
File: `wp-admin/includes/class-wp-ms-themes-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-themes-list-table.php/)
```
class WP_MS_Themes_List_Table extends WP_List_Table {
public $site_id;
public $is_site_themes;
private $has_items;
/**
* 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' => 'themes',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
$status = isset( $_REQUEST['theme_status'] ) ? $_REQUEST['theme_status'] : 'all';
if ( ! in_array( $status, array( 'all', 'enabled', 'disabled', 'upgrade', 'search', 'broken', 'auto-update-enabled', 'auto-update-disabled' ), true ) ) {
$status = 'all';
}
$page = $this->get_pagenum();
$this->is_site_themes = ( 'site-themes-network' === $this->screen->id ) ? true : false;
if ( $this->is_site_themes ) {
$this->site_id = isset( $_REQUEST['id'] ) ? (int) $_REQUEST['id'] : 0;
}
$this->show_autoupdates = wp_is_auto_update_enabled_for_type( 'theme' ) &&
! $this->is_site_themes && current_user_can( 'update_themes' );
}
/**
* @return array
*/
protected function get_table_classes() {
// @todo Remove and add CSS for .themes.
return array( 'widefat', 'plugins' );
}
/**
* @return bool
*/
public function ajax_user_can() {
if ( $this->is_site_themes ) {
return current_user_can( 'manage_sites' );
} else {
return current_user_can( 'manage_network_themes' );
}
}
/**
* @global string $status
* @global array $totals
* @global int $page
* @global string $orderby
* @global string $order
* @global string $s
*/
public function prepare_items() {
global $status, $totals, $page, $orderby, $order, $s;
wp_reset_vars( array( 'orderby', 'order', 's' ) );
$themes = array(
/**
* Filters the full array of WP_Theme objects to list in the Multisite
* themes list table.
*
* @since 3.1.0
*
* @param WP_Theme[] $all Array of WP_Theme objects to display in the list table.
*/
'all' => apply_filters( 'all_themes', wp_get_themes() ),
'search' => array(),
'enabled' => array(),
'disabled' => array(),
'upgrade' => array(),
'broken' => $this->is_site_themes ? array() : wp_get_themes( array( 'errors' => true ) ),
);
if ( $this->show_autoupdates ) {
$auto_updates = (array) get_site_option( 'auto_update_themes', array() );
$themes['auto-update-enabled'] = array();
$themes['auto-update-disabled'] = array();
}
if ( $this->is_site_themes ) {
$themes_per_page = $this->get_items_per_page( 'site_themes_network_per_page' );
$allowed_where = 'site';
} else {
$themes_per_page = $this->get_items_per_page( 'themes_network_per_page' );
$allowed_where = 'network';
}
$current = get_site_transient( 'update_themes' );
$maybe_update = current_user_can( 'update_themes' ) && ! $this->is_site_themes && $current;
foreach ( (array) $themes['all'] as $key => $theme ) {
if ( $this->is_site_themes && $theme->is_allowed( 'network' ) ) {
unset( $themes['all'][ $key ] );
continue;
}
if ( $maybe_update && isset( $current->response[ $key ] ) ) {
$themes['all'][ $key ]->update = true;
$themes['upgrade'][ $key ] = $themes['all'][ $key ];
}
$filter = $theme->is_allowed( $allowed_where, $this->site_id ) ? 'enabled' : 'disabled';
$themes[ $filter ][ $key ] = $themes['all'][ $key ];
$theme_data = array(
'update_supported' => isset( $theme->update_supported ) ? $theme->update_supported : true,
);
// Extra info if known. array_merge() ensures $theme_data has precedence if keys collide.
if ( isset( $current->response[ $key ] ) ) {
$theme_data = array_merge( (array) $current->response[ $key ], $theme_data );
} elseif ( isset( $current->no_update[ $key ] ) ) {
$theme_data = array_merge( (array) $current->no_update[ $key ], $theme_data );
} else {
$theme_data['update_supported'] = false;
}
$theme->update_supported = $theme_data['update_supported'];
/*
* Create the expected payload for the auto_update_theme filter, this is the same data
* as contained within $updates or $no_updates but used when the Theme is not known.
*/
$filter_payload = array(
'theme' => $key,
'new_version' => '',
'url' => '',
'package' => '',
'requires' => '',
'requires_php' => '',
);
$filter_payload = (object) array_merge( $filter_payload, array_intersect_key( $theme_data, $filter_payload ) );
$auto_update_forced = wp_is_auto_update_forced_for_item( 'theme', null, $filter_payload );
if ( ! is_null( $auto_update_forced ) ) {
$theme->auto_update_forced = $auto_update_forced;
}
if ( $this->show_autoupdates ) {
$enabled = in_array( $key, $auto_updates, true ) && $theme->update_supported;
if ( isset( $theme->auto_update_forced ) ) {
$enabled = (bool) $theme->auto_update_forced;
}
if ( $enabled ) {
$themes['auto-update-enabled'][ $key ] = $theme;
} else {
$themes['auto-update-disabled'][ $key ] = $theme;
}
}
}
if ( $s ) {
$status = 'search';
$themes['search'] = array_filter( array_merge( $themes['all'], $themes['broken'] ), array( $this, '_search_callback' ) );
}
$totals = array();
$js_themes = array();
foreach ( $themes as $type => $list ) {
$totals[ $type ] = count( $list );
$js_themes[ $type ] = array_keys( $list );
}
if ( empty( $themes[ $status ] ) && ! in_array( $status, array( 'all', 'search' ), true ) ) {
$status = 'all';
}
$this->items = $themes[ $status ];
WP_Theme::sort_by_name( $this->items );
$this->has_items = ! empty( $themes['all'] );
$total_this_page = $totals[ $status ];
wp_localize_script(
'updates',
'_wpUpdatesItemCounts',
array(
'themes' => $js_themes,
'totals' => wp_get_update_data(),
)
);
if ( $orderby ) {
$orderby = ucfirst( $orderby );
$order = strtoupper( $order );
if ( 'Name' === $orderby ) {
if ( 'ASC' === $order ) {
$this->items = array_reverse( $this->items );
}
} else {
uasort( $this->items, array( $this, '_order_callback' ) );
}
}
$start = ( $page - 1 ) * $themes_per_page;
if ( $total_this_page > $themes_per_page ) {
$this->items = array_slice( $this->items, $start, $themes_per_page, true );
}
$this->set_pagination_args(
array(
'total_items' => $total_this_page,
'per_page' => $themes_per_page,
)
);
}
/**
* @param WP_Theme $theme
* @return bool
*/
public function _search_callback( $theme ) {
static $term = null;
if ( is_null( $term ) ) {
$term = wp_unslash( $_REQUEST['s'] );
}
foreach ( array( 'Name', 'Description', 'Author', 'Author', 'AuthorURI' ) as $field ) {
// Don't mark up; Do translate.
if ( false !== stripos( $theme->display( $field, false, true ), $term ) ) {
return true;
}
}
if ( false !== stripos( $theme->get_stylesheet(), $term ) ) {
return true;
}
if ( false !== stripos( $theme->get_template(), $term ) ) {
return true;
}
return false;
}
// Not used by any core columns.
/**
* @global string $orderby
* @global string $order
* @param array $theme_a
* @param array $theme_b
* @return int
*/
public function _order_callback( $theme_a, $theme_b ) {
global $orderby, $order;
$a = $theme_a[ $orderby ];
$b = $theme_b[ $orderby ];
if ( $a === $b ) {
return 0;
}
if ( 'DESC' === $order ) {
return ( $a < $b ) ? 1 : -1;
} else {
return ( $a < $b ) ? -1 : 1;
}
}
/**
*/
public function no_items() {
if ( $this->has_items ) {
_e( 'No themes found.' );
} else {
_e( 'No themes are currently available.' );
}
}
/**
* @return array
*/
public function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />',
'name' => __( 'Theme' ),
'description' => __( 'Description' ),
);
if ( $this->show_autoupdates ) {
$columns['auto-updates'] = __( 'Automatic Updates' );
}
return $columns;
}
/**
* @return array
*/
protected function get_sortable_columns() {
return array(
'name' => 'name',
);
}
/**
* Gets the name of the primary column.
*
* @since 4.3.0
*
* @return string Unalterable name of the primary column name, in this case, 'name'.
*/
protected function get_primary_column_name() {
return 'name';
}
/**
* @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 themes. */
$text = _nx(
'All <span class="count">(%s)</span>',
'All <span class="count">(%s)</span>',
$count,
'themes'
);
break;
case 'enabled':
/* translators: %s: Number of themes. */
$text = _nx(
'Enabled <span class="count">(%s)</span>',
'Enabled <span class="count">(%s)</span>',
$count,
'themes'
);
break;
case 'disabled':
/* translators: %s: Number of themes. */
$text = _nx(
'Disabled <span class="count">(%s)</span>',
'Disabled <span class="count">(%s)</span>',
$count,
'themes'
);
break;
case 'upgrade':
/* translators: %s: Number of themes. */
$text = _nx(
'Update Available <span class="count">(%s)</span>',
'Update Available <span class="count">(%s)</span>',
$count,
'themes'
);
break;
case 'broken':
/* translators: %s: Number of themes. */
$text = _nx(
'Broken <span class="count">(%s)</span>',
'Broken <span class="count">(%s)</span>',
$count,
'themes'
);
break;
case 'auto-update-enabled':
/* translators: %s: Number of themes. */
$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 themes. */
$text = _n(
'Auto-updates Disabled <span class="count">(%s)</span>',
'Auto-updates Disabled <span class="count">(%s)</span>',
$count
);
break;
}
if ( $this->is_site_themes ) {
$url = 'site-themes.php?id=' . $this->site_id;
} else {
$url = 'themes.php';
}
if ( 'search' !== $type ) {
$status_links[ $type ] = array(
'url' => esc_url( add_query_arg( 'theme_status', $type, $url ) ),
'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 ( 'enabled' !== $status ) {
$actions['enable-selected'] = $this->is_site_themes ? __( 'Enable' ) : __( 'Network Enable' );
}
if ( 'disabled' !== $status ) {
$actions['disable-selected'] = $this->is_site_themes ? __( 'Disable' ) : __( 'Network Disable' );
}
if ( ! $this->is_site_themes ) {
if ( current_user_can( 'update_themes' ) ) {
$actions['update-selected'] = __( 'Update' );
}
if ( current_user_can( 'delete_themes' ) ) {
$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;
}
/**
*/
public function display_rows() {
foreach ( $this->items as $theme ) {
$this->single_row( $theme );
}
}
/**
* Handles the checkbox column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$theme` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Theme $item The current WP_Theme object.
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$theme = $item;
$checkbox_id = 'checkbox_' . md5( $theme->get( 'Name' ) );
?>
<input type="checkbox" name="checked[]" value="<?php echo esc_attr( $theme->get_stylesheet() ); ?>" id="<?php echo $checkbox_id; ?>" />
<label class="screen-reader-text" for="<?php echo $checkbox_id; ?>" ><?php _e( 'Select' ); ?> <?php echo $theme->display( 'Name' ); ?></label>
<?php
}
/**
* Handles the name column output.
*
* @since 4.3.0
*
* @global string $status
* @global int $page
* @global string $s
*
* @param WP_Theme $theme The current WP_Theme object.
*/
public function column_name( $theme ) {
global $status, $page, $s;
$context = $status;
if ( $this->is_site_themes ) {
$url = "site-themes.php?id={$this->site_id}&";
$allowed = $theme->is_allowed( 'site', $this->site_id );
} else {
$url = 'themes.php?';
$allowed = $theme->is_allowed( 'network' );
}
// Pre-order.
$actions = array(
'enable' => '',
'disable' => '',
'delete' => '',
);
$stylesheet = $theme->get_stylesheet();
$theme_key = urlencode( $stylesheet );
if ( ! $allowed ) {
if ( ! $theme->errors() ) {
$url = add_query_arg(
array(
'action' => 'enable',
'theme' => $theme_key,
'paged' => $page,
's' => $s,
),
$url
);
if ( $this->is_site_themes ) {
/* translators: %s: Theme name. */
$aria_label = sprintf( __( 'Enable %s' ), $theme->display( 'Name' ) );
} else {
/* translators: %s: Theme name. */
$aria_label = sprintf( __( 'Network Enable %s' ), $theme->display( 'Name' ) );
}
$actions['enable'] = sprintf(
'<a href="%s" class="edit" aria-label="%s">%s</a>',
esc_url( wp_nonce_url( $url, 'enable-theme_' . $stylesheet ) ),
esc_attr( $aria_label ),
( $this->is_site_themes ? __( 'Enable' ) : __( 'Network Enable' ) )
);
}
} else {
$url = add_query_arg(
array(
'action' => 'disable',
'theme' => $theme_key,
'paged' => $page,
's' => $s,
),
$url
);
if ( $this->is_site_themes ) {
/* translators: %s: Theme name. */
$aria_label = sprintf( __( 'Disable %s' ), $theme->display( 'Name' ) );
} else {
/* translators: %s: Theme name. */
$aria_label = sprintf( __( 'Network Disable %s' ), $theme->display( 'Name' ) );
}
$actions['disable'] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
esc_url( wp_nonce_url( $url, 'disable-theme_' . $stylesheet ) ),
esc_attr( $aria_label ),
( $this->is_site_themes ? __( 'Disable' ) : __( 'Network Disable' ) )
);
}
if ( ! $allowed && ! $this->is_site_themes
&& current_user_can( 'delete_themes' )
&& get_option( 'stylesheet' ) !== $stylesheet
&& get_option( 'template' ) !== $stylesheet
) {
$url = add_query_arg(
array(
'action' => 'delete-selected',
'checked[]' => $theme_key,
'theme_status' => $context,
'paged' => $page,
's' => $s,
),
'themes.php'
);
/* translators: %s: Theme name. */
$aria_label = sprintf( _x( 'Delete %s', 'theme' ), $theme->display( 'Name' ) );
$actions['delete'] = sprintf(
'<a href="%s" class="delete" aria-label="%s">%s</a>',
esc_url( wp_nonce_url( $url, 'bulk-themes' ) ),
esc_attr( $aria_label ),
__( 'Delete' )
);
}
/**
* Filters the action links displayed for each theme in the Multisite
* themes list table.
*
* The action links displayed are determined by the theme's status, and
* which Multisite themes list table is being displayed - the Network
* themes list table (themes.php), which displays all installed themes,
* or the Site themes list table (site-themes.php), which displays the
* non-network enabled themes when editing a site in the Network admin.
*
* The default action links for the Network themes list table include
* 'Network Enable', 'Network Disable', and 'Delete'.
*
* The default action links for the Site themes list table include
* 'Enable', and 'Disable'.
*
* @since 2.8.0
*
* @param string[] $actions An array of action links.
* @param WP_Theme $theme The current WP_Theme object.
* @param string $context Status of the theme, one of 'all', 'enabled', or 'disabled'.
*/
$actions = apply_filters( 'theme_action_links', array_filter( $actions ), $theme, $context );
/**
* Filters the action links of a specific theme in the Multisite themes
* list table.
*
* The dynamic portion of the hook name, `$stylesheet`, refers to the
* directory name of the theme, which in most cases is synonymous
* with the template name.
*
* @since 3.1.0
*
* @param string[] $actions An array of action links.
* @param WP_Theme $theme The current WP_Theme object.
* @param string $context Status of the theme, one of 'all', 'enabled', or 'disabled'.
*/
$actions = apply_filters( "theme_action_links_{$stylesheet}", $actions, $theme, $context );
echo $this->row_actions( $actions, true );
}
/**
* Handles the description column output.
*
* @since 4.3.0
*
* @global string $status
* @global array $totals
*
* @param WP_Theme $theme The current WP_Theme object.
*/
public function column_description( $theme ) {
global $status, $totals;
if ( $theme->errors() ) {
$pre = 'broken' === $status ? __( 'Broken Theme:' ) . ' ' : '';
echo '<p><strong class="error-message">' . $pre . $theme->errors()->get_error_message() . '</strong></p>';
}
if ( $this->is_site_themes ) {
$allowed = $theme->is_allowed( 'site', $this->site_id );
} else {
$allowed = $theme->is_allowed( 'network' );
}
$class = ! $allowed ? 'inactive' : 'active';
if ( ! empty( $totals['upgrade'] ) && ! empty( $theme->update ) ) {
$class .= ' update';
}
echo "<div class='theme-description'><p>" . $theme->display( 'Description' ) . "</p></div>
<div class='$class second theme-version-author-uri'>";
$stylesheet = $theme->get_stylesheet();
$theme_meta = array();
if ( $theme->get( 'Version' ) ) {
/* translators: %s: Theme version. */
$theme_meta[] = sprintf( __( 'Version %s' ), $theme->display( 'Version' ) );
}
/* translators: %s: Theme author. */
$theme_meta[] = sprintf( __( 'By %s' ), $theme->display( 'Author' ) );
if ( $theme->get( 'ThemeURI' ) ) {
/* translators: %s: Theme name. */
$aria_label = sprintf( __( 'Visit theme site for %s' ), $theme->display( 'Name' ) );
$theme_meta[] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
$theme->display( 'ThemeURI' ),
esc_attr( $aria_label ),
__( 'Visit Theme Site' )
);
}
if ( $theme->parent() ) {
$theme_meta[] = sprintf(
/* translators: %s: Theme name. */
__( 'Child theme of %s' ),
'<strong>' . $theme->parent()->display( 'Name' ) . '</strong>'
);
}
/**
* Filters the array of row meta for each theme in the Multisite themes
* list table.
*
* @since 3.1.0
*
* @param string[] $theme_meta An array of the theme's metadata, including
* the version, author, and theme URI.
* @param string $stylesheet Directory name of the theme.
* @param WP_Theme $theme WP_Theme object.
* @param string $status Status of the theme.
*/
$theme_meta = apply_filters( 'theme_row_meta', $theme_meta, $stylesheet, $theme, $status );
echo implode( ' | ', $theme_meta );
echo '</div>';
}
/**
* Handles the auto-updates column output.
*
* @since 5.5.0
*
* @global string $status
* @global int $page
*
* @param WP_Theme $theme The current WP_Theme object.
*/
public function column_autoupdates( $theme ) {
global $status, $page;
static $auto_updates, $available_updates;
if ( ! $auto_updates ) {
$auto_updates = (array) get_site_option( 'auto_update_themes', array() );
}
if ( ! $available_updates ) {
$available_updates = get_site_transient( 'update_themes' );
}
$stylesheet = $theme->get_stylesheet();
if ( isset( $theme->auto_update_forced ) ) {
if ( $theme->auto_update_forced ) {
// Forced on.
$text = __( 'Auto-updates enabled' );
} else {
$text = __( 'Auto-updates disabled' );
}
$action = 'unavailable';
$time_class = ' hidden';
} elseif ( empty( $theme->update_supported ) ) {
$text = '';
$action = 'unavailable';
$time_class = ' hidden';
} elseif ( in_array( $stylesheet, $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",
'theme' => $stylesheet,
'paged' => $page,
'theme_status' => $status,
);
$url = add_query_arg( $query_args, 'themes.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 ( isset( $available_updates->response[ $stylesheet ] ) ) {
$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 theme in the Themes list table.
*
* @since 5.5.0
*
* @param string $html The HTML for theme's auto-update setting, including
* toggle auto-update action link and time to next update.
* @param string $stylesheet Directory name of the theme.
* @param WP_Theme $theme WP_Theme object.
*/
echo apply_filters( 'theme_auto_update_setting_html', $html, $stylesheet, $theme );
echo '<div class="notice notice-error notice-alt inline hidden"><p></p></div>';
}
/**
* Handles default column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$theme` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Theme $item The current WP_Theme object.
* @param string $column_name The current column name.
*/
public function column_default( $item, $column_name ) {
/**
* Fires inside each custom column of the Multisite themes list table.
*
* @since 3.1.0
*
* @param string $column_name Name of the column.
* @param string $stylesheet Directory name of the theme.
* @param WP_Theme $theme Current WP_Theme object.
*/
do_action(
'manage_themes_custom_column',
$column_name,
$item->get_stylesheet(), // Directory name of the theme.
$item // Theme object.
);
}
/**
* Handles the output for a single table row.
*
* @since 4.3.0
*
* @param WP_Theme $item The current WP_Theme object.
*/
public function single_row_columns( $item ) {
list( $columns, $hidden, $sortable, $primary ) = $this->get_column_info();
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">';
$this->column_cb( $item );
echo '</th>';
break;
case 'name':
$active_theme_label = '';
/* The presence of the site_id property means that this is a subsite view and a label for the active theme needs to be added */
if ( ! empty( $this->site_id ) ) {
$stylesheet = get_blog_option( $this->site_id, 'stylesheet' );
$template = get_blog_option( $this->site_id, 'template' );
/* Add a label for the active template */
if ( $item->get_template() === $template ) {
$active_theme_label = ' — ' . __( 'Active Theme' );
}
/* In case this is a child theme, label it properly */
if ( $stylesheet !== $template && $item->get_stylesheet() === $stylesheet ) {
$active_theme_label = ' — ' . __( 'Active Child Theme' );
}
}
echo "<td class='theme-title column-primary{$extra_classes}'><strong>" . $item->display( 'Name' ) . $active_theme_label . '</strong>';
$this->column_name( $item );
echo '</td>';
break;
case 'description':
echo "<td class='column-description desc{$extra_classes}'>";
$this->column_description( $item );
echo '</td>';
break;
case 'auto-updates':
echo "<td class='column-auto-updates{$extra_classes}'>";
$this->column_autoupdates( $item );
echo '</td>';
break;
default:
echo "<td class='$column_name column-$column_name{$extra_classes}'>";
$this->column_default( $item, $column_name );
echo '</td>';
break;
}
}
}
/**
* @global string $status
* @global array $totals
*
* @param WP_Theme $theme
*/
public function single_row( $theme ) {
global $status, $totals;
if ( $this->is_site_themes ) {
$allowed = $theme->is_allowed( 'site', $this->site_id );
} else {
$allowed = $theme->is_allowed( 'network' );
}
$stylesheet = $theme->get_stylesheet();
$class = ! $allowed ? 'inactive' : 'active';
if ( ! empty( $totals['upgrade'] ) && ! empty( $theme->update ) ) {
$class .= ' update';
}
printf(
'<tr class="%s" data-slug="%s">',
esc_attr( $class ),
esc_attr( $stylesheet )
);
$this->single_row_columns( $theme );
echo '</tr>';
if ( $this->is_site_themes ) {
remove_action( "after_theme_row_$stylesheet", 'wp_theme_update_row' );
}
/**
* Fires after each row in the Multisite themes list table.
*
* @since 3.1.0
*
* @param string $stylesheet Directory name of the theme.
* @param WP_Theme $theme Current WP_Theme object.
* @param string $status Status of the theme.
*/
do_action( 'after_theme_row', $stylesheet, $theme, $status );
/**
* Fires after each specific row in the Multisite themes list table.
*
* The dynamic portion of the hook name, `$stylesheet`, refers to the
* directory name of the theme, most often synonymous with the template
* name of the theme.
*
* @since 3.5.0
*
* @param string $stylesheet Directory name of the theme.
* @param WP_Theme $theme Current WP_Theme object.
* @param string $status Status of the theme.
*/
do_action( "after_theme_row_{$stylesheet}", $stylesheet, $theme, $status );
}
}
```
| 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_List_Util {} class WP\_List\_Util {}
=======================
List utility.
Utility class to handle operations on an array of objects or arrays.
* [\_\_construct](wp_list_util/__construct) — Constructor.
* [filter](wp_list_util/filter) — Filters the list, based on a set of key => value arguments.
* [get\_input](wp_list_util/get_input) — Returns the original input array.
* [get\_output](wp_list_util/get_output) — Returns the output array.
* [pluck](wp_list_util/pluck) — Plucks a certain field out of each element in the input array.
* [sort](wp_list_util/sort) — Sorts the input array based on one or more orderby arguments.
* [sort\_callback](wp_list_util/sort_callback) — Callback to sort an array by specific fields.
File: `wp-includes/class-wp-list-util.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-list-util.php/)
```
class WP_List_Util {
/**
* The input array.
*
* @since 4.7.0
* @var array
*/
private $input = array();
/**
* The output array.
*
* @since 4.7.0
* @var array
*/
private $output = array();
/**
* Temporary arguments for sorting.
*
* @since 4.7.0
* @var string[]
*/
private $orderby = array();
/**
* Constructor.
*
* Sets the input array.
*
* @since 4.7.0
*
* @param array $input Array to perform operations on.
*/
public function __construct( $input ) {
$this->output = $input;
$this->input = $input;
}
/**
* Returns the original input array.
*
* @since 4.7.0
*
* @return array The input array.
*/
public function get_input() {
return $this->input;
}
/**
* Returns the output array.
*
* @since 4.7.0
*
* @return array The output array.
*/
public function get_output() {
return $this->output;
}
/**
* Filters the list, based on a set of key => value arguments.
*
* Retrieves the objects from the list that match the given arguments.
* Key represents property name, and value represents property value.
*
* If an object has more properties than those specified in arguments,
* that will not disqualify it. When using the 'AND' operator,
* any missing properties will disqualify it.
*
* @since 4.7.0
*
* @param array $args Optional. An array of key => value arguments to match
* against each object. Default empty array.
* @param string $operator Optional. The logical operation to perform. 'AND' means
* all elements from the array must match. 'OR' means only
* one element needs to match. 'NOT' means no elements may
* match. Default 'AND'.
* @return array Array of found values.
*/
public function filter( $args = array(), $operator = 'AND' ) {
if ( empty( $args ) ) {
return $this->output;
}
$operator = strtoupper( $operator );
if ( ! in_array( $operator, array( 'AND', 'OR', 'NOT' ), true ) ) {
$this->output = array();
return $this->output;
}
$count = count( $args );
$filtered = array();
foreach ( $this->output as $key => $obj ) {
$matched = 0;
foreach ( $args as $m_key => $m_value ) {
if ( is_array( $obj ) ) {
// Treat object as an array.
if ( array_key_exists( $m_key, $obj ) && ( $m_value == $obj[ $m_key ] ) ) {
$matched++;
}
} elseif ( is_object( $obj ) ) {
// Treat object as an object.
if ( isset( $obj->{$m_key} ) && ( $m_value == $obj->{$m_key} ) ) {
$matched++;
}
}
}
if ( ( 'AND' === $operator && $matched === $count )
|| ( 'OR' === $operator && $matched > 0 )
|| ( 'NOT' === $operator && 0 === $matched )
) {
$filtered[ $key ] = $obj;
}
}
$this->output = $filtered;
return $this->output;
}
/**
* Plucks a certain field out of each element in the input array.
*
* This has the same functionality and prototype of
* array_column() (PHP 5.5) but also supports objects.
*
* @since 4.7.0
*
* @param int|string $field Field to fetch from the object or array.
* @param int|string $index_key Optional. Field from the element to use as keys for the new array.
* Default null.
* @return array Array of found values. If `$index_key` is set, an array of found values with keys
* corresponding to `$index_key`. If `$index_key` is null, array keys from the original
* `$list` will be preserved in the results.
*/
public function pluck( $field, $index_key = null ) {
$newlist = array();
if ( ! $index_key ) {
/*
* This is simple. Could at some point wrap array_column()
* if we knew we had an array of arrays.
*/
foreach ( $this->output as $key => $value ) {
if ( is_object( $value ) ) {
$newlist[ $key ] = $value->$field;
} else {
$newlist[ $key ] = $value[ $field ];
}
}
$this->output = $newlist;
return $this->output;
}
/*
* When index_key is not set for a particular item, push the value
* to the end of the stack. This is how array_column() behaves.
*/
foreach ( $this->output as $value ) {
if ( is_object( $value ) ) {
if ( isset( $value->$index_key ) ) {
$newlist[ $value->$index_key ] = $value->$field;
} else {
$newlist[] = $value->$field;
}
} else {
if ( isset( $value[ $index_key ] ) ) {
$newlist[ $value[ $index_key ] ] = $value[ $field ];
} else {
$newlist[] = $value[ $field ];
}
}
}
$this->output = $newlist;
return $this->output;
}
/**
* Sorts the input array based on one or more orderby arguments.
*
* @since 4.7.0
*
* @param string|array $orderby Optional. Either the field name to order by or an array
* of multiple orderby fields as $orderby => $order.
* @param string $order Optional. Either 'ASC' or 'DESC'. Only used if $orderby
* is a string.
* @param bool $preserve_keys Optional. Whether to preserve keys. Default false.
* @return array The sorted array.
*/
public function sort( $orderby = array(), $order = 'ASC', $preserve_keys = false ) {
if ( empty( $orderby ) ) {
return $this->output;
}
if ( is_string( $orderby ) ) {
$orderby = array( $orderby => $order );
}
foreach ( $orderby as $field => $direction ) {
$orderby[ $field ] = 'DESC' === strtoupper( $direction ) ? 'DESC' : 'ASC';
}
$this->orderby = $orderby;
if ( $preserve_keys ) {
uasort( $this->output, array( $this, 'sort_callback' ) );
} else {
usort( $this->output, array( $this, 'sort_callback' ) );
}
$this->orderby = array();
return $this->output;
}
/**
* Callback to sort an array by specific fields.
*
* @since 4.7.0
*
* @see WP_List_Util::sort()
*
* @param object|array $a One object to compare.
* @param object|array $b The other object to compare.
* @return int 0 if both objects equal. -1 if second object should come first, 1 otherwise.
*/
private function sort_callback( $a, $b ) {
if ( empty( $this->orderby ) ) {
return 0;
}
$a = (array) $a;
$b = (array) $b;
foreach ( $this->orderby as $field => $direction ) {
if ( ! isset( $a[ $field ] ) || ! isset( $b[ $field ] ) ) {
continue;
}
if ( $a[ $field ] == $b[ $field ] ) {
continue;
}
$results = 'DESC' === $direction ? array( 1, -1 ) : array( -1, 1 );
if ( is_numeric( $a[ $field ] ) && is_numeric( $b[ $field ] ) ) {
return ( $a[ $field ] < $b[ $field ] ) ? $results[0] : $results[1];
}
return 0 > strcmp( $a[ $field ], $b[ $field ] ) ? $results[0] : $results[1];
}
return 0;
}
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress class WP_Query {} class WP\_Query {}
==================
The WordPress Query class.
Most of the time you can find the information you want without actually dealing with the class internals and global variables. There are a whole bunch of functions that you can call from anywhere that will enable you to get the information you need.
There are two main scenarios you might want to use `WP_Query` in. The first is to find out what type of request WordPress is currently dealing with. The `$is_*` properties are designed to hold this information: use the [Conditional Tags](https://developer.wordpress.org/themes/basics/conditional-tags/) to interact here. This is the more common scenario to plugin writers (the second normally applies to theme writers).
The second is during [The Loop](https://developer.wordpress.org/themes/basics/the-loop/). `WP_Query` provides numerous functions for common tasks within [The Loop](https://developer.wordpress.org/themes/basics/the-loop/). To begin with, [have\_posts()](../functions/have_posts) , which calls `$wp_query->have_posts()`, is called to see if there are any posts to show. If there are, a `while` loop is begun, using [have\_posts()](../functions/have_posts) as the condition. This will iterate around as long as there are posts to show. In each iteration, [the\_post()](../functions/the_post) , which calls `$wp_query->the_post()` is called, setting up internal variables within `$wp_query` and the global `$post` variable (which the [Template Tags](https://developer.wordpress.org/themes/basics/template-tags/) rely on), as above. These are the functions you should use when writing a theme file that needs a loop.
**Note:** If you use [the\_post()](../functions/the_post) with your query, you need to run [wp\_reset\_postdata()](../functions/wp_reset_postdata) afterwards to have template tags use the main query’s current post again.
**Note:** [Ticket #18408](https://core.trac.wordpress.org/ticket/18408) For querying posts in the admin, consider using [get\_posts()](../functions/get_posts) as [wp\_reset\_postdata()](../functions/wp_reset_postdata) might not behave as expected.
```
<?php
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
```
```
<?php
// the query
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- pagination here -->
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
<!-- end of the loop -->
<!-- pagination here -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
```
If you have multiple queries, you need to perform multiple loops. Like so…
```
<?php
// The Query
$query1 = new WP_Query( $args );
// The Loop
while ( $query1->have_posts() ) {
$query1->the_post();
echo '<li>' . get_the_title() . '</li>';
}
/* Restore original Post Data
* NB: Because we are using new WP_Query we aren't stomping on the
* original $wp_query and it does not need to be reset with
* wp_reset_query(). We just need to set the post data back up with
* wp_reset_postdata().
*/
wp_reset_postdata();
/* The 2nd Query (without global var) */
$query2 = new WP_Query( $args2 );
// The 2nd Loop
while ( $query2->have_posts() ) {
$query2->the_post();
echo '<li>' . get_the_title( $query2->post->ID ) . '</li>';
}
// Restore original Post Data
wp_reset_postdata();
?>
```
This is the formal documentation of `WP_Query`. You shouldn’t alter the properties directly, but instead use the [methods (see methods list below)](#methods) to interact with them.
* `$query`
Holds the query string that was passed to the `$wp_query` object by WP class.
* `$query_vars`
An associative array containing the dissected `$query`: an array of the query variables and their respective values.
* `$queried_object`
Applicable if the request is a category, author, permalink or Page. Holds information on the requested category, author, post or Page.
* `$queried_object_id`
If the request is a category, author, permalink or post / page, holds the corresponding ID.
* `$posts`
Gets filled with the requested posts from the database.
* `$post_count`
The number of posts being displayed.
* `$found_posts`
The total number of posts found matching the current query parameters
* `$max_num_pages`
The total number of pages. Is the result of $found\_posts / $posts\_per\_page
* `$current_post`
(available during The Loop) Index of the post currently being displayed.
* `$post`
(available during The Loop) The post currently being displayed.
* `$is_single`, `$is_page`, `$is_archive`, `$is_preview`, `$is_date`, `$is_year`, `$is_month`, `$is_time`, `$is_author`, `$is_category`, `$is_tag`, `$is_tax`, `$is_search`, `$is_feed`, `$is_comment_feed`, `$is_trackback`, `$is_home`, `$is_404`, `$is_comments_popup`, `$is_admin`, `$is_attachment`, `$is_singular`, `$is_robots`, `$is_posts_page`, `$is_paged`
Booleans dictating what type of request this is. For example, the first three represent ‘is it a permalink?’, ‘is it a Page?’, ‘is it any type of archive page?’, respectively. See also [Conditional Tags](https://developer.wordpress.org/themes/basics/conditional-tags/).
Show posts associated with certain author.
* **`author`** (*int*) – use author id.
* **`author_name`** (*string*) – use ‘`user_nicename`‘ – NOT name.
* **`author__in`** (*array*) – use author id (available since version 3.7).
* **`author__not_in`** (*array*) – use author id (available since version 3.7).
**Show Posts for one Author**
Display posts by author, using author id:
```
$query = new WP_Query( array( 'author' => 123 ) );
```
Display posts by author, using author ‘`user_nicename`‘:
```
$query = new WP_Query( array( 'author_name' => 'rami' ) );
```
**Show Posts From Several Authors**
Display posts from several specific authors:
```
$query = new WP_Query( array( 'author' => '2,6,17,38' ) );
```
**Exclude Posts Belonging to an Author**
Display all posts *except* those from an author(singular) by prefixing its id with a ‘-‘ (minus) sign:
```
$query = new WP_Query( array( 'author' => -12 ) );
```
**Multiple Author Handling**
Display posts from multiple authors:
```
$query = new WP_Query( array( 'author__in' => array( 2, 6 ) ) );
```
You can also exclude multiple author this way:
```
$query = new WP_Query( array( 'author__not_in' => array( 2, 6 ) ) );
```
Show posts associated with certain categories.
* **`cat`** (*int*) – use category id.
* **`category_name`** (*string*) – use category slug.
* **`category__and`** (*array*) – use category id.
* **`category__in`** (*array*) – use category id.
* **`category__not_in`** (*array*) – use category id.
**Display posts that have one category (and any children of that category), using category id:**
```
$query = new WP_Query( array( 'cat' => 4 ) );
```
**Display posts that have this category (and any children of that category), using category slug:**
```
$query = new WP_Query( array( 'category_name' => 'staff' ) );
```
**Display posts that have this category (not children of that category), using category id:**
```
$query = new WP_Query( array( 'category__in' => 4 ) );
```
**Display posts that have several categories, using category id:**
```
$query = new WP_Query( array( 'cat' => '2,6,17,38' ) );
```
**Display posts that have these categories, using category slug:**
```
$query = new WP_Query( array( 'category_name' => 'staff,news' ) );
```
**Display posts that have “all” of these categories:**
```
$query = new WP_Query( array( 'category_name' => 'staff+news' ) );
```
**Display all posts *except* those from a category by prefixing its id with a ‘-‘ (minus) sign.**
```
$query = new WP_Query( array( 'cat' => '-12,-34,-56' ) );
```
**Display posts that are in multiple categories. This shows posts that are in both categories 2 and 6:**
```
$query = new WP_Query( array( 'category__and' => array( 2, 6 ) ) );
```
To display posts from either category 2 OR 6, you could use `cat` as mentioned above, or by using `category__in` (note this does not show posts from any children of these categories):
```
$query = new WP_Query( array( 'category__in' => array( 2, 6 ) ) );
```
You can also exclude multiple categories this way:
```
$query = new WP_Query( array( 'category__not_in' => array( 2, 6 ) ) );
```
Show posts associated with certain tags.
* **`tag`** (*string*) – use tag slug.
* **`tag_id`** (*int*) – use tag id.
* **`tag__and`** (*array*) – use tag ids.
* **`tag__in`** (*array*) – use tag ids.
* **`tag__not_in`** (*array*) – use tag ids.
* **`tag_slug__and`** (*array*) – use tag slugs.
* **`tag_slug__in`** (*array*) – use tag slugs.
**Display posts that have one tag, using tag slug:**
```
$query = new WP_Query( array( 'tag' => 'cooking' ) );
```
**Display posts that have this tag, using tag id:**
```
$query = new WP_Query( array( 'tag_id' => 13 ) );
```
**Display posts that have “either” of these tags:**
```
$query = new WP_Query( array( 'tag' => 'bread,baking' ) );
```
**Display posts that have “all” of these tags:**
```
$query = new WP_Query( array( 'tag' => 'bread+baking+recipe' ) );
```
**Display posts that are tagged with both tag id 37 and tag id 47:**
```
$query = new WP_Query( array( 'tag__and' => array( 37, 47 ) ) );
```
To display posts from either tag id 37 or 47, you could use `tag` as mentioned above, or explicitly specify by using `tag__in`:
```
$query = new WP_Query( array( 'tag__in' => array( 37, 47 ) ) );
```
**Display posts that do not have any of the two tag ids 37 and 47:**
```
$query = new WP_Query( array( 'tag__not_in' => array( 37, 47 ) ) );
```
The `tag_slug__in` and `tag_slug__and` behave much the same, except match against the tag’s slug.
Show posts associated with certain taxonomy.
* **`{tax}`** (*string*) – use taxonomy slug. (**Deprecated** since version 3.1 in favor of ‘`tax_query`‘).
* **`tax_query`** (*array*) – use taxonomy parameters (available since version 3.1).
+ **`relation`** (*string*) – The logical relationship between each inner taxonomy array when there is more than one. Possible values are ‘AND’, ‘OR’. Do not use with a single inner taxonomy array.
- **`taxonomy`** (*string*) – Taxonomy.
- **`field`** (*string*) – Select taxonomy term by. Possible values are ‘term\_id’, ‘name’, ‘slug’ or ‘term\_taxonomy\_id’. Default value is ‘term\_id’.
- **`terms`** (*int/string/array*) – Taxonomy term(s).
- **`include_children`** (*boolean*) – Whether or not to include children for hierarchical taxonomies. Defaults to true.
- **`operator`** (*string*) – Operator to test. Possible values are ‘IN’, ‘NOT IN’, ‘AND’, ‘EXISTS’ and ‘NOT EXISTS’. Default value is ‘IN’.
**Important Note:** `tax_query` takes an **array** of tax query arguments **arrays** (it takes an array of arrays).
This construct allows you to query multiple taxonomies by using the **`relation`** parameter in the first (outer) array to describe the boolean relationship between the taxonomy arrays.
**Simple Taxonomy Query:**
Display **posts** tagged with **bob**, under **people** custom taxonomy:
```
$args = array(
'post_type' => 'post',
'tax_query' => array(
array(
'taxonomy' => 'people',
'field' => 'slug',
'terms' => 'bob',
),
),
);
$query = new WP_Query( $args );
```
**Multiple Taxonomy Handling:**
Display **posts** from several custom taxonomies:
```
$args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'movie_genre',
'field' => 'slug',
'terms' => array( 'action', 'comedy' ),
),
array(
'taxonomy' => 'actor',
'field' => 'term_id',
'terms' => array( 103, 115, 206 ),
'operator' => 'NOT IN',
),
),
);
$query = new WP_Query( $args );
```
Display **posts** that are in the **quotes** category OR have the **quote** post format:
```
$args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'quotes' ),
),
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array( 'post-format-quote' ),
),
),
);
$query = new WP_Query( $args );
```
**Nested Taxonomy Handling:**
The `'tax_query'` clauses can be nested, to create more complex queries. Example: Display **posts** that are in the **quotes** category OR both have the **quote** post format AND are in the **wisdom** category:
```
$args = array(
'post_type' => 'post',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'quotes' ),
),
array(
'relation' => 'AND',
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array( 'post-format-quote' ),
),
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'wisdom' ),
),
),
),
);
$query = new WP_Query( $args );
```
Show posts based on a keyword search.
* **`s`** (*string*) – Search keyword.
**Show Posts based on a keyword search**
```
$query = new WP_Query( array( 's' => 'keyword' ) );
```
Prepending a term with a hyphen will exclude posts matching that term. Eg, `'pillow -sofa'` will return posts containing ‘pillow’ but not ‘sofa’ (available since Version 4.4).
Display content based on post and page parameters. Remember that default `post_type` is only set to display posts but not pages.
* **`p`** (*int*) – use post id.
* **`name`** (*string*) – use post slug.
* **`page_id`** (*int*) – use page id.
* **`pagename`** (*string*) – use page slug.
* **`post_parent`** (*int*) – use page id to return only child pages. Set to 0 to return only top-level entries.
* **`post_parent__in`** (*array*) – use post ids. Specify posts whose parent is in an array (available since version 3.6).
* **`post_parent__not_in`** (*array*) – use post ids. Specify posts whose parent is not in an array (available since version 3.6).
* **`post__in`** (*array*) – use post ids. Specify posts to retrieve. **ATTENTION** If you use sticky posts, they will be included (prepended!) in the posts you retrieve whether you want it or not. To suppress this behaviour use `ignore_sticky_posts`.
* **`post__not_in`** (*array*) – use post ids. Specify post NOT to retrieve.
* **`post_name__in`** (*array*) – use post slugs. Specify posts to retrieve (available since version 4.4).
**NOTE:** [Ticket #28099](https://core.trac.wordpress.org/ticket/28099): Passing an empty array to `post__in` will return `has_posts()` as true (and all posts will be returned). Logic should be used before hand to determine if `WP_Query` should be used in the event that the array being passed to `post__in` is empty.
**Display post by ID:**
```
$query = new WP_Query( array( 'p' => 7 ) );
```
**Display page by ID:**
```
$query = new WP_Query( array( 'page_id' => 7 ) );
```
**Show post/page by slug**
```
$query = new WP_Query( array( 'name' => 'about-my-life' ) );
```
**Display page by `slug`:**
```
$query = new WP_Query( array( 'pagename' => 'contact' ) );
```
**Display child page using the slug of the parent and the child page, separated by a slash (e.g. ‘parent\_slug/child\_slug’):**
```
$query = new WP_Query( array( 'pagename' => 'contact_us/canada' ) );
```
**Display child pages using parent page ID:**
```
$query = new WP_Query( array( 'post_parent' => 93 ) );
```
**Display only top-level pages, exclude all child pages:**
```
$query = new WP_Query( array( 'post_parent' => 0 ) );
```
**Display posts whose parent is in an array:**
```
$query = new WP_Query( array( 'post_parent__in' => array( 2, 5, 12, 14, 20 ) ) );
```
**Display only the specific posts:**
```
$query = new WP_Query( array( 'post_type' => 'page', 'post__in' => array( 2, 5, 12, 14, 20 ) ) );
```
**Display all posts but NOT the specified ones:**
```
$query = new WP_Query( array( 'post_type' => 'post', 'post__not_in' => array( 2, 5, 12, 14, 20 ) ) );
```
**Note:** you cannot combine `post__in` and `post__not_in` in the same query.
Also note that using a string containing a comma separated list will not work here. If you’re passing a variable, make sure it’s a proper array of integer values:
```
// This will NOT work
$exclude_ids = '1,2,3';
$query = new WP_Query( array( 'post__not_in' => array( $exclude_ids ) ) );
// This WILL work
$exclude_ids = array( 1, 2, 3 );
$query = new WP_Query( array( 'post__not_in' => $exclude_ids ) );
```
Show content based on post and page parameters. Remember that default `post_type` is only set to display posts but not pages.
* **`has_password`** (*bool*) – true for posts with passwords ; false for posts without passwords ; null for all posts with and without passwords (available since version 3.9).
* **`post_password`** (*string*) – show posts with a particular password (available since version 3.9)
**Display only password protected posts:**
```
$query = new WP_Query( array( 'has_password' => true ) );
```
**Display only posts without passwords:**
```
$query = new WP_Query( array( 'has_password' => false ) );
```
**Display only posts with and without passwords:**
```
$query = new WP_Query( array( 'has_password' => null ) );
```
**Display posts with a particular password:**
```
$query = new WP_Query( array( 'post_password' => 'zxcvbn' ) );
```
Show posts associated with certain [type](https://developer.wordpress.org/themes/basics/post-types/).
* **`post_type`** (*string* / *array*) – use post types. Retrieves posts by post types, default value is ‘`post`‘. If ‘`tax_query`‘ is set for a query, the default value becomes ‘`any`‘;
+ ‘`post`‘ – a post.
+ ‘`page`‘ – a page.
+ ‘`revision`‘ – a revision.
+ ‘`attachment`‘ – an attachment. Whilst the default [WP\_Query](wp_query) `post_status` is ‘publish’, attachments have a default `post_status` of ‘inherit’. This means no attachments will be returned unless you also explicitly set `post_status` to ‘inherit’ or ‘any’. See [Status parameters](#status-parameters) section below.
+ ‘`nav_menu_item`‘ – a navigation menu item
+ ‘`any`‘ – retrieves any type except revisions and types with ‘exclude\_from\_search’ set to true.
\*\* Custom Post Types (e.g. movies)
**Display only pages:**
```
$query = new WP_Query( array( 'post_type' => 'page' ) );
```
**Display ‘`any`‘ post type (retrieves any type except revisions and types with ‘exclude\_from\_search’ set to TRUE):**
```
$query = new WP_Query( array( 'post_type' => 'any' ) );
```
**Display multiple post types, including custom post types:**
```
$args = array(
'post_type' => array( 'post', 'page', 'movie', 'book' )
);
$query = new WP_Query( $args );
```
Show posts associated with certain [post status](https://wordpress.org/support/article/post-status/).
* **`post_status`** (*string* / *array*) – use post status. Retrieves posts by post status. Default value is ‘`publish`‘, but if the user is logged in, ‘`private`‘ is added. Public [custom post statuses](https://wordpress.org/support/article/post-status/#custom-status) are also included by default. And if the query is run in an admin context (administration area or AJAX call), protected statuses are added too. By default protected statuses are ‘`future`‘, ‘`draft`‘ and ‘`pending`‘.
+ ‘`publish`‘ – a published post or page.
+ ‘`pending`‘ – post is pending review.
+ ‘`draft`‘ – a post in draft status.
+ ‘`auto-draft`‘ – a newly created post, with no content.
+ ‘`future`‘ – a post to publish in the future.
+ ‘`private`‘ – not visible to users who are not logged in.
+ ‘`inherit`‘ – a revision. see [get\_children()](../functions/get_children) .
+ ‘`trash`‘ – post is in trashbin (available since version 2.9).
+ ‘`any`‘ – retrieves any status except for ‘inherit’, ‘trash’ and ‘auto-draft’. Custom post statuses with ‘exclude\_from\_search’ set to true are also excluded.
**Display only posts with the ‘`draft`‘ status:**
```
$query = new WP_Query( array( 'post_status' => 'draft' ) );
```
**Display multiple post status:**
```
$args = array(
'post_status' => array( 'pending', 'draft', 'future' )
);
$query = new WP_Query( $args );
```
**Display all attachments:**
```
$args = array(
'post_status' => 'any',
'post_type' => 'attachment'
);
$query = new WP_Query( $args );
```
Since Version 4.9 Introduced the `$comment\_count` parameter. It can be either an Integer or an Array.
* **`comment_count`** (*int*) – The amount of comments your CPT has to have ( Search operator will do a ‘=’ operation )
* **`comment_count`** (*Array*) – If comment\_count is an array, it should have two arguments:
+ ‘`value`‘ – The amount of comments your post has to have when comparing
+ ‘`compare`‘ – The search operator. Possible values are ‘=’, ‘!=’, ‘>’, ‘>=’, ‘<‘, ‘<=’. Default value is ‘=’.
**Display posts with 20 comments:**
```
$args = array(
'post_type' => 'post',
'comment_count' => 20,
);
$query = new WP_Query( $args );
```
**Display posts with 25 comments or more:**
```
$args = array(
'post_type' => 'post',
'comment_count' => array(
'value' => 25,
'compare' => '>=',
)
);
$query = new WP_Query( $args );
```
* **`nopaging`** (*boolean*) – show all posts or use pagination. Default value is ‘false’, use paging.
* **`posts_per_page`** (*int*) – number of post to show per page (available since version 2.1, replaced **`showposts`** parameter). Use `'posts_per_page'=>-1` to show all posts (the `'offset'` parameter is ignored with a `-1` value). Set the ‘paged’ parameter if pagination is off after using this parameter. *Note*: if the query is in a feed, wordpress overwrites this parameter with the stored ‘posts\_per\_rss’ option. To reimpose the limit, try using the ‘post\_limits’ filter, or filter ‘pre\_option\_posts\_per\_rss’ and return -1
* **`posts_per_archive_page`** (*int*) – number of posts to show per page – on archive pages only. Over-rides **`posts_per_page`** and **`showposts`** on pages where [is\_archive()](../functions/is_archive) or [is\_search()](../functions/is_search) would be true.
* **`offset`** (*int*) – number of post to *displace* or pass over. *Warning*: Setting the offset parameter overrides/ignores the paged parameter and breaks pagination. The `'offset'` parameter is ignored when `'posts_per_page'=>-1` (show all posts) is used.
* **`paged`** (*int*) – number of page. Show the posts that would normally show up just on page X when using the “Older Entries” link.
* **`page`** (*int*) – number of page for a static front page. Show the posts that would normally show up just on page X of a Static Front Page.
* **`ignore_sticky_posts`** (*boolean*) – ignore post stickiness (available since version 3.1, replaced **`caller_get_posts`** parameter). `false` (default): move sticky posts to the start of the set. `true`: do not move sticky posts to the start of the set.
**Display x posts per page:**
```
$query = new WP_Query( array( 'posts_per_page' => 3 ) );
```
**Display all posts in one page:**
```
$query = new WP_Query( array( 'posts_per_page' => -1 ) );
```
**Display all posts by disabling pagination:**
```
$query = new WP_Query( array( 'nopaging' => true ) );
```
**Display posts from the 4th one:**
```
$query = new WP_Query( array( 'offset' => 3 ) );
```
**Display 5 posts per page which follow the 3 most recent posts:**
```
$query = new WP_Query( array( 'posts_per_page' => 5, 'offset' => 3 ) );
```
**Display posts from page number x:**
```
$query = new WP_Query( array( 'paged' => 6 ) );
```
**Display posts from current page:**
```
$query = new WP_Query( array( 'paged' => get_query_var( 'paged' ) ) );
```
Display posts from the current page and set the ‘paged’ parameter to 1 when the query variable is not set (first page).
```
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query = new WP_Query( array( 'paged' => $paged ) );
```
Pagination Note: Use `get_query_var('page');` if you want your query to work in a [page template](https://developer.wordpress.org/themes/template-files-section/page-template-files/) that you’ve set as your [static front page](https://wordpress.org/support/article/creating-a-static-front-page/). The query variable ‘page’ also holds the pagenumber for a single paginated Post or Page that includes the `<!--nextpage-->` quicktag in the post content.
**Display posts from current page on a [static front page](https://wordpress.org/support/article/creating-a-static-front-page/):**
```
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
$query = new WP_Query( array( 'paged' => $paged ) );
```
**Display just the first sticky post:**
```
$sticky = get_option( 'sticky_posts' );
$query = new WP_Query( array( 'p' => $sticky[0] ) );
```
**Display just the first sticky post, if none return the last post published:**
```
$args = array(
'posts_per_page' => 1,
'post__in' => get_option( 'sticky_posts' ),
'ignore_sticky_posts' => 1,
);
$query = new WP_Query( $args );
```
**Display just the first sticky post, if none return nothing:**
```
$sticky = get_option( 'sticky_posts' );
$args = array(
'posts_per_page' => 1,
'post__in' => $sticky,
'ignore_sticky_posts' => 1,
);
$query = new WP_Query( $args );
if ( $sticky[0] ) {
// insert here your stuff...
}
```
**Exclude all sticky posts from the query:**
```
$query = new WP_Query( array( 'post__not_in' => get_option( 'sticky_posts' ) ) );
```
**Exclude sticky posts from a category:**
Return ALL posts within the category, but don’t show sticky posts at the top. The ‘sticky posts’ will still show in their natural position (e.g. by date):
```
$query = new WP_Query( array( 'ignore_sticky_posts' => 1, 'posts_per_page' => 3, 'cat' => 6 );
```
**Exclude sticky posts from a category:**
Return posts within the category, but exclude sticky posts completely, and adhere to paging rules:
```
$paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
$sticky = get_option( 'sticky_posts' );
$args = array(
'cat' => 3,
'ignore_sticky_posts' => 1,
'post__not_in' => $sticky,
'paged' => $paged,
);
$query = new WP_Query( $args );
```
Sort retrieved posts.
* **`order`** (*string | array*) – Designates the ascending or descending order of the ‘`orderby`‘ parameter. Defaults to ‘DESC’. An array can be used for multiple order/orderby sets.
+ ‘`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).
* **`orderby`** (*string | array*) – Sort retrieved posts by parameter. Defaults to ‘date (post\_date)’. One or more options can be passed.
+ ‘`none`‘ – No order (available since version 2.8).
+ ‘`ID`‘ – Order by post id. Note the capitalization.
+ ‘`author`‘ – Order by author.
+ ‘`title`‘ – Order by title.
+ ‘`name`‘ – Order by post name (post slug).
+ ‘`type`‘ – Order by post type (available since version 4.0).
+ ‘`date`‘ – Order by date.
+ ‘`modified`‘ – Order by last modified date.
+ ‘`parent`‘ – Order by post/page parent id.
+ ‘`rand`‘ – Random order.
+ ‘`comment_count`‘ – Order by number of comments (available since version 2.9).
+ ‘`relevance`‘ – Order by search terms in the following order: First, whether the entire sentence is matched. Second, if all the search terms are within the titles. Third, if any of the search terms appear in the titles. And, fourth, if the full sentence appears in the contents.
+ ‘`menu_order`‘ – Order by Page Order. Used most often for pages (*Order* field in the Edit Page Attributes box) and for attachments (the integer fields in the Insert / Upload Media Gallery dialog), but could be used for any post type with distinct ‘`menu_order`‘ values (they all default to 0).
+ ‘`meta_value`‘ – Note that a ‘`meta_key=keyname`‘ must also be present in the query. Note also that the sorting will be alphabetical which is fine for strings (i.e. words), but can be unexpected for numbers (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as you might naturally expect). Use ‘`meta_value_num`‘ instead for numeric values. You may also specify ‘`meta_type`‘ if you want to cast the meta value as a specific type. Possible values are ‘NUMERIC’, ‘BINARY’, ‘CHAR’, ‘DATE’, ‘DATETIME’, ‘DECIMAL’, ‘SIGNED’, ‘TIME’, ‘UNSIGNED’, same as in ‘`$meta_query`‘. When using ‘meta\_type’ you can also use ‘meta\_value\_\*’ accordingly. For example, when using DATETIME as ‘meta\_type’ you can use ‘meta\_value\_datetime’ to define order structure.
+ ‘`meta_value_num`‘ – Order by numeric meta value (available since version 2.8). Also note that a ‘`meta_key=keyname`‘ must also be present in the query. This value allows for numerical sorting as noted above in ‘`meta_value`‘.
+ ‘`post__in`‘ – Preserve post ID order given in the post\_\_in array (available since version 3.5). Note – the value of the order parameter does not change the resulting sort order.
+ ‘`post_name__in`‘ – Preserve post slug order given in the ‘post\_name\_\_in’ array (available since Version 4.6). Note – the value of the order parameter does not change the resulting sort order.
+ ‘`post_parent__in`‘ -Preserve post parent order given in the ‘post\_parent\_\_in’ array (available since Version 4.6). Note – the value of the order parameter does not change the resulting sort order.
**Display posts sorted by post ‘title’ in a descending order:**
```
$args = array(
'orderby' => 'title',
'order' => 'DESC',
);
$query = new WP_Query( $args );
```
**Display posts sorted by ‘menu\_order’ with a fallback to post ‘title’, in a descending order:**
```
$args = array(
'orderby' => 'menu_order title',
'order' => 'DESC',
);
$query = new WP_Query( $args );
```
**Display one random post:**
```
$args = array(
'orderby' => 'rand',
'posts_per_page' => '1',
);
$query = new WP_Query( $args );
```
**Display posts ordered by comment count (popularity):**
```
$args = array(
'orderby' => 'comment_count'
);
$query = new WP_Query( $args );
```
**Display posts with ‘Product’ type ordered by ‘Price’ custom field:**
```
$args = array(
'post_type' => 'product',
'orderby' => 'meta_value_num',
'meta_key' => 'price',
);
$query = new WP_Query( $args );
```
**Display pages ordered by ‘title’ and ‘menu\_order’. (title is dominant):**
```
$args = array(
'post_type' => 'page',
'orderby' => 'title menu_order',
'order' => 'ASC',
);
$query = new WP_Query( $args );
```
**Display pages ordered by ‘title’ and ‘menu\_order’ with different sort orders (ASC/DESC) (available since version 4.0):**
```
$args = array(
'orderby' => array( 'title' => 'DESC', 'menu_order' => 'ASC' )
);
$query = new WP_Query( $args );
```
Related article: [A more powerful ORDER BY in WordPress 4.0](https://make.wordpress.org/core/2014/08/29/a-more-powerful-order-by-in-wordpress-4-0/).
**Mulitiple orderby/order pairs**
```
$args = array(
'orderby' => array( 'meta_value_num' => 'DESC', 'title' => 'ASC' ),
'meta_key' => 'age'
);
$query = new WP_Query( $args );
```
**‘orderby’ with ‘meta\_value’ and custom post type**
Display posts of type ‘my\_custom\_post\_type’, ordered by ‘age’, and filtered to show only ages 3 and 4 (using meta\_query).
```
$args = array(
'post_type' => 'my_custom_post_type',
'meta_key' => 'age',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'age',
'value' => array( 3, 4 ),
'compare' => 'IN',
),
),
);
$query = new WP_Query( $args );
```
**‘orderby’ with multiple ‘meta\_key’s**
If you wish to order by two different pieces of postmeta (for example, City first and State second), you need to combine and link your meta query to your orderby array using ‘named meta queries’. See the example below:
```
$q = new WP_Query( array(
'meta_query' => array(
'relation' => 'AND',
'state_clause' => array(
'key' => 'state',
'value' => 'Wisconsin',
),
'city_clause' => array(
'key' => 'city',
'compare' => 'EXISTS',
),
),
'orderby' => array(
'city_clause' => 'ASC',
'state_clause' => 'DESC',
),
) );
```
(props to cybmeta on WPSE for [this example](http://wordpress.stackexchange.com/a/246358/3687)).
Show posts associated with a certain time and date period.
* **`year`** (*int*) – 4 digit year (e.g. 2011).
* **`monthnum`** (*int*) – Month number (from 1 to 12).
* **`w`** (*int*) – Week of the year (from 0 to 53). Uses [MySQL WEEK command](http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_week). The mode is dependent on the “start\_of\_week” option.
* **`day`** (*int*) – Day of the month (from 1 to 31).
* **`hour`** (*int*) – Hour (from 0 to 23).
* **`minute`** (*int*) – Minute (from 0 to 60).
* **`second`** (*int*) – Second (0 to 60).
* **`m`** (*int*) – YearMonth (For e.g.: **`201307`**).
* **`date_query`** (*array*) – Date parameters (available since version 3.7).
+ **`year`** (*int*) – 4 digit year (e.g. 2011).
+ **`month`** (*int*) – Month number (from 1 to 12).
+ **`week`** (*int*) – Week of the year (from 0 to 53).
+ **`day`** (*int*) – Day of the month (from 1 to 31).
+ **`hour`** (*int*) – Hour (from 0 to 23).
+ **`minute`** (*int*) – Minute (from 0 to 59).
+ **`second`** (*int*) – Second (0 to 59).
+ **`after`** (*string/array*) – Date to retrieve posts after. Accepts `[strtotime()](http://php.net/strtotime)`-compatible string, or array of ‘year’, ‘month’, ‘day’ values:
- **`year`** (*string*) Accepts any four-digit year. Default is empty.
- **`month`** (*string*) The month of the year. Accepts numbers 1-12. Default: 12.
- **`day`** (*string*) The day of the month. Accepts numbers 1-31. Default: last day of month.
+ **`before`** (*string/array*) – Date to retrieve posts before. Accepts `[strtotime()](http://php.net/strtotime)`-compatible string, or array of ‘year’, ‘month’, ‘day’ values:
- **`year`** (*string*) Accepts any four-digit year. Default is empty.
- **`month`** (*string*) The month of the year. Accepts numbers 1-12. Default: 1.
- **`day`** (*string*) The day of the month. Accepts numbers 1-31. Default: 1.
+ **`inclusive`** (*boolean*) – For after/before, whether exact value should be matched or not’.
+ **`compare`** (*string*) – See [WP\_Date\_Query::get\_compare()](wp_date_query/get_compare).
+ **`column`** (*string*) – Posts column to query against. Default: ‘post\_date’.
+ **`relation`** (*string*) – OR or AND, how the sub-arrays should be compared. Default: AND.
**Returns posts dated December 12, 2012:**
```
$query = new WP_Query( 'year=2012&monthnum=12&day=12' );
```
or:
```
$args = array(
'date_query' => array(
array(
'year' => 2012,
'month' => 12,
'day' => 12,
),
),
);
$query = new WP_Query( $args );
```
**Returns posts for today:**
```
$today = getdate();
$query = new WP_Query( 'year=' . $today['year'] . '&monthnum=' . $today['mon'] . '&day=' . $today['mday'] );
```
or:
```
$today = getdate();
$args = array(
'date_query' => array(
array(
'year' => $today['year'],
'month' => $today['mon'],
'day' => $today['mday'],
),
),
);
$query = new WP_Query( $args );
```
**Returns posts for this week:**
```
$week = date( 'W' );
$year = date( 'Y' );
$query = new WP_Query( 'year=' . $year . '&w=' . $week );
```
or:
```
$args = array(
'date_query' => array(
array(
'year' => date( 'Y' ),
'week' => date( 'W' ),
),
),
);
$query = new WP_Query( $args );
```
**Return posts between 9AM to 5PM on weekdays**
```
$args = array(
'date_query' => array(
array(
'hour' => 9,
'compare' => '>=',
),
array(
'hour' => 17,
'compare' => '<=',
),
array(
'dayofweek' => array( 2, 6 ),
'compare' => 'BETWEEN',
),
),
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
```
**Return posts from January 1st to February 28th**
```
$args = array(
'date_query' => array(
array(
'after' => 'January 1st, 2013',
'before' => array(
'year' => 2013,
'month' => 2,
'day' => 28,
),
'inclusive' => true,
),
),
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
```
Note that if a `[strtotime()](http://php.net/strtotime)`-compatible string with just a date was passed in the `before` parameter, this will be converted to 00:00:00 on that date. In this case, even if `inclusive` was set to true, the date would not be included in the query. If you want a before date to be inclusive, include the time as well, such as `'before' => '2013-02-28 23:59:59'`, or use the array format, which is adjusted automatically if `inclusive` is set.
**Return posts made over a year ago but modified in the past month**
```
$args = array(
'date_query' => array(
array(
'column' => 'post_date_gmt',
'before' => '1 year ago',
),
array(
'column' => 'post_modified_gmt',
'after' => '1 month ago',
),
),
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
```
The `'date_query'` clauses can be nested, in order to construct complex queries. See [Taxonomy Parameters](#taxonomy-parameters) for details on the syntax.
Show posts associated with a certain custom field.
This part of the query is parsed by [WP\_Meta\_Query](wp_meta_query), so check the docs for it as well in case this list of arguments isn’t up to date.
* **`meta_key`** (*string*) – Custom field key.
* **`meta_value`** (*string*) – Custom field value.
* **`meta_value_num`** (*number*) – Custom field value.
* **`meta_compare`** (*string*) – Operator to test the ‘`meta_value`‘. Possible values are ‘=’, ‘!=’, ‘>’, ‘>=’, ‘<‘, ‘<=’, ‘LIKE’, ‘NOT LIKE’, ‘IN’, ‘NOT IN’, ‘BETWEEN’, ‘NOT BETWEEN’, ‘NOT EXISTS’, ‘REGEXP’, ‘NOT REGEXP’ or ‘RLIKE’. Default value is ‘=’.
* **`meta_query`** (*array*) – Custom field parameters (available since version 3.1).
+ **`relation`** (*string*) – The logical relationship between each inner meta\_query array when there is more than one. Possible values are ‘AND’, ‘OR’. Do not use with a single inner meta\_query array.
`meta_query` also 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` is required for `NOT EXISTS` comparisons to work correctly prior to 3.9. You must 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’ and ‘NOT EXISTS’. 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.
**Important Note:** `meta_query` takes an **array** of meta query arguments **arrays** (it takes an array of arrays) – you can see this in the examples below.
This construct allows you to query multiple metadatas by using the **`relation`** parameter in the first (outer) array to describe the boolean relationship between the meta queries. Accepted arguments are ‘AND’, ‘OR’. The default is ‘AND’.
**Simple Custom Field Query:**
Display posts where the custom field key is ‘color’, regardless of the custom field value:
```
$query = new WP_Query( array( 'meta_key' => 'color' ) );
```
Display posts where the custom field value is ‘blue’, regardless of the custom field key:
```
$query = new WP_Query( array( 'meta_value' => 'blue' ) );
```
Display page where the custom field value is ‘blue’, regardless of the custom field key:
```
$args = array(
'meta_value' => 'blue',
'post_type' => 'page'
);
$query = new WP_Query( $args );
```
Display posts where the custom field key is ‘color’ and the custom field value is ‘blue’:
```
$args = array(
'meta_key' => 'color',
'meta_value' => 'blue'
);
$query = new WP_Query( $args );
```
Display posts where the custom field key is ‘color’ and the custom field value IS NOT ‘blue’:
```
$args = array(
'meta_key' => 'color',
'meta_value' => 'blue',
'meta_compare' => '!='
);
$query = new WP_Query( $args );
```
Display posts where the custom field key is a set date and the custom field value is now. Displays only posts which date has not passed.
```
$args = array(
'post_type' => 'event',
'meta_key' => 'event_date',
'meta_value' => date( "Ymd" ), // change to how "event date" is stored
'meta_compare' => '>',
);
$query = new WP_Query( $args );
```
Display ‘product'(s) where the custom field key is ‘price’ and the custom field value that is LESS THAN OR EQUAL TO 22.
*By using the ‘meta\_value’ parameter the value 99 will be considered greater than 100 as the data are stored as ‘strings’, not ‘numbers’. For number comparison use ‘meta\_value\_num’.*
```
$args = array(
'meta_key' => 'price',
'meta_value' => '22',
'meta_compare' => '<=',
'post_type' => 'product'
);
$query = new WP_Query( $args );
```
Display posts with a custom field value of zero (0), regardless of the custom field key:
```
$args = array(
'meta_value' => '_wp_zero_value'
);
$query = new WP_Query( $args );
```
**Display posts from a single custom field:**
```
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'color',
'value' => 'blue',
'compare' => 'NOT LIKE',
),
),
);
$query = new WP_Query( $args );
```
(Note that meta\_query expects nested arrays, even if you only have one query.)
**Display posts from several custom fields:**
```
$args = array(
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'color',
'value' => 'blue',
'compare' => 'NOT LIKE',
),
array(
'key' => 'price',
'value' => array( 20, 100 ),
'type' => 'numeric',
'compare' => 'BETWEEN',
),
),
);
$query = new WP_Query( $args );
```
**Display posts that have meta key ‘color’ NOT LIKE value ‘blue’ OR meta key ‘price’ with values BETWEEN 20 and 100:**
```
$args = array(
'post_type' => 'product',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'color',
'value' => 'blue',
'compare' => 'NOT LIKE',
),
array(
'key' => 'price',
'value' => array( 20, 100 ),
'type' => 'numeric',
'compare' => 'BETWEEN',
),
),
);
$query = new WP_Query( $args );
```
The `'meta_query'` clauses can be nested in order to construct complex queries. For example, show productss where **color=orange** OR **color=red&size=small** translates to the following:
```
$args = array(
'post_type' => 'product',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'color',
'value' => 'orange',
'compare' => '=',
),
array(
'relation' => 'AND',
array(
'key' => 'color',
'value' => 'red',
'compare' => '=',
),
array(
'key' => 'size',
'value' => 'small',
'compare' => '=',
),
),
),
);
$query = new WP_Query( $args );
```
Show posts if user has the appropriate capability
* **`perm`** (*string*) – User permission.
**Display published and private posts, if the user has the appropriate capability:**
```
$args = array(
'post_status' => array( 'publish', 'private' ),
'perm' => 'readable',
);
$query = new WP_Query( $args );
```
Used with the attachments post type.
* **`post_mime_type`** (*string/array*) – Allowed mime types.
**Get attachments that are *gif* images:**
Get gif images and remember that by default the attachment’s post\_status is set to **inherit**.
```
$args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => 'image/gif',
);
$query = new WP_Query( $args );
```
**Get attachments that are not images:**
To exclude certain mime types you first need to get all mime types using [get\_allowed\_mime\_types()](../functions/get_allowed_mime_types) and run a difference between arrays of what you want and the allowed mime types with `[array\_diff()](http://php.net/manual/en/function.array-diff.php)`.
```
$unsupported_mimes = array( 'image/jpeg', 'image/gif', 'image/png', 'image/bmp', 'image/tiff', 'image/x-icon' );
$all_mimes = get_allowed_mime_types();
$accepted_mimes = array_diff( $all_mimes, $unsupported_mimes );
$args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => $accepted_mimes,
);
$query = new WP_Query( $query_args );
```
Stop the data retrieved from being added to the cache.
* **`cache_results`** (*boolean*) – Post information cache.
* **`update_post_meta_cache`** (*boolean*) – Post meta information cache.
* **`update_post_term_cache`** (*boolean*) – Post term information cache.
**Show Posts without adding post information to the cache**
Display 50 posts, but don’t add post information to the cache:
```
$args = array(
'posts_per_page' => 50,
'cache_results' => false
);
$query = new WP_Query( $args );
```
**Show Posts without adding post meta information to the cache**
Display 50 posts, but don’t add post meta information to the cache:
```
$args = array(
'posts_per_page' => 50,
'update_post_meta_cache' => false
);
$query = new WP_Query( $args );
```
**Show Posts without adding post term information to the cache**
Display 50 posts, but don’t add post term information to the cache:
```
$args = array(
'posts_per_page' => 50,
'update_post_term_cache' => false
);
$query = new WP_Query( $args );
```
In general usage you should not need to use these, adding to the cache is the right thing to do, however they may be useful in specific circumstances. An example of such circumstances might be when using a [WP\_Query](wp_query) to retrieve a list of post titles and URLs to be displayed, but in which no other information about the post will be used and the taxonomy and meta data won’t be needed. By not loading this information, you can save time from the extra unnecessary SQL queries.
**Note**: If a persistent object cache backend (such as memcached) is used, these flags are set to false by default since there is no need to update the cache every page load when a persistent cache exists.
Set return values.
* **`fields`** (*string*) – Which fields to return. There are three options:
+ **`'all'`** – Return all fields (default).
+ **`'ids'`** – Return an array of post IDs.
+ **`'id=>parent'`** – Return an array of stdClass objects with ID and post\_parent properties.
Passing anything else will return all fields (default) – an array of post objects.
* [\_\_call](wp_query/__call) — Make private/protected methods readable for backward compatibility.
* [\_\_construct](wp_query/__construct) — Constructor.
* [\_\_get](wp_query/__get) — Make private properties readable for backward compatibility.
* [\_\_isset](wp_query/__isset) — Make private properties checkable for backward compatibility.
* [fill\_query\_vars](wp_query/fill_query_vars) — Fills in the query variables, which do not exist within the parameter.
* [generate\_cache\_key](wp_query/generate_cache_key) — Generate cache key.
* [generate\_postdata](wp_query/generate_postdata) — Generate post data.
* [get](wp_query/get) — Retrieves the value of a query variable.
* [get\_posts](wp_query/get_posts) — Retrieves an array of posts based on query variables.
* [get\_queried\_object](wp_query/get_queried_object) — Retrieves the currently queried object.
* [get\_queried\_object\_id](wp_query/get_queried_object_id) — Retrieves the ID of the currently queried object.
* [get\_search\_stopwords](wp_query/get_search_stopwords) — Retrieve stopwords used when parsing search terms.
* [have\_comments](wp_query/have_comments) — Whether there are more comments available.
* [have\_posts](wp_query/have_posts) — Determines whether there are more posts available in the loop.
* [init](wp_query/init) — Initiates object properties and sets default values.
* [init\_query\_flags](wp_query/init_query_flags) — Resets query flags to false.
* [is\_404](wp_query/is_404) — Is the query a 404 (returns no results)?
* [is\_archive](wp_query/is_archive) — Is the query for an existing archive page?
* [is\_attachment](wp_query/is_attachment) — Is the query for an existing attachment page?
* [is\_author](wp_query/is_author) — Is the query for an existing author archive page?
* [is\_category](wp_query/is_category) — Is the query for an existing category archive page?
* [is\_comment\_feed](wp_query/is_comment_feed) — Is the query for a comments feed?
* [is\_comments\_popup](wp_query/is_comments_popup) — Whether the current URL is within the comments popup window. — deprecated
* [is\_date](wp_query/is_date) — Is the query for an existing date archive?
* [is\_day](wp_query/is_day) — Is the query for an existing day archive?
* [is\_embed](wp_query/is_embed) — Is the query for an embedded post?
* [is\_favicon](wp_query/is_favicon) — Is the query for the favicon.ico file?
* [is\_feed](wp_query/is_feed) — Is the query for a feed?
* [is\_front\_page](wp_query/is_front_page) — Is the query for the front page of the site?
* [is\_home](wp_query/is_home) — Is the query for the blog homepage?
* [is\_main\_query](wp_query/is_main_query) — Is the query the main query?
* [is\_month](wp_query/is_month) — Is the query for an existing month archive?
* [is\_page](wp_query/is_page) — Is the query for an existing single page?
* [is\_paged](wp_query/is_paged) — Is the query for a paged result and not for the first page?
* [is\_post\_type\_archive](wp_query/is_post_type_archive) — Is the query for an existing post type archive page?
* [is\_preview](wp_query/is_preview) — Is the query for a post or page preview?
* [is\_privacy\_policy](wp_query/is_privacy_policy) — Is the query for the Privacy Policy page?
* [is\_robots](wp_query/is_robots) — Is the query for the robots.txt file?
* [is\_search](wp_query/is_search) — Is the query for a search?
* [is\_single](wp_query/is_single) — Is the query for an existing single post?
* [is\_singular](wp_query/is_singular) — Is the query for an existing single post of any post type (post, attachment, page, custom post types)?
* [is\_tag](wp_query/is_tag) — Is the query for an existing tag archive page?
* [is\_tax](wp_query/is_tax) — Is the query for an existing custom taxonomy archive page?
* [is\_time](wp_query/is_time) — Is the query for a specific time?
* [is\_trackback](wp_query/is_trackback) — Is the query for a trackback endpoint call?
* [is\_year](wp_query/is_year) — Is the query for an existing year archive?
* [lazyload\_comment\_meta](wp_query/lazyload_comment_meta) — Lazyload comment meta for comments in the loop. — deprecated
* [lazyload\_term\_meta](wp_query/lazyload_term_meta) — Lazyload term meta for posts in the loop. — deprecated
* [next\_comment](wp_query/next_comment) — Iterate current comment index and return WP\_Comment object.
* [next\_post](wp_query/next_post) — Set up the next post and iterate current post index.
* [parse\_order](wp_query/parse_order) — Parse an 'order' query variable and cast it to ASC or DESC as necessary.
* [parse\_orderby](wp_query/parse_orderby) — Converts the given orderby alias (if allowed) to a properly-prefixed value.
* [parse\_query](wp_query/parse_query) — Parse a query string and set query type booleans.
* [parse\_query\_vars](wp_query/parse_query_vars) — Reparse the query vars.
* [parse\_search](wp_query/parse_search) — Generates SQL for the WHERE clause based on passed search terms.
* [parse\_search\_order](wp_query/parse_search_order) — Generates SQL for the ORDER BY condition based on passed search terms.
* [parse\_search\_terms](wp_query/parse_search_terms) — Check if the terms are suitable for searching.
* [parse\_tax\_query](wp_query/parse_tax_query) — Parses various taxonomy related query vars.
* [query](wp_query/query) — Sets up the WordPress query by parsing query string.
* [reset\_postdata](wp_query/reset_postdata) — After looping through a nested query, this function restores the $post global to the current post in this query.
* [rewind\_comments](wp_query/rewind_comments) — Rewind the comments, resets the comment index and comment to first.
* [rewind\_posts](wp_query/rewind_posts) — Rewind the posts and reset post index.
* [set](wp_query/set) — Sets the value of a query variable.
* [set\_404](wp_query/set_404) — Sets the 404 property and saves whether query is feed.
* [set\_found\_posts](wp_query/set_found_posts) — Set up the amount of found posts and the number of pages (if limit clause was used) for the current query.
* [setup\_postdata](wp_query/setup_postdata) — Set up global post data.
* [the\_comment](wp_query/the_comment) — Sets up the current comment.
* [the\_post](wp_query/the_post) — Sets up the current post.
File: `wp-includes/class-wp-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-query.php/)
```
class WP_Query {
/**
* Query vars set by the user.
*
* @since 1.5.0
* @var array
*/
public $query;
/**
* Query vars, after parsing.
*
* @since 1.5.0
* @var array
*/
public $query_vars = array();
/**
* Taxonomy query, as passed to get_tax_sql().
*
* @since 3.1.0
* @var WP_Tax_Query A taxonomy query instance.
*/
public $tax_query;
/**
* Metadata query container.
*
* @since 3.2.0
* @var WP_Meta_Query A meta query instance.
*/
public $meta_query = false;
/**
* Date query container.
*
* @since 3.7.0
* @var WP_Date_Query A date query instance.
*/
public $date_query = false;
/**
* Holds the data for a single object that is queried.
*
* Holds the contents of a post, page, category, attachment.
*
* @since 1.5.0
* @var WP_Term|WP_Post_Type|WP_Post|WP_User|null
*/
public $queried_object;
/**
* The ID of the queried object.
*
* @since 1.5.0
* @var int
*/
public $queried_object_id;
/**
* SQL for the database query.
*
* @since 2.0.1
* @var string
*/
public $request;
/**
* Array of post objects or post IDs.
*
* @since 1.5.0
* @var WP_Post[]|int[]
*/
public $posts;
/**
* The number of posts for the current query.
*
* @since 1.5.0
* @var int
*/
public $post_count = 0;
/**
* Index of the current item in the loop.
*
* @since 1.5.0
* @var int
*/
public $current_post = -1;
/**
* Whether the loop has started and the caller is in the loop.
*
* @since 2.0.0
* @var bool
*/
public $in_the_loop = false;
/**
* The current post.
*
* This property does not get populated when the `fields` argument is set to
* `ids` or `id=>parent`.
*
* @since 1.5.0
* @var WP_Post|null
*/
public $post;
/**
* The list of comments for current post.
*
* @since 2.2.0
* @var WP_Comment[]
*/
public $comments;
/**
* The number of comments for the posts.
*
* @since 2.2.0
* @var int
*/
public $comment_count = 0;
/**
* The index of the comment in the comment loop.
*
* @since 2.2.0
* @var int
*/
public $current_comment = -1;
/**
* Current comment object.
*
* @since 2.2.0
* @var WP_Comment
*/
public $comment;
/**
* The number of found posts for the current query.
*
* If limit clause was not used, equals $post_count.
*
* @since 2.1.0
* @var int
*/
public $found_posts = 0;
/**
* The number of pages.
*
* @since 2.1.0
* @var int
*/
public $max_num_pages = 0;
/**
* The number of comment pages.
*
* @since 2.7.0
* @var int
*/
public $max_num_comment_pages = 0;
/**
* Signifies whether the current query is for a single post.
*
* @since 1.5.0
* @var bool
*/
public $is_single = false;
/**
* Signifies whether the current query is for a preview.
*
* @since 2.0.0
* @var bool
*/
public $is_preview = false;
/**
* Signifies whether the current query is for a page.
*
* @since 1.5.0
* @var bool
*/
public $is_page = false;
/**
* Signifies whether the current query is for an archive.
*
* @since 1.5.0
* @var bool
*/
public $is_archive = false;
/**
* Signifies whether the current query is for a date archive.
*
* @since 1.5.0
* @var bool
*/
public $is_date = false;
/**
* Signifies whether the current query is for a year archive.
*
* @since 1.5.0
* @var bool
*/
public $is_year = false;
/**
* Signifies whether the current query is for a month archive.
*
* @since 1.5.0
* @var bool
*/
public $is_month = false;
/**
* Signifies whether the current query is for a day archive.
*
* @since 1.5.0
* @var bool
*/
public $is_day = false;
/**
* Signifies whether the current query is for a specific time.
*
* @since 1.5.0
* @var bool
*/
public $is_time = false;
/**
* Signifies whether the current query is for an author archive.
*
* @since 1.5.0
* @var bool
*/
public $is_author = false;
/**
* Signifies whether the current query is for a category archive.
*
* @since 1.5.0
* @var bool
*/
public $is_category = false;
/**
* Signifies whether the current query is for a tag archive.
*
* @since 2.3.0
* @var bool
*/
public $is_tag = false;
/**
* Signifies whether the current query is for a taxonomy archive.
*
* @since 2.5.0
* @var bool
*/
public $is_tax = false;
/**
* Signifies whether the current query is for a search.
*
* @since 1.5.0
* @var bool
*/
public $is_search = false;
/**
* Signifies whether the current query is for a feed.
*
* @since 1.5.0
* @var bool
*/
public $is_feed = false;
/**
* Signifies whether the current query is for a comment feed.
*
* @since 2.2.0
* @var bool
*/
public $is_comment_feed = false;
/**
* Signifies whether the current query is for trackback endpoint call.
*
* @since 1.5.0
* @var bool
*/
public $is_trackback = false;
/**
* Signifies whether the current query is for the site homepage.
*
* @since 1.5.0
* @var bool
*/
public $is_home = false;
/**
* Signifies whether the current query is for the Privacy Policy page.
*
* @since 5.2.0
* @var bool
*/
public $is_privacy_policy = false;
/**
* Signifies whether the current query couldn't find anything.
*
* @since 1.5.0
* @var bool
*/
public $is_404 = false;
/**
* Signifies whether the current query is for an embed.
*
* @since 4.4.0
* @var bool
*/
public $is_embed = false;
/**
* Signifies whether the current query is for a paged result and not for the first page.
*
* @since 1.5.0
* @var bool
*/
public $is_paged = false;
/**
* Signifies whether the current query is for an administrative interface page.
*
* @since 1.5.0
* @var bool
*/
public $is_admin = false;
/**
* Signifies whether the current query is for an attachment page.
*
* @since 2.0.0
* @var bool
*/
public $is_attachment = false;
/**
* Signifies whether the current query is for an existing single post of any post type
* (post, attachment, page, custom post types).
*
* @since 2.1.0
* @var bool
*/
public $is_singular = false;
/**
* Signifies whether the current query is for the robots.txt file.
*
* @since 2.1.0
* @var bool
*/
public $is_robots = false;
/**
* Signifies whether the current query is for the favicon.ico file.
*
* @since 5.4.0
* @var bool
*/
public $is_favicon = false;
/**
* Signifies whether the current query is for the page_for_posts page.
*
* Basically, the homepage if the option isn't set for the static homepage.
*
* @since 2.1.0
* @var bool
*/
public $is_posts_page = false;
/**
* Signifies whether the current query is for a post type archive.
*
* @since 3.1.0
* @var bool
*/
public $is_post_type_archive = false;
/**
* Stores the ->query_vars state like md5(serialize( $this->query_vars ) ) so we know
* whether we have to re-parse because something has changed
*
* @since 3.1.0
* @var bool|string
*/
private $query_vars_hash = false;
/**
* Whether query vars have changed since the initial parse_query() call. Used to catch modifications to query vars made
* via pre_get_posts hooks.
*
* @since 3.1.1
*/
private $query_vars_changed = true;
/**
* Set if post thumbnails are cached
*
* @since 3.2.0
* @var bool
*/
public $thumbnails_cached = false;
/**
* Controls whether an attachment query should include filenames or not.
*
* @since 6.0.3
* @var bool
*/
protected $allow_query_attachment_by_filename = false;
/**
* Cached list of search stopwords.
*
* @since 3.7.0
* @var array
*/
private $stopwords;
private $compat_fields = array( 'query_vars_hash', 'query_vars_changed' );
private $compat_methods = array( 'init_query_flags', 'parse_tax_query' );
/**
* Resets query flags to false.
*
* The query flags are what page info WordPress was able to figure out.
*
* @since 2.0.0
*/
private function init_query_flags() {
$this->is_single = false;
$this->is_preview = false;
$this->is_page = false;
$this->is_archive = false;
$this->is_date = false;
$this->is_year = false;
$this->is_month = false;
$this->is_day = false;
$this->is_time = false;
$this->is_author = false;
$this->is_category = false;
$this->is_tag = false;
$this->is_tax = false;
$this->is_search = false;
$this->is_feed = false;
$this->is_comment_feed = false;
$this->is_trackback = false;
$this->is_home = false;
$this->is_privacy_policy = false;
$this->is_404 = false;
$this->is_paged = false;
$this->is_admin = false;
$this->is_attachment = false;
$this->is_singular = false;
$this->is_robots = false;
$this->is_favicon = false;
$this->is_posts_page = false;
$this->is_post_type_archive = false;
}
/**
* Initiates object properties and sets default values.
*
* @since 1.5.0
*/
public function init() {
unset( $this->posts );
unset( $this->query );
$this->query_vars = array();
unset( $this->queried_object );
unset( $this->queried_object_id );
$this->post_count = 0;
$this->current_post = -1;
$this->in_the_loop = false;
unset( $this->request );
unset( $this->post );
unset( $this->comments );
unset( $this->comment );
$this->comment_count = 0;
$this->current_comment = -1;
$this->found_posts = 0;
$this->max_num_pages = 0;
$this->max_num_comment_pages = 0;
$this->init_query_flags();
}
/**
* Reparse the query vars.
*
* @since 1.5.0
*/
public function parse_query_vars() {
$this->parse_query();
}
/**
* Fills in the query variables, which do not exist within the parameter.
*
* @since 2.1.0
* @since 4.5.0 Removed the `comments_popup` public query variable.
*
* @param array $query_vars Defined query variables.
* @return array Complete query variables with undefined ones filled in empty.
*/
public function fill_query_vars( $query_vars ) {
$keys = array(
'error',
'm',
'p',
'post_parent',
'subpost',
'subpost_id',
'attachment',
'attachment_id',
'name',
'pagename',
'page_id',
'second',
'minute',
'hour',
'day',
'monthnum',
'year',
'w',
'category_name',
'tag',
'cat',
'tag_id',
'author',
'author_name',
'feed',
'tb',
'paged',
'meta_key',
'meta_value',
'preview',
's',
'sentence',
'title',
'fields',
'menu_order',
'embed',
);
foreach ( $keys as $key ) {
if ( ! isset( $query_vars[ $key ] ) ) {
$query_vars[ $key ] = '';
}
}
$array_keys = array(
'category__in',
'category__not_in',
'category__and',
'post__in',
'post__not_in',
'post_name__in',
'tag__in',
'tag__not_in',
'tag__and',
'tag_slug__in',
'tag_slug__and',
'post_parent__in',
'post_parent__not_in',
'author__in',
'author__not_in',
);
foreach ( $array_keys as $key ) {
if ( ! isset( $query_vars[ $key ] ) ) {
$query_vars[ $key ] = array();
}
}
return $query_vars;
}
/**
* Parse a query string and set query type booleans.
*
* @since 1.5.0
* @since 4.2.0 Introduced the ability to order by specific clauses of a `$meta_query`, by passing the clause's
* array key to `$orderby`.
* @since 4.4.0 Introduced `$post_name__in` and `$title` parameters. `$s` was updated to support excluded
* search terms, by prepending a hyphen.
* @since 4.5.0 Removed the `$comments_popup` parameter.
* Introduced the `$comment_status` and `$ping_status` parameters.
* Introduced `RAND(x)` syntax for `$orderby`, which allows an integer seed value to random sorts.
* @since 4.6.0 Added 'post_name__in' support for `$orderby`. Introduced the `$lazy_load_term_meta` argument.
* @since 4.9.0 Introduced the `$comment_count` parameter.
* @since 5.1.0 Introduced the `$meta_compare_key` parameter.
* @since 5.3.0 Introduced the `$meta_type_key` parameter.
* @since 6.1.0 Introduced the `$update_menu_item_cache` parameter.
*
* @param string|array $query {
* Optional. Array or string of Query parameters.
*
* @type int $attachment_id Attachment post ID. Used for 'attachment' post_type.
* @type int|string $author Author ID, or comma-separated list of IDs.
* @type string $author_name User 'user_nicename'.
* @type int[] $author__in An array of author IDs to query from.
* @type int[] $author__not_in An array of author IDs not to query from.
* @type bool $cache_results Whether to cache post information. Default true.
* @type int|string $cat Category ID or comma-separated list of IDs (this or any children).
* @type int[] $category__and An array of category IDs (AND in).
* @type int[] $category__in An array of category IDs (OR in, no children).
* @type int[] $category__not_in An array of category IDs (NOT in).
* @type string $category_name Use category slug (not name, this or any children).
* @type array|int $comment_count Filter results by comment count. Provide an integer to match
* comment count exactly. Provide an array with integer 'value'
* and 'compare' operator ('=', '!=', '>', '>=', '<', '<=' ) to
* compare against comment_count in a specific way.
* @type string $comment_status Comment status.
* @type int $comments_per_page The number of comments to return per page.
* Default 'comments_per_page' option.
* @type array $date_query An associative array of WP_Date_Query arguments.
* See WP_Date_Query::__construct().
* @type int $day Day of the month. Default empty. Accepts numbers 1-31.
* @type bool $exact Whether to search by exact keyword. Default false.
* @type string $fields Post fields to query for. Accepts:
* - '' Returns an array of complete post objects (`WP_Post[]`).
* - 'ids' Returns an array of post IDs (`int[]`).
* - 'id=>parent' Returns an associative array of parent post IDs,
* keyed by post ID (`int[]`).
* Default ''.
* @type int $hour Hour of the day. Default empty. Accepts numbers 0-23.
* @type int|bool $ignore_sticky_posts Whether to ignore sticky posts or not. Setting this to false
* excludes stickies from 'post__in'. Accepts 1|true, 0|false.
* Default false.
* @type int $m Combination YearMonth. Accepts any four-digit year and month
* numbers 01-12. 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 $menu_order The menu order of the posts.
* @type int $minute Minute of the hour. Default empty. Accepts numbers 0-59.
* @type int $monthnum The two-digit month. Default empty. Accepts numbers 1-12.
* @type string $name Post slug.
* @type bool $nopaging Show all posts (true) or paginate (false). Default false.
* @type bool $no_found_rows Whether to skip counting the total rows found. Enabling can improve
* performance. Default false.
* @type int $offset The number of posts to offset before retrieval.
* @type string $order Designates ascending or descending order of posts. Default 'DESC'.
* Accepts 'ASC', 'DESC'.
* @type string|array $orderby Sort retrieved posts by parameter. One or more options may be passed.
* To use 'meta_value', or 'meta_value_num', 'meta_key=keyname' must be
* also be defined. To sort by a specific `$meta_query` clause, use that
* clause's array key. Accepts:
* - 'none'
* - 'name'
* - 'author'
* - 'date'
* - 'title'
* - 'modified'
* - 'menu_order'
* - 'parent'
* - 'ID'
* - 'rand'
* - 'relevance'
* - 'RAND(x)' (where 'x' is an integer seed value)
* - 'comment_count'
* - 'meta_value'
* - 'meta_value_num'
* - 'post__in'
* - 'post_name__in'
* - 'post_parent__in'
* - The array keys of `$meta_query`.
* Default is 'date', except when a search is being performed, when
* the default is 'relevance'.
* @type int $p Post ID.
* @type int $page Show the number of posts that would show up on page X of a
* static front page.
* @type int $paged The number of the current page.
* @type int $page_id Page ID.
* @type string $pagename Page slug.
* @type string $perm Show posts if user has the appropriate capability.
* @type string $ping_status Ping status.
* @type int[] $post__in An array of post IDs to retrieve, sticky posts will be included.
* @type int[] $post__not_in An array of post IDs not to retrieve. Note: a string of comma-
* separated IDs will NOT work.
* @type string $post_mime_type The mime type of the post. Used for 'attachment' post_type.
* @type string[] $post_name__in An array of post slugs that results must match.
* @type int $post_parent Page ID to retrieve child pages for. Use 0 to only retrieve
* top-level pages.
* @type int[] $post_parent__in An array containing parent page IDs to query child pages from.
* @type int[] $post_parent__not_in An array containing parent page IDs not to query child pages from.
* @type string|string[] $post_type A post type slug (string) or array of post type slugs.
* Default 'any' if using 'tax_query'.
* @type string|string[] $post_status A post status (string) or array of post statuses.
* @type int $posts_per_page The number of posts to query for. Use -1 to request all posts.
* @type int $posts_per_archive_page The number of posts to query for by archive page. Overrides
* 'posts_per_page' when is_archive(), or is_search() are true.
* @type string $s Search keyword(s). Prepending a term with a hyphen will
* exclude posts matching that term. Eg, 'pillow -sofa' will
* return posts containing 'pillow' but not 'sofa'. The
* character used for exclusion can be modified using the
* the 'wp_query_search_exclusion_prefix' filter.
* @type int $second Second of the minute. Default empty. Accepts numbers 0-59.
* @type bool $sentence Whether to search by phrase. Default false.
* @type bool $suppress_filters Whether to suppress filters. Default false.
* @type string $tag Tag slug. Comma-separated (either), Plus-separated (all).
* @type int[] $tag__and An array of tag IDs (AND in).
* @type int[] $tag__in An array of tag IDs (OR in).
* @type int[] $tag__not_in An array of tag IDs (NOT in).
* @type int $tag_id Tag id or comma-separated list of IDs.
* @type string[] $tag_slug__and An array of tag slugs (AND in).
* @type string[] $tag_slug__in An array of tag slugs (OR in). unless 'ignore_sticky_posts' is
* true. Note: a string of comma-separated IDs will NOT work.
* @type array $tax_query An associative array of WP_Tax_Query arguments.
* See WP_Tax_Query::__construct().
* @type string $title Post title.
* @type bool $update_post_meta_cache Whether to update the post meta cache. Default true.
* @type bool $update_post_term_cache Whether to update the post term cache. Default true.
* @type bool $update_menu_item_cache Whether to update the menu item cache. Default false.
* @type bool $lazy_load_term_meta Whether to lazy-load term meta. Setting to false will
* disable cache priming for term meta, so that each
* get_term_meta() call will hit the database.
* Defaults to the value of `$update_post_term_cache`.
* @type int $w The week number of the year. Default empty. Accepts numbers 0-53.
* @type int $year The four-digit year. Default empty. Accepts any four-digit year.
* }
*/
public function parse_query( $query = '' ) {
if ( ! empty( $query ) ) {
$this->init();
$this->query = wp_parse_args( $query );
$this->query_vars = $this->query;
} elseif ( ! isset( $this->query ) ) {
$this->query = $this->query_vars;
}
$this->query_vars = $this->fill_query_vars( $this->query_vars );
$qv = &$this->query_vars;
$this->query_vars_changed = true;
if ( ! empty( $qv['robots'] ) ) {
$this->is_robots = true;
} elseif ( ! empty( $qv['favicon'] ) ) {
$this->is_favicon = true;
}
if ( ! is_scalar( $qv['p'] ) || (int) $qv['p'] < 0 ) {
$qv['p'] = 0;
$qv['error'] = '404';
} else {
$qv['p'] = (int) $qv['p'];
}
$qv['page_id'] = is_scalar( $qv['page_id'] ) ? absint( $qv['page_id'] ) : 0;
$qv['year'] = is_scalar( $qv['year'] ) ? absint( $qv['year'] ) : 0;
$qv['monthnum'] = is_scalar( $qv['monthnum'] ) ? absint( $qv['monthnum'] ) : 0;
$qv['day'] = is_scalar( $qv['day'] ) ? absint( $qv['day'] ) : 0;
$qv['w'] = is_scalar( $qv['w'] ) ? absint( $qv['w'] ) : 0;
$qv['m'] = is_scalar( $qv['m'] ) ? preg_replace( '|[^0-9]|', '', $qv['m'] ) : '';
$qv['paged'] = is_scalar( $qv['paged'] ) ? absint( $qv['paged'] ) : 0;
$qv['cat'] = preg_replace( '|[^0-9,-]|', '', $qv['cat'] ); // Array or comma-separated list of positive or negative integers.
$qv['author'] = is_scalar( $qv['author'] ) ? preg_replace( '|[^0-9,-]|', '', $qv['author'] ) : ''; // Comma-separated list of positive or negative integers.
$qv['pagename'] = is_scalar( $qv['pagename'] ) ? trim( $qv['pagename'] ) : '';
$qv['name'] = is_scalar( $qv['name'] ) ? trim( $qv['name'] ) : '';
$qv['title'] = is_scalar( $qv['title'] ) ? trim( $qv['title'] ) : '';
if ( is_scalar( $qv['hour'] ) && '' !== $qv['hour'] ) {
$qv['hour'] = absint( $qv['hour'] );
} else {
$qv['hour'] = '';
}
if ( is_scalar( $qv['minute'] ) && '' !== $qv['minute'] ) {
$qv['minute'] = absint( $qv['minute'] );
} else {
$qv['minute'] = '';
}
if ( is_scalar( $qv['second'] ) && '' !== $qv['second'] ) {
$qv['second'] = absint( $qv['second'] );
} else {
$qv['second'] = '';
}
if ( is_scalar( $qv['menu_order'] ) && '' !== $qv['menu_order'] ) {
$qv['menu_order'] = absint( $qv['menu_order'] );
} else {
$qv['menu_order'] = '';
}
// Fairly large, potentially too large, upper bound for search string lengths.
if ( ! is_scalar( $qv['s'] ) || ( ! empty( $qv['s'] ) && strlen( $qv['s'] ) > 1600 ) ) {
$qv['s'] = '';
}
// Compat. Map subpost to attachment.
if ( is_scalar( $qv['subpost'] ) && '' != $qv['subpost'] ) {
$qv['attachment'] = $qv['subpost'];
}
if ( is_scalar( $qv['subpost_id'] ) && '' != $qv['subpost_id'] ) {
$qv['attachment_id'] = $qv['subpost_id'];
}
$qv['attachment_id'] = is_scalar( $qv['attachment_id'] ) ? absint( $qv['attachment_id'] ) : 0;
if ( ( '' !== $qv['attachment'] ) || ! empty( $qv['attachment_id'] ) ) {
$this->is_single = true;
$this->is_attachment = true;
} elseif ( '' !== $qv['name'] ) {
$this->is_single = true;
} elseif ( $qv['p'] ) {
$this->is_single = true;
} elseif ( '' !== $qv['pagename'] || ! empty( $qv['page_id'] ) ) {
$this->is_page = true;
$this->is_single = false;
} else {
// Look for archive queries. Dates, categories, authors, search, post type archives.
if ( isset( $this->query['s'] ) ) {
$this->is_search = true;
}
if ( '' !== $qv['second'] ) {
$this->is_time = true;
$this->is_date = true;
}
if ( '' !== $qv['minute'] ) {
$this->is_time = true;
$this->is_date = true;
}
if ( '' !== $qv['hour'] ) {
$this->is_time = true;
$this->is_date = true;
}
if ( $qv['day'] ) {
if ( ! $this->is_date ) {
$date = sprintf( '%04d-%02d-%02d', $qv['year'], $qv['monthnum'], $qv['day'] );
if ( $qv['monthnum'] && $qv['year'] && ! wp_checkdate( $qv['monthnum'], $qv['day'], $qv['year'], $date ) ) {
$qv['error'] = '404';
} else {
$this->is_day = true;
$this->is_date = true;
}
}
}
if ( $qv['monthnum'] ) {
if ( ! $this->is_date ) {
if ( 12 < $qv['monthnum'] ) {
$qv['error'] = '404';
} else {
$this->is_month = true;
$this->is_date = true;
}
}
}
if ( $qv['year'] ) {
if ( ! $this->is_date ) {
$this->is_year = true;
$this->is_date = true;
}
}
if ( $qv['m'] ) {
$this->is_date = true;
if ( strlen( $qv['m'] ) > 9 ) {
$this->is_time = true;
} elseif ( strlen( $qv['m'] ) > 7 ) {
$this->is_day = true;
} elseif ( strlen( $qv['m'] ) > 5 ) {
$this->is_month = true;
} else {
$this->is_year = true;
}
}
if ( $qv['w'] ) {
$this->is_date = true;
}
$this->query_vars_hash = false;
$this->parse_tax_query( $qv );
foreach ( $this->tax_query->queries as $tax_query ) {
if ( ! is_array( $tax_query ) ) {
continue;
}
if ( isset( $tax_query['operator'] ) && 'NOT IN' !== $tax_query['operator'] ) {
switch ( $tax_query['taxonomy'] ) {
case 'category':
$this->is_category = true;
break;
case 'post_tag':
$this->is_tag = true;
break;
default:
$this->is_tax = true;
}
}
}
unset( $tax_query );
if ( empty( $qv['author'] ) || ( '0' == $qv['author'] ) ) {
$this->is_author = false;
} else {
$this->is_author = true;
}
if ( '' !== $qv['author_name'] ) {
$this->is_author = true;
}
if ( ! empty( $qv['post_type'] ) && ! is_array( $qv['post_type'] ) ) {
$post_type_obj = get_post_type_object( $qv['post_type'] );
if ( ! empty( $post_type_obj->has_archive ) ) {
$this->is_post_type_archive = true;
}
}
if ( $this->is_post_type_archive || $this->is_date || $this->is_author || $this->is_category || $this->is_tag || $this->is_tax ) {
$this->is_archive = true;
}
}
if ( '' != $qv['feed'] ) {
$this->is_feed = true;
}
if ( '' != $qv['embed'] ) {
$this->is_embed = true;
}
if ( '' != $qv['tb'] ) {
$this->is_trackback = true;
}
if ( '' != $qv['paged'] && ( (int) $qv['paged'] > 1 ) ) {
$this->is_paged = true;
}
// If we're previewing inside the write screen.
if ( '' != $qv['preview'] ) {
$this->is_preview = true;
}
if ( is_admin() ) {
$this->is_admin = true;
}
if ( false !== strpos( $qv['feed'], 'comments-' ) ) {
$qv['feed'] = str_replace( 'comments-', '', $qv['feed'] );
$qv['withcomments'] = 1;
}
$this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
if ( $this->is_feed && ( ! empty( $qv['withcomments'] ) || ( empty( $qv['withoutcomments'] ) && $this->is_singular ) ) ) {
$this->is_comment_feed = true;
}
if ( ! ( $this->is_singular || $this->is_archive || $this->is_search || $this->is_feed
|| ( defined( 'REST_REQUEST' ) && REST_REQUEST && $this->is_main_query() )
|| $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_robots || $this->is_favicon ) ) {
$this->is_home = true;
}
// Correct `is_*` for 'page_on_front' and 'page_for_posts'.
if ( $this->is_home && 'page' === get_option( 'show_on_front' ) && get_option( 'page_on_front' ) ) {
$_query = wp_parse_args( $this->query );
// 'pagename' can be set and empty depending on matched rewrite rules. Ignore an empty 'pagename'.
if ( isset( $_query['pagename'] ) && '' === $_query['pagename'] ) {
unset( $_query['pagename'] );
}
unset( $_query['embed'] );
if ( empty( $_query ) || ! array_diff( array_keys( $_query ), array( 'preview', 'page', 'paged', 'cpage' ) ) ) {
$this->is_page = true;
$this->is_home = false;
$qv['page_id'] = get_option( 'page_on_front' );
// Correct <!--nextpage--> for 'page_on_front'.
if ( ! empty( $qv['paged'] ) ) {
$qv['page'] = $qv['paged'];
unset( $qv['paged'] );
}
}
}
if ( '' !== $qv['pagename'] ) {
$this->queried_object = get_page_by_path( $qv['pagename'] );
if ( $this->queried_object && 'attachment' === $this->queried_object->post_type ) {
if ( preg_match( '/^[^%]*%(?:postname)%/', get_option( 'permalink_structure' ) ) ) {
// See if we also have a post with the same slug.
$post = get_page_by_path( $qv['pagename'], OBJECT, 'post' );
if ( $post ) {
$this->queried_object = $post;
$this->is_page = false;
$this->is_single = true;
}
}
}
if ( ! empty( $this->queried_object ) ) {
$this->queried_object_id = (int) $this->queried_object->ID;
} else {
unset( $this->queried_object );
}
if ( 'page' === get_option( 'show_on_front' ) && isset( $this->queried_object_id ) && get_option( 'page_for_posts' ) == $this->queried_object_id ) {
$this->is_page = false;
$this->is_home = true;
$this->is_posts_page = true;
}
if ( isset( $this->queried_object_id ) && get_option( 'wp_page_for_privacy_policy' ) == $this->queried_object_id ) {
$this->is_privacy_policy = true;
}
}
if ( $qv['page_id'] ) {
if ( 'page' === get_option( 'show_on_front' ) && get_option( 'page_for_posts' ) == $qv['page_id'] ) {
$this->is_page = false;
$this->is_home = true;
$this->is_posts_page = true;
}
if ( get_option( 'wp_page_for_privacy_policy' ) == $qv['page_id'] ) {
$this->is_privacy_policy = true;
}
}
if ( ! empty( $qv['post_type'] ) ) {
if ( is_array( $qv['post_type'] ) ) {
$qv['post_type'] = array_map( 'sanitize_key', $qv['post_type'] );
} else {
$qv['post_type'] = sanitize_key( $qv['post_type'] );
}
}
if ( ! empty( $qv['post_status'] ) ) {
if ( is_array( $qv['post_status'] ) ) {
$qv['post_status'] = array_map( 'sanitize_key', $qv['post_status'] );
} else {
$qv['post_status'] = preg_replace( '|[^a-z0-9_,-]|', '', $qv['post_status'] );
}
}
if ( $this->is_posts_page && ( ! isset( $qv['withcomments'] ) || ! $qv['withcomments'] ) ) {
$this->is_comment_feed = false;
}
$this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
// Done correcting `is_*` for 'page_on_front' and 'page_for_posts'.
if ( '404' == $qv['error'] ) {
$this->set_404();
}
$this->is_embed = $this->is_embed && ( $this->is_singular || $this->is_404 );
$this->query_vars_hash = md5( serialize( $this->query_vars ) );
$this->query_vars_changed = false;
/**
* Fires after the main query vars have been parsed.
*
* @since 1.5.0
*
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
do_action_ref_array( 'parse_query', array( &$this ) );
}
/**
* Parses various taxonomy related query vars.
*
* For BC, this method is not marked as protected. See [28987].
*
* @since 3.1.0
*
* @param array $q The query variables. Passed by reference.
*/
public function parse_tax_query( &$q ) {
if ( ! empty( $q['tax_query'] ) && is_array( $q['tax_query'] ) ) {
$tax_query = $q['tax_query'];
} else {
$tax_query = array();
}
if ( ! empty( $q['taxonomy'] ) && ! empty( $q['term'] ) ) {
$tax_query[] = array(
'taxonomy' => $q['taxonomy'],
'terms' => array( $q['term'] ),
'field' => 'slug',
);
}
foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy => $t ) {
if ( 'post_tag' === $taxonomy ) {
continue; // Handled further down in the $q['tag'] block.
}
if ( $t->query_var && ! empty( $q[ $t->query_var ] ) ) {
$tax_query_defaults = array(
'taxonomy' => $taxonomy,
'field' => 'slug',
);
if ( ! empty( $t->rewrite['hierarchical'] ) ) {
$q[ $t->query_var ] = wp_basename( $q[ $t->query_var ] );
}
$term = $q[ $t->query_var ];
if ( is_array( $term ) ) {
$term = implode( ',', $term );
}
if ( strpos( $term, '+' ) !== false ) {
$terms = preg_split( '/[+]+/', $term );
foreach ( $terms as $term ) {
$tax_query[] = array_merge(
$tax_query_defaults,
array(
'terms' => array( $term ),
)
);
}
} else {
$tax_query[] = array_merge(
$tax_query_defaults,
array(
'terms' => preg_split( '/[,]+/', $term ),
)
);
}
}
}
// If query string 'cat' is an array, implode it.
if ( is_array( $q['cat'] ) ) {
$q['cat'] = implode( ',', $q['cat'] );
}
// Category stuff.
if ( ! empty( $q['cat'] ) && ! $this->is_singular ) {
$cat_in = array();
$cat_not_in = array();
$cat_array = preg_split( '/[,\s]+/', urldecode( $q['cat'] ) );
$cat_array = array_map( 'intval', $cat_array );
$q['cat'] = implode( ',', $cat_array );
foreach ( $cat_array as $cat ) {
if ( $cat > 0 ) {
$cat_in[] = $cat;
} elseif ( $cat < 0 ) {
$cat_not_in[] = abs( $cat );
}
}
if ( ! empty( $cat_in ) ) {
$tax_query[] = array(
'taxonomy' => 'category',
'terms' => $cat_in,
'field' => 'term_id',
'include_children' => true,
);
}
if ( ! empty( $cat_not_in ) ) {
$tax_query[] = array(
'taxonomy' => 'category',
'terms' => $cat_not_in,
'field' => 'term_id',
'operator' => 'NOT IN',
'include_children' => true,
);
}
unset( $cat_array, $cat_in, $cat_not_in );
}
if ( ! empty( $q['category__and'] ) && 1 === count( (array) $q['category__and'] ) ) {
$q['category__and'] = (array) $q['category__and'];
if ( ! isset( $q['category__in'] ) ) {
$q['category__in'] = array();
}
$q['category__in'][] = absint( reset( $q['category__and'] ) );
unset( $q['category__and'] );
}
if ( ! empty( $q['category__in'] ) ) {
$q['category__in'] = array_map( 'absint', array_unique( (array) $q['category__in'] ) );
$tax_query[] = array(
'taxonomy' => 'category',
'terms' => $q['category__in'],
'field' => 'term_id',
'include_children' => false,
);
}
if ( ! empty( $q['category__not_in'] ) ) {
$q['category__not_in'] = array_map( 'absint', array_unique( (array) $q['category__not_in'] ) );
$tax_query[] = array(
'taxonomy' => 'category',
'terms' => $q['category__not_in'],
'operator' => 'NOT IN',
'include_children' => false,
);
}
if ( ! empty( $q['category__and'] ) ) {
$q['category__and'] = array_map( 'absint', array_unique( (array) $q['category__and'] ) );
$tax_query[] = array(
'taxonomy' => 'category',
'terms' => $q['category__and'],
'field' => 'term_id',
'operator' => 'AND',
'include_children' => false,
);
}
// If query string 'tag' is array, implode it.
if ( is_array( $q['tag'] ) ) {
$q['tag'] = implode( ',', $q['tag'] );
}
// Tag stuff.
if ( '' !== $q['tag'] && ! $this->is_singular && $this->query_vars_changed ) {
if ( strpos( $q['tag'], ',' ) !== false ) {
$tags = preg_split( '/[,\r\n\t ]+/', $q['tag'] );
foreach ( (array) $tags as $tag ) {
$tag = sanitize_term_field( 'slug', $tag, 0, 'post_tag', 'db' );
$q['tag_slug__in'][] = $tag;
}
} elseif ( preg_match( '/[+\r\n\t ]+/', $q['tag'] ) || ! empty( $q['cat'] ) ) {
$tags = preg_split( '/[+\r\n\t ]+/', $q['tag'] );
foreach ( (array) $tags as $tag ) {
$tag = sanitize_term_field( 'slug', $tag, 0, 'post_tag', 'db' );
$q['tag_slug__and'][] = $tag;
}
} else {
$q['tag'] = sanitize_term_field( 'slug', $q['tag'], 0, 'post_tag', 'db' );
$q['tag_slug__in'][] = $q['tag'];
}
}
if ( ! empty( $q['tag_id'] ) ) {
$q['tag_id'] = absint( $q['tag_id'] );
$tax_query[] = array(
'taxonomy' => 'post_tag',
'terms' => $q['tag_id'],
);
}
if ( ! empty( $q['tag__in'] ) ) {
$q['tag__in'] = array_map( 'absint', array_unique( (array) $q['tag__in'] ) );
$tax_query[] = array(
'taxonomy' => 'post_tag',
'terms' => $q['tag__in'],
);
}
if ( ! empty( $q['tag__not_in'] ) ) {
$q['tag__not_in'] = array_map( 'absint', array_unique( (array) $q['tag__not_in'] ) );
$tax_query[] = array(
'taxonomy' => 'post_tag',
'terms' => $q['tag__not_in'],
'operator' => 'NOT IN',
);
}
if ( ! empty( $q['tag__and'] ) ) {
$q['tag__and'] = array_map( 'absint', array_unique( (array) $q['tag__and'] ) );
$tax_query[] = array(
'taxonomy' => 'post_tag',
'terms' => $q['tag__and'],
'operator' => 'AND',
);
}
if ( ! empty( $q['tag_slug__in'] ) ) {
$q['tag_slug__in'] = array_map( 'sanitize_title_for_query', array_unique( (array) $q['tag_slug__in'] ) );
$tax_query[] = array(
'taxonomy' => 'post_tag',
'terms' => $q['tag_slug__in'],
'field' => 'slug',
);
}
if ( ! empty( $q['tag_slug__and'] ) ) {
$q['tag_slug__and'] = array_map( 'sanitize_title_for_query', array_unique( (array) $q['tag_slug__and'] ) );
$tax_query[] = array(
'taxonomy' => 'post_tag',
'terms' => $q['tag_slug__and'],
'field' => 'slug',
'operator' => 'AND',
);
}
$this->tax_query = new WP_Tax_Query( $tax_query );
/**
* Fires after taxonomy-related query vars have been parsed.
*
* @since 3.7.0
*
* @param WP_Query $query The WP_Query instance.
*/
do_action( 'parse_tax_query', $this );
}
/**
* Generates SQL for the WHERE clause based on passed search terms.
*
* @since 3.7.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param array $q Query variables.
* @return string WHERE clause.
*/
protected function parse_search( &$q ) {
global $wpdb;
$search = '';
// Added slashes screw with quote grouping when done early, so done later.
$q['s'] = stripslashes( $q['s'] );
if ( empty( $_GET['s'] ) && $this->is_main_query() ) {
$q['s'] = urldecode( $q['s'] );
}
// There are no line breaks in <input /> fields.
$q['s'] = str_replace( array( "\r", "\n" ), '', $q['s'] );
$q['search_terms_count'] = 1;
if ( ! empty( $q['sentence'] ) ) {
$q['search_terms'] = array( $q['s'] );
} else {
if ( preg_match_all( '/".*?("|$)|((?<=[\t ",+])|^)[^\t ",+]+/', $q['s'], $matches ) ) {
$q['search_terms_count'] = count( $matches[0] );
$q['search_terms'] = $this->parse_search_terms( $matches[0] );
// If the search string has only short terms or stopwords, or is 10+ terms long, match it as sentence.
if ( empty( $q['search_terms'] ) || count( $q['search_terms'] ) > 9 ) {
$q['search_terms'] = array( $q['s'] );
}
} else {
$q['search_terms'] = array( $q['s'] );
}
}
$n = ! empty( $q['exact'] ) ? '' : '%';
$searchand = '';
$q['search_orderby_title'] = array();
/**
* Filters the prefix that indicates that a search term should be excluded from results.
*
* @since 4.7.0
*
* @param string $exclusion_prefix The prefix. Default '-'. Returning
* an empty value disables exclusions.
*/
$exclusion_prefix = apply_filters( 'wp_query_search_exclusion_prefix', '-' );
foreach ( $q['search_terms'] as $term ) {
// If there is an $exclusion_prefix, terms prefixed with it should be excluded.
$exclude = $exclusion_prefix && ( substr( $term, 0, 1 ) === $exclusion_prefix );
if ( $exclude ) {
$like_op = 'NOT LIKE';
$andor_op = 'AND';
$term = substr( $term, 1 );
} else {
$like_op = 'LIKE';
$andor_op = 'OR';
}
if ( $n && ! $exclude ) {
$like = '%' . $wpdb->esc_like( $term ) . '%';
$q['search_orderby_title'][] = $wpdb->prepare( "{$wpdb->posts}.post_title LIKE %s", $like );
}
$like = $n . $wpdb->esc_like( $term ) . $n;
if ( ! empty( $this->allow_query_attachment_by_filename ) ) {
$search .= $wpdb->prepare( "{$searchand}(({$wpdb->posts}.post_title $like_op %s) $andor_op ({$wpdb->posts}.post_excerpt $like_op %s) $andor_op ({$wpdb->posts}.post_content $like_op %s) $andor_op (sq1.meta_value $like_op %s))", $like, $like, $like, $like );
} else {
$search .= $wpdb->prepare( "{$searchand}(({$wpdb->posts}.post_title $like_op %s) $andor_op ({$wpdb->posts}.post_excerpt $like_op %s) $andor_op ({$wpdb->posts}.post_content $like_op %s))", $like, $like, $like );
}
$searchand = ' AND ';
}
if ( ! empty( $search ) ) {
$search = " AND ({$search}) ";
if ( ! is_user_logged_in() ) {
$search .= " AND ({$wpdb->posts}.post_password = '') ";
}
}
return $search;
}
/**
* Check if the terms are suitable for searching.
*
* Uses an array of stopwords (terms) that are excluded from the separate
* term matching when searching for posts. The list of English stopwords is
* the approximate search engines list, and is translatable.
*
* @since 3.7.0
*
* @param string[] $terms Array of terms to check.
* @return string[] Terms that are not stopwords.
*/
protected function parse_search_terms( $terms ) {
$strtolower = function_exists( 'mb_strtolower' ) ? 'mb_strtolower' : 'strtolower';
$checked = array();
$stopwords = $this->get_search_stopwords();
foreach ( $terms as $term ) {
// Keep before/after spaces when term is for exact match.
if ( preg_match( '/^".+"$/', $term ) ) {
$term = trim( $term, "\"'" );
} else {
$term = trim( $term, "\"' " );
}
// Avoid single A-Z and single dashes.
if ( ! $term || ( 1 === strlen( $term ) && preg_match( '/^[a-z\-]$/i', $term ) ) ) {
continue;
}
if ( in_array( call_user_func( $strtolower, $term ), $stopwords, true ) ) {
continue;
}
$checked[] = $term;
}
return $checked;
}
/**
* Retrieve stopwords used when parsing search terms.
*
* @since 3.7.0
*
* @return string[] Stopwords.
*/
protected function get_search_stopwords() {
if ( isset( $this->stopwords ) ) {
return $this->stopwords;
}
/*
* translators: This is a comma-separated list of very common words that should be excluded from a search,
* like a, an, and the. These are usually called "stopwords". You should not simply translate these individual
* words into your language. Instead, look for and provide commonly accepted stopwords in your language.
*/
$words = explode(
',',
_x(
'about,an,are,as,at,be,by,com,for,from,how,in,is,it,of,on,or,that,the,this,to,was,what,when,where,who,will,with,www',
'Comma-separated list of search stopwords in your language'
)
);
$stopwords = array();
foreach ( $words as $word ) {
$word = trim( $word, "\r\n\t " );
if ( $word ) {
$stopwords[] = $word;
}
}
/**
* Filters stopwords used when parsing search terms.
*
* @since 3.7.0
*
* @param string[] $stopwords Array of stopwords.
*/
$this->stopwords = apply_filters( 'wp_search_stopwords', $stopwords );
return $this->stopwords;
}
/**
* Generates SQL for the ORDER BY condition based on passed search terms.
*
* @since 3.7.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param array $q Query variables.
* @return string ORDER BY clause.
*/
protected function parse_search_order( &$q ) {
global $wpdb;
if ( $q['search_terms_count'] > 1 ) {
$num_terms = count( $q['search_orderby_title'] );
// If the search terms contain negative queries, don't bother ordering by sentence matches.
$like = '';
if ( ! preg_match( '/(?:\s|^)\-/', $q['s'] ) ) {
$like = '%' . $wpdb->esc_like( $q['s'] ) . '%';
}
$search_orderby = '';
// Sentence match in 'post_title'.
if ( $like ) {
$search_orderby .= $wpdb->prepare( "WHEN {$wpdb->posts}.post_title LIKE %s THEN 1 ", $like );
}
// Sanity limit, sort as sentence when more than 6 terms
// (few searches are longer than 6 terms and most titles are not).
if ( $num_terms < 7 ) {
// All words in title.
$search_orderby .= 'WHEN ' . implode( ' AND ', $q['search_orderby_title'] ) . ' THEN 2 ';
// Any word in title, not needed when $num_terms == 1.
if ( $num_terms > 1 ) {
$search_orderby .= 'WHEN ' . implode( ' OR ', $q['search_orderby_title'] ) . ' THEN 3 ';
}
}
// Sentence match in 'post_content' and 'post_excerpt'.
if ( $like ) {
$search_orderby .= $wpdb->prepare( "WHEN {$wpdb->posts}.post_excerpt LIKE %s THEN 4 ", $like );
$search_orderby .= $wpdb->prepare( "WHEN {$wpdb->posts}.post_content LIKE %s THEN 5 ", $like );
}
if ( $search_orderby ) {
$search_orderby = '(CASE ' . $search_orderby . 'ELSE 6 END)';
}
} else {
// Single word or sentence search.
$search_orderby = reset( $q['search_orderby_title'] ) . ' DESC';
}
return $search_orderby;
}
/**
* Converts the given orderby alias (if allowed) to a properly-prefixed value.
*
* @since 4.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $orderby Alias for the field to order by.
* @return string|false Table-prefixed value to used in the ORDER clause. False otherwise.
*/
protected function parse_orderby( $orderby ) {
global $wpdb;
// Used to filter values.
$allowed_keys = array(
'post_name',
'post_author',
'post_date',
'post_title',
'post_modified',
'post_parent',
'post_type',
'name',
'author',
'date',
'title',
'modified',
'parent',
'type',
'ID',
'menu_order',
'comment_count',
'rand',
'post__in',
'post_parent__in',
'post_name__in',
);
$primary_meta_key = '';
$primary_meta_query = false;
$meta_clauses = $this->meta_query->get_clauses();
if ( ! empty( $meta_clauses ) ) {
$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 RAND() contains a seed value, sanitize and add to allowed keys.
$rand_with_seed = false;
if ( preg_match( '/RAND\(([0-9]+)\)/i', $orderby, $matches ) ) {
$orderby = sprintf( 'RAND(%s)', (int) $matches[1] );
$allowed_keys[] = $orderby;
$rand_with_seed = true;
}
if ( ! in_array( $orderby, $allowed_keys, true ) ) {
return false;
}
$orderby_clause = '';
switch ( $orderby ) {
case 'post_name':
case 'post_author':
case 'post_date':
case 'post_title':
case 'post_modified':
case 'post_parent':
case 'post_type':
case 'ID':
case 'menu_order':
case 'comment_count':
$orderby_clause = "{$wpdb->posts}.{$orderby}";
break;
case 'rand':
$orderby_clause = 'RAND()';
break;
case $primary_meta_key:
case 'meta_value':
if ( ! empty( $primary_meta_query['type'] ) ) {
$orderby_clause = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})";
} else {
$orderby_clause = "{$primary_meta_query['alias']}.meta_value";
}
break;
case 'meta_value_num':
$orderby_clause = "{$primary_meta_query['alias']}.meta_value+0";
break;
case 'post__in':
if ( ! empty( $this->query_vars['post__in'] ) ) {
$orderby_clause = "FIELD({$wpdb->posts}.ID," . implode( ',', array_map( 'absint', $this->query_vars['post__in'] ) ) . ')';
}
break;
case 'post_parent__in':
if ( ! empty( $this->query_vars['post_parent__in'] ) ) {
$orderby_clause = "FIELD( {$wpdb->posts}.post_parent," . implode( ', ', array_map( 'absint', $this->query_vars['post_parent__in'] ) ) . ' )';
}
break;
case 'post_name__in':
if ( ! empty( $this->query_vars['post_name__in'] ) ) {
$post_name__in = array_map( 'sanitize_title_for_query', $this->query_vars['post_name__in'] );
$post_name__in_string = "'" . implode( "','", $post_name__in ) . "'";
$orderby_clause = "FIELD( {$wpdb->posts}.post_name," . $post_name__in_string . ' )';
}
break;
default:
if ( array_key_exists( $orderby, $meta_clauses ) ) {
// $orderby corresponds to a meta_query clause.
$meta_clause = $meta_clauses[ $orderby ];
$orderby_clause = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
} elseif ( $rand_with_seed ) {
$orderby_clause = $orderby;
} else {
// Default: order by post field.
$orderby_clause = "{$wpdb->posts}.post_" . sanitize_key( $orderby );
}
break;
}
return $orderby_clause;
}
/**
* Parse an 'order' query variable and cast it to ASC or DESC as necessary.
*
* @since 4.0.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';
}
}
/**
* Sets the 404 property and saves whether query is feed.
*
* @since 2.0.0
*/
public function set_404() {
$is_feed = $this->is_feed;
$this->init_query_flags();
$this->is_404 = true;
$this->is_feed = $is_feed;
/**
* Fires after a 404 is triggered.
*
* @since 5.5.0
*
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
do_action_ref_array( 'set_404', array( $this ) );
}
/**
* Retrieves the value of a query variable.
*
* @since 1.5.0
* @since 3.9.0 The `$default_value` argument was introduced.
*
* @param string $query_var Query variable key.
* @param mixed $default_value Optional. Value to return if the query variable is not set. Default empty string.
* @return mixed Contents of the query variable.
*/
public function get( $query_var, $default_value = '' ) {
if ( isset( $this->query_vars[ $query_var ] ) ) {
return $this->query_vars[ $query_var ];
}
return $default_value;
}
/**
* Sets the value of a query variable.
*
* @since 1.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;
}
/**
* Retrieves an array of posts based on query variables.
*
* There are a few filters and actions that can be used to modify the post
* database query.
*
* @since 1.5.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @return WP_Post[]|int[] Array of post objects or post IDs.
*/
public function get_posts() {
global $wpdb;
$this->parse_query();
/**
* Fires after the query variable object is created, but before the actual query is run.
*
* Note: If using conditional tags, use the method versions within the passed instance
* (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions
* like is_main_query() test against the global $wp_query instance, not the passed one.
*
* @since 2.0.0
*
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
do_action_ref_array( 'pre_get_posts', array( &$this ) );
// Shorthand.
$q = &$this->query_vars;
// Fill again in case 'pre_get_posts' unset some vars.
$q = $this->fill_query_vars( $q );
/**
* Filters whether an attachment query should include filenames or not.
*
* @since 6.0.3
*
* @param bool $allow_query_attachment_by_filename Whether or not to include filenames.
*/
$this->allow_query_attachment_by_filename = apply_filters( 'wp_allow_query_attachment_by_filename', false );
remove_all_filters( 'wp_allow_query_attachment_by_filename' );
// Parse meta query.
$this->meta_query = new WP_Meta_Query();
$this->meta_query->parse_query_vars( $q );
// Set a flag if a 'pre_get_posts' hook changed the query vars.
$hash = md5( serialize( $this->query_vars ) );
if ( $hash != $this->query_vars_hash ) {
$this->query_vars_changed = true;
$this->query_vars_hash = $hash;
}
unset( $hash );
// First let's clear some variables.
$distinct = '';
$whichauthor = '';
$whichmimetype = '';
$where = '';
$limits = '';
$join = '';
$search = '';
$groupby = '';
$post_status_join = false;
$page = 1;
if ( isset( $q['caller_get_posts'] ) ) {
_deprecated_argument(
'WP_Query',
'3.1.0',
sprintf(
/* translators: 1: caller_get_posts, 2: ignore_sticky_posts */
__( '%1$s is deprecated. Use %2$s instead.' ),
'<code>caller_get_posts</code>',
'<code>ignore_sticky_posts</code>'
)
);
if ( ! isset( $q['ignore_sticky_posts'] ) ) {
$q['ignore_sticky_posts'] = $q['caller_get_posts'];
}
}
if ( ! isset( $q['ignore_sticky_posts'] ) ) {
$q['ignore_sticky_posts'] = false;
}
if ( ! isset( $q['suppress_filters'] ) ) {
$q['suppress_filters'] = false;
}
if ( ! isset( $q['cache_results'] ) ) {
$q['cache_results'] = true;
}
if ( ! isset( $q['update_post_term_cache'] ) ) {
$q['update_post_term_cache'] = true;
}
if ( ! isset( $q['update_menu_item_cache'] ) ) {
$q['update_menu_item_cache'] = false;
}
if ( ! isset( $q['lazy_load_term_meta'] ) ) {
$q['lazy_load_term_meta'] = $q['update_post_term_cache'];
}
if ( ! isset( $q['update_post_meta_cache'] ) ) {
$q['update_post_meta_cache'] = true;
}
if ( ! isset( $q['post_type'] ) ) {
if ( $this->is_search ) {
$q['post_type'] = 'any';
} else {
$q['post_type'] = '';
}
}
$post_type = $q['post_type'];
if ( empty( $q['posts_per_page'] ) ) {
$q['posts_per_page'] = get_option( 'posts_per_page' );
}
if ( isset( $q['showposts'] ) && $q['showposts'] ) {
$q['showposts'] = (int) $q['showposts'];
$q['posts_per_page'] = $q['showposts'];
}
if ( ( isset( $q['posts_per_archive_page'] ) && 0 != $q['posts_per_archive_page'] ) && ( $this->is_archive || $this->is_search ) ) {
$q['posts_per_page'] = $q['posts_per_archive_page'];
}
if ( ! isset( $q['nopaging'] ) ) {
if ( -1 == $q['posts_per_page'] ) {
$q['nopaging'] = true;
} else {
$q['nopaging'] = false;
}
}
if ( $this->is_feed ) {
// This overrides 'posts_per_page'.
if ( ! empty( $q['posts_per_rss'] ) ) {
$q['posts_per_page'] = $q['posts_per_rss'];
} else {
$q['posts_per_page'] = get_option( 'posts_per_rss' );
}
$q['nopaging'] = false;
}
$q['posts_per_page'] = (int) $q['posts_per_page'];
if ( $q['posts_per_page'] < -1 ) {
$q['posts_per_page'] = abs( $q['posts_per_page'] );
} elseif ( 0 == $q['posts_per_page'] ) {
$q['posts_per_page'] = 1;
}
if ( ! isset( $q['comments_per_page'] ) || 0 == $q['comments_per_page'] ) {
$q['comments_per_page'] = get_option( 'comments_per_page' );
}
if ( $this->is_home && ( empty( $this->query ) || 'true' === $q['preview'] ) && ( 'page' === get_option( 'show_on_front' ) ) && get_option( 'page_on_front' ) ) {
$this->is_page = true;
$this->is_home = false;
$q['page_id'] = get_option( 'page_on_front' );
}
if ( isset( $q['page'] ) ) {
$q['page'] = trim( $q['page'], '/' );
$q['page'] = absint( $q['page'] );
}
// If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
if ( isset( $q['no_found_rows'] ) ) {
$q['no_found_rows'] = (bool) $q['no_found_rows'];
} else {
$q['no_found_rows'] = false;
}
switch ( $q['fields'] ) {
case 'ids':
$fields = "{$wpdb->posts}.ID";
break;
case 'id=>parent':
$fields = "{$wpdb->posts}.ID, {$wpdb->posts}.post_parent";
break;
default:
$fields = "{$wpdb->posts}.*";
}
if ( '' !== $q['menu_order'] ) {
$where .= " AND {$wpdb->posts}.menu_order = " . $q['menu_order'];
}
// The "m" parameter is meant for months but accepts datetimes of varying specificity.
if ( $q['m'] ) {
$where .= " AND YEAR({$wpdb->posts}.post_date)=" . substr( $q['m'], 0, 4 );
if ( strlen( $q['m'] ) > 5 ) {
$where .= " AND MONTH({$wpdb->posts}.post_date)=" . substr( $q['m'], 4, 2 );
}
if ( strlen( $q['m'] ) > 7 ) {
$where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)=" . substr( $q['m'], 6, 2 );
}
if ( strlen( $q['m'] ) > 9 ) {
$where .= " AND HOUR({$wpdb->posts}.post_date)=" . substr( $q['m'], 8, 2 );
}
if ( strlen( $q['m'] ) > 11 ) {
$where .= " AND MINUTE({$wpdb->posts}.post_date)=" . substr( $q['m'], 10, 2 );
}
if ( strlen( $q['m'] ) > 13 ) {
$where .= " AND SECOND({$wpdb->posts}.post_date)=" . substr( $q['m'], 12, 2 );
}
}
// Handle the other individual date parameters.
$date_parameters = array();
if ( '' !== $q['hour'] ) {
$date_parameters['hour'] = $q['hour'];
}
if ( '' !== $q['minute'] ) {
$date_parameters['minute'] = $q['minute'];
}
if ( '' !== $q['second'] ) {
$date_parameters['second'] = $q['second'];
}
if ( $q['year'] ) {
$date_parameters['year'] = $q['year'];
}
if ( $q['monthnum'] ) {
$date_parameters['monthnum'] = $q['monthnum'];
}
if ( $q['w'] ) {
$date_parameters['week'] = $q['w'];
}
if ( $q['day'] ) {
$date_parameters['day'] = $q['day'];
}
if ( $date_parameters ) {
$date_query = new WP_Date_Query( array( $date_parameters ) );
$where .= $date_query->get_sql();
}
unset( $date_parameters, $date_query );
// Handle complex date queries.
if ( ! empty( $q['date_query'] ) ) {
$this->date_query = new WP_Date_Query( $q['date_query'] );
$where .= $this->date_query->get_sql();
}
// If we've got a post_type AND it's not "any" post_type.
if ( ! empty( $q['post_type'] ) && 'any' !== $q['post_type'] ) {
foreach ( (array) $q['post_type'] as $_post_type ) {
$ptype_obj = get_post_type_object( $_post_type );
if ( ! $ptype_obj || ! $ptype_obj->query_var || empty( $q[ $ptype_obj->query_var ] ) ) {
continue;
}
if ( ! $ptype_obj->hierarchical ) {
// Non-hierarchical post types can directly use 'name'.
$q['name'] = $q[ $ptype_obj->query_var ];
} else {
// Hierarchical post types will operate through 'pagename'.
$q['pagename'] = $q[ $ptype_obj->query_var ];
$q['name'] = '';
}
// Only one request for a slug is possible, this is why name & pagename are overwritten above.
break;
} // End foreach.
unset( $ptype_obj );
}
if ( '' !== $q['title'] ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_title = %s", stripslashes( $q['title'] ) );
}
// Parameters related to 'post_name'.
if ( '' !== $q['name'] ) {
$q['name'] = sanitize_title_for_query( $q['name'] );
$where .= " AND {$wpdb->posts}.post_name = '" . $q['name'] . "'";
} elseif ( '' !== $q['pagename'] ) {
if ( isset( $this->queried_object_id ) ) {
$reqpage = $this->queried_object_id;
} else {
if ( 'page' !== $q['post_type'] ) {
foreach ( (array) $q['post_type'] as $_post_type ) {
$ptype_obj = get_post_type_object( $_post_type );
if ( ! $ptype_obj || ! $ptype_obj->hierarchical ) {
continue;
}
$reqpage = get_page_by_path( $q['pagename'], OBJECT, $_post_type );
if ( $reqpage ) {
break;
}
}
unset( $ptype_obj );
} else {
$reqpage = get_page_by_path( $q['pagename'] );
}
if ( ! empty( $reqpage ) ) {
$reqpage = $reqpage->ID;
} else {
$reqpage = 0;
}
}
$page_for_posts = get_option( 'page_for_posts' );
if ( ( 'page' !== get_option( 'show_on_front' ) ) || empty( $page_for_posts ) || ( $reqpage != $page_for_posts ) ) {
$q['pagename'] = sanitize_title_for_query( wp_basename( $q['pagename'] ) );
$q['name'] = $q['pagename'];
$where .= " AND ({$wpdb->posts}.ID = '$reqpage')";
$reqpage_obj = get_post( $reqpage );
if ( is_object( $reqpage_obj ) && 'attachment' === $reqpage_obj->post_type ) {
$this->is_attachment = true;
$post_type = 'attachment';
$q['post_type'] = 'attachment';
$this->is_page = true;
$q['attachment_id'] = $reqpage;
}
}
} elseif ( '' !== $q['attachment'] ) {
$q['attachment'] = sanitize_title_for_query( wp_basename( $q['attachment'] ) );
$q['name'] = $q['attachment'];
$where .= " AND {$wpdb->posts}.post_name = '" . $q['attachment'] . "'";
} elseif ( is_array( $q['post_name__in'] ) && ! empty( $q['post_name__in'] ) ) {
$q['post_name__in'] = array_map( 'sanitize_title_for_query', $q['post_name__in'] );
$post_name__in = "'" . implode( "','", $q['post_name__in'] ) . "'";
$where .= " AND {$wpdb->posts}.post_name IN ($post_name__in)";
}
// If an attachment is requested by number, let it supersede any post number.
if ( $q['attachment_id'] ) {
$q['p'] = absint( $q['attachment_id'] );
}
// If a post number is specified, load that post.
if ( $q['p'] ) {
$where .= " AND {$wpdb->posts}.ID = " . $q['p'];
} elseif ( $q['post__in'] ) {
$post__in = implode( ',', array_map( 'absint', $q['post__in'] ) );
$where .= " AND {$wpdb->posts}.ID IN ($post__in)";
} elseif ( $q['post__not_in'] ) {
$post__not_in = implode( ',', array_map( 'absint', $q['post__not_in'] ) );
$where .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)";
}
if ( is_numeric( $q['post_parent'] ) ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_parent = %d ", $q['post_parent'] );
} elseif ( $q['post_parent__in'] ) {
$post_parent__in = implode( ',', array_map( 'absint', $q['post_parent__in'] ) );
$where .= " AND {$wpdb->posts}.post_parent IN ($post_parent__in)";
} elseif ( $q['post_parent__not_in'] ) {
$post_parent__not_in = implode( ',', array_map( 'absint', $q['post_parent__not_in'] ) );
$where .= " AND {$wpdb->posts}.post_parent NOT IN ($post_parent__not_in)";
}
if ( $q['page_id'] ) {
if ( ( 'page' !== get_option( 'show_on_front' ) ) || ( get_option( 'page_for_posts' ) != $q['page_id'] ) ) {
$q['p'] = $q['page_id'];
$where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
}
}
// If a search pattern is specified, load the posts that match.
if ( strlen( $q['s'] ) ) {
$search = $this->parse_search( $q );
}
if ( ! $q['suppress_filters'] ) {
/**
* Filters the search SQL that is used in the WHERE clause of WP_Query.
*
* @since 3.0.0
*
* @param string $search Search SQL for WHERE clause.
* @param WP_Query $query The current WP_Query object.
*/
$search = apply_filters_ref_array( 'posts_search', array( $search, &$this ) );
}
// Taxonomies.
if ( ! $this->is_singular ) {
$this->parse_tax_query( $q );
$clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' );
$join .= $clauses['join'];
$where .= $clauses['where'];
}
if ( $this->is_tax ) {
if ( empty( $post_type ) ) {
// Do a fully inclusive search for currently registered post types of queried taxonomies.
$post_type = array();
$taxonomies = array_keys( $this->tax_query->queried_terms );
foreach ( get_post_types( array( 'exclude_from_search' => false ) ) as $pt ) {
$object_taxonomies = 'attachment' === $pt ? get_taxonomies_for_attachments() : get_object_taxonomies( $pt );
if ( array_intersect( $taxonomies, $object_taxonomies ) ) {
$post_type[] = $pt;
}
}
if ( ! $post_type ) {
$post_type = 'any';
} elseif ( count( $post_type ) == 1 ) {
$post_type = $post_type[0];
}
$post_status_join = true;
} elseif ( in_array( 'attachment', (array) $post_type, true ) ) {
$post_status_join = true;
}
}
/*
* Ensure that 'taxonomy', 'term', 'term_id', 'cat', and
* 'category_name' vars are set for backward compatibility.
*/
if ( ! empty( $this->tax_query->queried_terms ) ) {
/*
* Set 'taxonomy', 'term', and 'term_id' to the
* first taxonomy other than 'post_tag' or 'category'.
*/
if ( ! isset( $q['taxonomy'] ) ) {
foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
if ( empty( $queried_items['terms'][0] ) ) {
continue;
}
if ( ! in_array( $queried_taxonomy, array( 'category', 'post_tag' ), true ) ) {
$q['taxonomy'] = $queried_taxonomy;
if ( 'slug' === $queried_items['field'] ) {
$q['term'] = $queried_items['terms'][0];
} else {
$q['term_id'] = $queried_items['terms'][0];
}
// Take the first one we find.
break;
}
}
}
// 'cat', 'category_name', 'tag_id'.
foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
if ( empty( $queried_items['terms'][0] ) ) {
continue;
}
if ( 'category' === $queried_taxonomy ) {
$the_cat = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'category' );
if ( $the_cat ) {
$this->set( 'cat', $the_cat->term_id );
$this->set( 'category_name', $the_cat->slug );
}
unset( $the_cat );
}
if ( 'post_tag' === $queried_taxonomy ) {
$the_tag = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'post_tag' );
if ( $the_tag ) {
$this->set( 'tag_id', $the_tag->term_id );
}
unset( $the_tag );
}
}
}
if ( ! empty( $this->tax_query->queries ) || ! empty( $this->meta_query->queries ) || ! empty( $this->allow_query_attachment_by_filename ) ) {
$groupby = "{$wpdb->posts}.ID";
}
// Author/user stuff.
if ( ! empty( $q['author'] ) && '0' != $q['author'] ) {
$q['author'] = addslashes_gpc( '' . urldecode( $q['author'] ) );
$authors = array_unique( array_map( 'intval', preg_split( '/[,\s]+/', $q['author'] ) ) );
foreach ( $authors as $author ) {
$key = $author > 0 ? 'author__in' : 'author__not_in';
$q[ $key ][] = abs( $author );
}
$q['author'] = implode( ',', $authors );
}
if ( ! empty( $q['author__not_in'] ) ) {
$author__not_in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__not_in'] ) ) );
$where .= " AND {$wpdb->posts}.post_author NOT IN ($author__not_in) ";
} elseif ( ! empty( $q['author__in'] ) ) {
$author__in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__in'] ) ) );
$where .= " AND {$wpdb->posts}.post_author IN ($author__in) ";
}
// Author stuff for nice URLs.
if ( '' !== $q['author_name'] ) {
if ( strpos( $q['author_name'], '/' ) !== false ) {
$q['author_name'] = explode( '/', $q['author_name'] );
if ( $q['author_name'][ count( $q['author_name'] ) - 1 ] ) {
$q['author_name'] = $q['author_name'][ count( $q['author_name'] ) - 1 ]; // No trailing slash.
} else {
$q['author_name'] = $q['author_name'][ count( $q['author_name'] ) - 2 ]; // There was a trailing slash.
}
}
$q['author_name'] = sanitize_title_for_query( $q['author_name'] );
$q['author'] = get_user_by( 'slug', $q['author_name'] );
if ( $q['author'] ) {
$q['author'] = $q['author']->ID;
}
$whichauthor .= " AND ({$wpdb->posts}.post_author = " . absint( $q['author'] ) . ')';
}
// Matching by comment count.
if ( isset( $q['comment_count'] ) ) {
// Numeric comment count is converted to array format.
if ( is_numeric( $q['comment_count'] ) ) {
$q['comment_count'] = array(
'value' => (int) $q['comment_count'],
);
}
if ( isset( $q['comment_count']['value'] ) ) {
$q['comment_count'] = array_merge(
array(
'compare' => '=',
),
$q['comment_count']
);
// Fallback for invalid compare operators is '='.
$compare_operators = array( '=', '!=', '>', '>=', '<', '<=' );
if ( ! in_array( $q['comment_count']['compare'], $compare_operators, true ) ) {
$q['comment_count']['compare'] = '=';
}
$where .= $wpdb->prepare( " AND {$wpdb->posts}.comment_count {$q['comment_count']['compare']} %d", $q['comment_count']['value'] );
}
}
// MIME-Type stuff for attachment browsing.
if ( isset( $q['post_mime_type'] ) && '' !== $q['post_mime_type'] ) {
$whichmimetype = wp_post_mime_type_where( $q['post_mime_type'], $wpdb->posts );
}
$where .= $search . $whichauthor . $whichmimetype;
if ( ! empty( $this->allow_query_attachment_by_filename ) ) {
$join .= " LEFT JOIN {$wpdb->postmeta} AS sq1 ON ( {$wpdb->posts}.ID = sq1.post_id AND sq1.meta_key = '_wp_attached_file' )";
}
if ( ! empty( $this->meta_query->queries ) ) {
$clauses = $this->meta_query->get_sql( 'post', $wpdb->posts, 'ID', $this );
$join .= $clauses['join'];
$where .= $clauses['where'];
}
$rand = ( isset( $q['orderby'] ) && 'rand' === $q['orderby'] );
if ( ! isset( $q['order'] ) ) {
$q['order'] = $rand ? '' : 'DESC';
} else {
$q['order'] = $rand ? '' : $this->parse_order( $q['order'] );
}
// These values of orderby should ignore the 'order' parameter.
$force_asc = array( 'post__in', 'post_name__in', 'post_parent__in' );
if ( isset( $q['orderby'] ) && in_array( $q['orderby'], $force_asc, true ) ) {
$q['order'] = '';
}
// Order by.
if ( empty( $q['orderby'] ) ) {
/*
* Boolean false or empty array blanks out ORDER BY,
* while leaving the value unset or otherwise empty sets the default.
*/
if ( isset( $q['orderby'] ) && ( is_array( $q['orderby'] ) || false === $q['orderby'] ) ) {
$orderby = '';
} else {
$orderby = "{$wpdb->posts}.post_date " . $q['order'];
}
} elseif ( 'none' === $q['orderby'] ) {
$orderby = '';
} else {
$orderby_array = array();
if ( is_array( $q['orderby'] ) ) {
foreach ( $q['orderby'] as $_orderby => $order ) {
$orderby = addslashes_gpc( urldecode( $_orderby ) );
$parsed = $this->parse_orderby( $orderby );
if ( ! $parsed ) {
continue;
}
$orderby_array[] = $parsed . ' ' . $this->parse_order( $order );
}
$orderby = implode( ', ', $orderby_array );
} else {
$q['orderby'] = urldecode( $q['orderby'] );
$q['orderby'] = addslashes_gpc( $q['orderby'] );
foreach ( explode( ' ', $q['orderby'] ) as $i => $orderby ) {
$parsed = $this->parse_orderby( $orderby );
// Only allow certain values for safety.
if ( ! $parsed ) {
continue;
}
$orderby_array[] = $parsed;
}
$orderby = implode( ' ' . $q['order'] . ', ', $orderby_array );
if ( empty( $orderby ) ) {
$orderby = "{$wpdb->posts}.post_date " . $q['order'];
} elseif ( ! empty( $q['order'] ) ) {
$orderby .= " {$q['order']}";
}
}
}
// Order search results by relevance only when another "orderby" is not specified in the query.
if ( ! empty( $q['s'] ) ) {
$search_orderby = '';
if ( ! empty( $q['search_orderby_title'] ) && ( empty( $q['orderby'] ) && ! $this->is_feed ) || ( isset( $q['orderby'] ) && 'relevance' === $q['orderby'] ) ) {
$search_orderby = $this->parse_search_order( $q );
}
if ( ! $q['suppress_filters'] ) {
/**
* Filters the ORDER BY used when ordering search results.
*
* @since 3.7.0
*
* @param string $search_orderby The ORDER BY clause.
* @param WP_Query $query The current WP_Query instance.
*/
$search_orderby = apply_filters( 'posts_search_orderby', $search_orderby, $this );
}
if ( $search_orderby ) {
$orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby;
}
}
if ( is_array( $post_type ) && count( $post_type ) > 1 ) {
$post_type_cap = 'multiple_post_type';
} else {
if ( is_array( $post_type ) ) {
$post_type = reset( $post_type );
}
$post_type_object = get_post_type_object( $post_type );
if ( empty( $post_type_object ) ) {
$post_type_cap = $post_type;
}
}
if ( isset( $q['post_password'] ) ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_password = %s", $q['post_password'] );
if ( empty( $q['perm'] ) ) {
$q['perm'] = 'readable';
}
} elseif ( isset( $q['has_password'] ) ) {
$where .= sprintf( " AND {$wpdb->posts}.post_password %s ''", $q['has_password'] ? '!=' : '=' );
}
if ( ! empty( $q['comment_status'] ) ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.comment_status = %s ", $q['comment_status'] );
}
if ( ! empty( $q['ping_status'] ) ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.ping_status = %s ", $q['ping_status'] );
}
$skip_post_status = false;
if ( 'any' === $post_type ) {
$in_search_post_types = get_post_types( array( 'exclude_from_search' => false ) );
if ( empty( $in_search_post_types ) ) {
$post_type_where = ' AND 1=0 ';
$skip_post_status = true;
} else {
$post_type_where = " AND {$wpdb->posts}.post_type IN ('" . implode( "', '", array_map( 'esc_sql', $in_search_post_types ) ) . "')";
}
} elseif ( ! empty( $post_type ) && is_array( $post_type ) ) {
$post_type_where = " AND {$wpdb->posts}.post_type IN ('" . implode( "', '", esc_sql( $post_type ) ) . "')";
} elseif ( ! empty( $post_type ) ) {
$post_type_where = $wpdb->prepare( " AND {$wpdb->posts}.post_type = %s", $post_type );
$post_type_object = get_post_type_object( $post_type );
} elseif ( $this->is_attachment ) {
$post_type_where = " AND {$wpdb->posts}.post_type = 'attachment'";
$post_type_object = get_post_type_object( 'attachment' );
} elseif ( $this->is_page ) {
$post_type_where = " AND {$wpdb->posts}.post_type = 'page'";
$post_type_object = get_post_type_object( 'page' );
} else {
$post_type_where = " AND {$wpdb->posts}.post_type = 'post'";
$post_type_object = get_post_type_object( 'post' );
}
$edit_cap = 'edit_post';
$read_cap = 'read_post';
if ( ! empty( $post_type_object ) ) {
$edit_others_cap = $post_type_object->cap->edit_others_posts;
$read_private_cap = $post_type_object->cap->read_private_posts;
} else {
$edit_others_cap = 'edit_others_' . $post_type_cap . 's';
$read_private_cap = 'read_private_' . $post_type_cap . 's';
}
$user_id = get_current_user_id();
$q_status = array();
if ( $skip_post_status ) {
$where .= $post_type_where;
} elseif ( ! empty( $q['post_status'] ) ) {
$where .= $post_type_where;
$statuswheres = array();
$q_status = $q['post_status'];
if ( ! is_array( $q_status ) ) {
$q_status = explode( ',', $q_status );
}
$r_status = array();
$p_status = array();
$e_status = array();
if ( in_array( 'any', $q_status, true ) ) {
foreach ( get_post_stati( array( 'exclude_from_search' => true ) ) as $status ) {
if ( ! in_array( $status, $q_status, true ) ) {
$e_status[] = "{$wpdb->posts}.post_status <> '$status'";
}
}
} else {
foreach ( get_post_stati() as $status ) {
if ( in_array( $status, $q_status, true ) ) {
if ( 'private' === $status ) {
$p_status[] = "{$wpdb->posts}.post_status = '$status'";
} else {
$r_status[] = "{$wpdb->posts}.post_status = '$status'";
}
}
}
}
if ( empty( $q['perm'] ) || 'readable' !== $q['perm'] ) {
$r_status = array_merge( $r_status, $p_status );
unset( $p_status );
}
if ( ! empty( $e_status ) ) {
$statuswheres[] = '(' . implode( ' AND ', $e_status ) . ')';
}
if ( ! empty( $r_status ) ) {
if ( ! empty( $q['perm'] ) && 'editable' === $q['perm'] && ! current_user_can( $edit_others_cap ) ) {
$statuswheres[] = "({$wpdb->posts}.post_author = $user_id " . 'AND (' . implode( ' OR ', $r_status ) . '))';
} else {
$statuswheres[] = '(' . implode( ' OR ', $r_status ) . ')';
}
}
if ( ! empty( $p_status ) ) {
if ( ! empty( $q['perm'] ) && 'readable' === $q['perm'] && ! current_user_can( $read_private_cap ) ) {
$statuswheres[] = "({$wpdb->posts}.post_author = $user_id " . 'AND (' . implode( ' OR ', $p_status ) . '))';
} else {
$statuswheres[] = '(' . implode( ' OR ', $p_status ) . ')';
}
}
if ( $post_status_join ) {
$join .= " LEFT JOIN {$wpdb->posts} AS p2 ON ({$wpdb->posts}.post_parent = p2.ID) ";
foreach ( $statuswheres as $index => $statuswhere ) {
$statuswheres[ $index ] = "($statuswhere OR ({$wpdb->posts}.post_status = 'inherit' AND " . str_replace( $wpdb->posts, 'p2', $statuswhere ) . '))';
}
}
$where_status = implode( ' OR ', $statuswheres );
if ( ! empty( $where_status ) ) {
$where .= " AND ($where_status)";
}
} elseif ( ! $this->is_singular ) {
if ( 'any' === $post_type ) {
$queried_post_types = get_post_types( array( 'exclude_from_search' => false ) );
} elseif ( is_array( $post_type ) ) {
$queried_post_types = $post_type;
} elseif ( ! empty( $post_type ) ) {
$queried_post_types = array( $post_type );
} else {
$queried_post_types = array( 'post' );
}
if ( ! empty( $queried_post_types ) ) {
$status_type_clauses = array();
foreach ( $queried_post_types as $queried_post_type ) {
$queried_post_type_object = get_post_type_object( $queried_post_type );
$type_where = '(' . $wpdb->prepare( "{$wpdb->posts}.post_type = %s AND (", $queried_post_type );
// Public statuses.
$public_statuses = get_post_stati( array( 'public' => true ) );
$status_clauses = array();
foreach ( $public_statuses as $public_status ) {
$status_clauses[] = "{$wpdb->posts}.post_status = '$public_status'";
}
$type_where .= implode( ' OR ', $status_clauses );
// Add protected states that should show in the admin all list.
if ( $this->is_admin ) {
$admin_all_statuses = get_post_stati(
array(
'protected' => true,
'show_in_admin_all_list' => true,
)
);
foreach ( $admin_all_statuses as $admin_all_status ) {
$type_where .= " OR {$wpdb->posts}.post_status = '$admin_all_status'";
}
}
// Add private states that are visible to current user.
if ( is_user_logged_in() && $queried_post_type_object instanceof WP_Post_Type ) {
$read_private_cap = $queried_post_type_object->cap->read_private_posts;
$private_statuses = get_post_stati( array( 'private' => true ) );
foreach ( $private_statuses as $private_status ) {
$type_where .= current_user_can( $read_private_cap ) ? " \nOR {$wpdb->posts}.post_status = '$private_status'" : " \nOR ({$wpdb->posts}.post_author = $user_id AND {$wpdb->posts}.post_status = '$private_status')";
}
}
$type_where .= '))';
$status_type_clauses[] = $type_where;
}
if ( ! empty( $status_type_clauses ) ) {
$where .= ' AND (' . implode( ' OR ', $status_type_clauses ) . ')';
}
} else {
$where .= ' AND 1=0 ';
}
} else {
$where .= $post_type_where;
}
/*
* Apply filters on where and join prior to paging so that any
* manipulations to them are reflected in the paging by day queries.
*/
if ( ! $q['suppress_filters'] ) {
/**
* Filters the WHERE clause of the query.
*
* @since 1.5.0
*
* @param string $where The WHERE clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$where = apply_filters_ref_array( 'posts_where', array( $where, &$this ) );
/**
* Filters the JOIN clause of the query.
*
* @since 1.5.0
*
* @param string $join The JOIN clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$join = apply_filters_ref_array( 'posts_join', array( $join, &$this ) );
}
// Paging.
if ( empty( $q['nopaging'] ) && ! $this->is_singular ) {
$page = absint( $q['paged'] );
if ( ! $page ) {
$page = 1;
}
// If 'offset' is provided, it takes precedence over 'paged'.
if ( isset( $q['offset'] ) && is_numeric( $q['offset'] ) ) {
$q['offset'] = absint( $q['offset'] );
$pgstrt = $q['offset'] . ', ';
} else {
$pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
}
$limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
}
// Comments feeds.
if ( $this->is_comment_feed && ! $this->is_singular ) {
if ( $this->is_archive || $this->is_search ) {
$cjoin = "JOIN {$wpdb->posts} ON ( {$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID ) $join ";
$cwhere = "WHERE comment_approved = '1' $where";
$cgroupby = "{$wpdb->comments}.comment_id";
} else { // Other non-singular, e.g. front.
$cjoin = "JOIN {$wpdb->posts} ON ( {$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID )";
$cwhere = "WHERE ( post_status = 'publish' OR ( post_status = 'inherit' AND post_type = 'attachment' ) ) AND comment_approved = '1'";
$cgroupby = '';
}
if ( ! $q['suppress_filters'] ) {
/**
* Filters the JOIN clause of the comments feed query before sending.
*
* @since 2.2.0
*
* @param string $cjoin The JOIN clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$cjoin = apply_filters_ref_array( 'comment_feed_join', array( $cjoin, &$this ) );
/**
* Filters the WHERE clause of the comments feed query before sending.
*
* @since 2.2.0
*
* @param string $cwhere The WHERE clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$cwhere = apply_filters_ref_array( 'comment_feed_where', array( $cwhere, &$this ) );
/**
* Filters the GROUP BY clause of the comments feed query before sending.
*
* @since 2.2.0
*
* @param string $cgroupby The GROUP BY clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( $cgroupby, &$this ) );
/**
* Filters the ORDER BY clause of the comments feed query before sending.
*
* @since 2.8.0
*
* @param string $corderby The ORDER BY clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
/**
* Filters the LIMIT clause of the comments feed query before sending.
*
* @since 2.8.0
*
* @param string $climits The JOIN clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option( 'posts_per_rss' ), &$this ) );
}
$cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
$corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
$climits = ( ! empty( $climits ) ) ? $climits : '';
$comments_request = "SELECT $distinct {$wpdb->comments}.comment_ID FROM {$wpdb->comments} $cjoin $cwhere $cgroupby $corderby $climits";
$key = md5( $comments_request );
$last_changed = wp_cache_get_last_changed( 'comment' ) . ':' . wp_cache_get_last_changed( 'posts' );
$cache_key = "comment_feed:$key:$last_changed";
$comment_ids = wp_cache_get( $cache_key, 'comment' );
if ( false === $comment_ids ) {
$comment_ids = $wpdb->get_col( $comments_request );
wp_cache_add( $cache_key, $comment_ids, 'comment' );
}
_prime_comment_caches( $comment_ids, false );
// Convert to WP_Comment.
/** @var WP_Comment[] */
$this->comments = array_map( 'get_comment', $comment_ids );
$this->comment_count = count( $this->comments );
$post_ids = array();
foreach ( $this->comments as $comment ) {
$post_ids[] = (int) $comment->comment_post_ID;
}
$post_ids = implode( ',', $post_ids );
$join = '';
if ( $post_ids ) {
$where = "AND {$wpdb->posts}.ID IN ($post_ids) ";
} else {
$where = 'AND 0';
}
}
$pieces = array( 'where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits' );
/*
* Apply post-paging filters on where and join. Only plugins that
* manipulate paging queries should use these hooks.
*/
if ( ! $q['suppress_filters'] ) {
/**
* Filters the WHERE clause of the query.
*
* Specifically for manipulating paging queries.
*
* @since 1.5.0
*
* @param string $where The WHERE clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$where = apply_filters_ref_array( 'posts_where_paged', array( $where, &$this ) );
/**
* Filters the GROUP BY clause of the query.
*
* @since 2.0.0
*
* @param string $groupby The GROUP BY clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$groupby = apply_filters_ref_array( 'posts_groupby', array( $groupby, &$this ) );
/**
* Filters the JOIN clause of the query.
*
* Specifically for manipulating paging queries.
*
* @since 1.5.0
*
* @param string $join The JOIN clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$join = apply_filters_ref_array( 'posts_join_paged', array( $join, &$this ) );
/**
* Filters the ORDER BY clause of the query.
*
* @since 1.5.1
*
* @param string $orderby The ORDER BY clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$orderby = apply_filters_ref_array( 'posts_orderby', array( $orderby, &$this ) );
/**
* Filters the DISTINCT clause of the query.
*
* @since 2.1.0
*
* @param string $distinct The DISTINCT clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$distinct = apply_filters_ref_array( 'posts_distinct', array( $distinct, &$this ) );
/**
* Filters the LIMIT clause of the query.
*
* @since 2.1.0
*
* @param string $limits The LIMIT clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$limits = apply_filters_ref_array( 'post_limits', array( $limits, &$this ) );
/**
* Filters the SELECT clause of the query.
*
* @since 2.1.0
*
* @param string $fields The SELECT clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$fields = apply_filters_ref_array( 'posts_fields', array( $fields, &$this ) );
/**
* Filters all query clauses at once, for convenience.
*
* Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
* fields (SELECT), and LIMIT clauses.
*
* @since 3.1.0
*
* @param string[] $clauses {
* Associative array of the clauses for the query.
*
* @type string $where The WHERE clause of the query.
* @type string $groupby The GROUP BY clause of the query.
* @type string $join The JOIN clause of the query.
* @type string $orderby The ORDER BY clause of the query.
* @type string $distinct The DISTINCT clause of the query.
* @type string $fields The SELECT clause of the query.
* @type string $limits The LIMIT clause of the query.
* }
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$clauses = (array) apply_filters_ref_array( 'posts_clauses', array( compact( $pieces ), &$this ) );
$where = isset( $clauses['where'] ) ? $clauses['where'] : '';
$groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : '';
$join = isset( $clauses['join'] ) ? $clauses['join'] : '';
$orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
$distinct = isset( $clauses['distinct'] ) ? $clauses['distinct'] : '';
$fields = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
$limits = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
}
/**
* Fires to announce the query's current selection parameters.
*
* For use by caching plugins.
*
* @since 2.3.0
*
* @param string $selection The assembled selection query.
*/
do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join );
/*
* Filters again for the benefit of caching plugins.
* Regular plugins should use the hooks above.
*/
if ( ! $q['suppress_filters'] ) {
/**
* Filters the WHERE clause of the query.
*
* For use by caching plugins.
*
* @since 2.5.0
*
* @param string $where The WHERE clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$where = apply_filters_ref_array( 'posts_where_request', array( $where, &$this ) );
/**
* Filters the GROUP BY clause of the query.
*
* For use by caching plugins.
*
* @since 2.5.0
*
* @param string $groupby The GROUP BY clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$groupby = apply_filters_ref_array( 'posts_groupby_request', array( $groupby, &$this ) );
/**
* Filters the JOIN clause of the query.
*
* For use by caching plugins.
*
* @since 2.5.0
*
* @param string $join The JOIN clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$join = apply_filters_ref_array( 'posts_join_request', array( $join, &$this ) );
/**
* Filters the ORDER BY clause of the query.
*
* For use by caching plugins.
*
* @since 2.5.0
*
* @param string $orderby The ORDER BY clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$orderby = apply_filters_ref_array( 'posts_orderby_request', array( $orderby, &$this ) );
/**
* Filters the DISTINCT clause of the query.
*
* For use by caching plugins.
*
* @since 2.5.0
*
* @param string $distinct The DISTINCT clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$distinct = apply_filters_ref_array( 'posts_distinct_request', array( $distinct, &$this ) );
/**
* Filters the SELECT clause of the query.
*
* For use by caching plugins.
*
* @since 2.5.0
*
* @param string $fields The SELECT clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$fields = apply_filters_ref_array( 'posts_fields_request', array( $fields, &$this ) );
/**
* Filters the LIMIT clause of the query.
*
* For use by caching plugins.
*
* @since 2.5.0
*
* @param string $limits The LIMIT clause of the query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$limits = apply_filters_ref_array( 'post_limits_request', array( $limits, &$this ) );
/**
* Filters all query clauses at once, for convenience.
*
* For use by caching plugins.
*
* Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
* fields (SELECT), and LIMIT clauses.
*
* @since 3.1.0
*
* @param string[] $clauses {
* Associative array of the clauses for the query.
*
* @type string $where The WHERE clause of the query.
* @type string $groupby The GROUP BY clause of the query.
* @type string $join The JOIN clause of the query.
* @type string $orderby The ORDER BY clause of the query.
* @type string $distinct The DISTINCT clause of the query.
* @type string $fields The SELECT clause of the query.
* @type string $limits The LIMIT clause of the query.
* }
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$clauses = (array) apply_filters_ref_array( 'posts_clauses_request', array( compact( $pieces ), &$this ) );
$where = isset( $clauses['where'] ) ? $clauses['where'] : '';
$groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : '';
$join = isset( $clauses['join'] ) ? $clauses['join'] : '';
$orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
$distinct = isset( $clauses['distinct'] ) ? $clauses['distinct'] : '';
$fields = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
$limits = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
}
if ( ! empty( $groupby ) ) {
$groupby = 'GROUP BY ' . $groupby;
}
if ( ! empty( $orderby ) ) {
$orderby = 'ORDER BY ' . $orderby;
}
$found_rows = '';
if ( ! $q['no_found_rows'] && ! empty( $limits ) ) {
$found_rows = 'SQL_CALC_FOUND_ROWS';
}
$old_request = "
SELECT $found_rows $distinct $fields
FROM {$wpdb->posts} $join
WHERE 1=1 $where
$groupby
$orderby
$limits
";
$this->request = $old_request;
if ( ! $q['suppress_filters'] ) {
/**
* Filters the completed SQL query before sending.
*
* @since 2.0.0
*
* @param string $request The complete SQL query.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$this->request = apply_filters_ref_array( 'posts_request', array( $this->request, &$this ) );
}
/**
* Filters the posts array before the query takes place.
*
* Return a non-null value to bypass WordPress' default post queries.
*
* Filtering functions that require pagination information are encouraged to set
* the `found_posts` and `max_num_pages` properties of the WP_Query object,
* passed to the filter by reference. If WP_Query does not perform a database
* query, it will not have enough information to generate these values itself.
*
* @since 4.6.0
*
* @param WP_Post[]|int[]|null $posts Return an array of post data to short-circuit WP's query,
* or null to allow WP to run its normal queries.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$this->posts = apply_filters_ref_array( 'posts_pre_query', array( null, &$this ) );
/*
* Ensure the ID database query is able to be cached.
*
* Random queries are expected to have unpredictable results and
* cannot be cached. Note the space before `RAND` in the string
* search, that to ensure against a collision with another
* function.
*/
$id_query_is_cacheable = ! str_contains( strtoupper( $orderby ), ' RAND(' );
if ( $q['cache_results'] && $id_query_is_cacheable ) {
$new_request = str_replace( $fields, "{$wpdb->posts}.*", $this->request );
$cache_key = $this->generate_cache_key( $q, $new_request );
$cache_found = false;
if ( null === $this->posts ) {
$cached_results = wp_cache_get( $cache_key, 'posts', false, $cache_found );
if ( $cached_results ) {
if ( 'ids' === $q['fields'] ) {
/** @var int[] */
$this->posts = array_map( 'intval', $cached_results['posts'] );
} else {
_prime_post_caches( $cached_results['posts'], $q['update_post_term_cache'], $q['update_post_meta_cache'] );
/** @var WP_Post[] */
$this->posts = array_map( 'get_post', $cached_results['posts'] );
}
$this->post_count = count( $this->posts );
$this->found_posts = $cached_results['found_posts'];
$this->max_num_pages = $cached_results['max_num_pages'];
if ( 'ids' === $q['fields'] ) {
return $this->posts;
} elseif ( 'id=>parent' === $q['fields'] ) {
/** @var int[] */
$post_parents = array();
foreach ( $this->posts as $key => $post ) {
$obj = new stdClass();
$obj->ID = (int) $post->ID;
$obj->post_parent = (int) $post->post_parent;
$this->posts[ $key ] = $obj;
$post_parents[ $obj->ID ] = $obj->post_parent;
}
return $post_parents;
}
}
}
}
if ( 'ids' === $q['fields'] ) {
if ( null === $this->posts ) {
$this->posts = $wpdb->get_col( $this->request );
}
/** @var int[] */
$this->posts = array_map( 'intval', $this->posts );
$this->post_count = count( $this->posts );
$this->set_found_posts( $q, $limits );
if ( $q['cache_results'] && $id_query_is_cacheable ) {
$cache_value = array(
'posts' => $this->posts,
'found_posts' => $this->found_posts,
'max_num_pages' => $this->max_num_pages,
);
wp_cache_set( $cache_key, $cache_value, 'posts' );
}
return $this->posts;
}
if ( 'id=>parent' === $q['fields'] ) {
if ( null === $this->posts ) {
$this->posts = $wpdb->get_results( $this->request );
}
$this->post_count = count( $this->posts );
$this->set_found_posts( $q, $limits );
/** @var int[] */
$post_parents = array();
$post_ids = array();
foreach ( $this->posts as $key => $post ) {
$this->posts[ $key ]->ID = (int) $post->ID;
$this->posts[ $key ]->post_parent = (int) $post->post_parent;
$post_parents[ (int) $post->ID ] = (int) $post->post_parent;
$post_ids[] = (int) $post->ID;
}
if ( $q['cache_results'] && $id_query_is_cacheable ) {
$cache_value = array(
'posts' => $post_ids,
'found_posts' => $this->found_posts,
'max_num_pages' => $this->max_num_pages,
);
wp_cache_set( $cache_key, $cache_value, 'posts' );
}
return $post_parents;
}
if ( null === $this->posts ) {
$split_the_query = ( $old_request == $this->request && "{$wpdb->posts}.*" === $fields && ! empty( $limits ) && $q['posts_per_page'] < 500 );
/**
* Filters whether to split the query.
*
* Splitting the query will cause it to fetch just the IDs of the found posts
* (and then individually fetch each post by ID), rather than fetching every
* complete row at once. One massive result vs. many small results.
*
* @since 3.4.0
*
* @param bool $split_the_query Whether or not to split the query.
* @param WP_Query $query The WP_Query instance.
*/
$split_the_query = apply_filters( 'split_the_query', $split_the_query, $this );
if ( $split_the_query ) {
// First get the IDs and then fill in the objects.
$this->request = "
SELECT $found_rows $distinct {$wpdb->posts}.ID
FROM {$wpdb->posts} $join
WHERE 1=1 $where
$groupby
$orderby
$limits
";
/**
* Filters the Post IDs SQL request before sending.
*
* @since 3.4.0
*
* @param string $request The post ID request.
* @param WP_Query $query The WP_Query instance.
*/
$this->request = apply_filters( 'posts_request_ids', $this->request, $this );
$post_ids = $wpdb->get_col( $this->request );
if ( $post_ids ) {
$this->posts = $post_ids;
$this->set_found_posts( $q, $limits );
_prime_post_caches( $post_ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
} else {
$this->posts = array();
}
} else {
$this->posts = $wpdb->get_results( $this->request );
$this->set_found_posts( $q, $limits );
}
}
// Convert to WP_Post objects.
if ( $this->posts ) {
/** @var WP_Post[] */
$this->posts = array_map( 'get_post', $this->posts );
}
if ( $q['cache_results'] && $id_query_is_cacheable && ! $cache_found ) {
$post_ids = wp_list_pluck( $this->posts, 'ID' );
$cache_value = array(
'posts' => $post_ids,
'found_posts' => $this->found_posts,
'max_num_pages' => $this->max_num_pages,
);
wp_cache_set( $cache_key, $cache_value, 'posts' );
}
if ( ! $q['suppress_filters'] ) {
/**
* Filters the raw post results array, prior to status checks.
*
* @since 2.3.0
*
* @param WP_Post[] $posts Array of post objects.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$this->posts = apply_filters_ref_array( 'posts_results', array( $this->posts, &$this ) );
}
if ( ! empty( $this->posts ) && $this->is_comment_feed && $this->is_singular ) {
/** This filter is documented in wp-includes/query.php */
$cjoin = apply_filters_ref_array( 'comment_feed_join', array( '', &$this ) );
/** This filter is documented in wp-includes/query.php */
$cwhere = apply_filters_ref_array( 'comment_feed_where', array( "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this ) );
/** This filter is documented in wp-includes/query.php */
$cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( '', &$this ) );
$cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
/** This filter is documented in wp-includes/query.php */
$corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
$corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
/** This filter is documented in wp-includes/query.php */
$climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option( 'posts_per_rss' ), &$this ) );
$comments_request = "SELECT {$wpdb->comments}.comment_ID FROM {$wpdb->comments} $cjoin $cwhere $cgroupby $corderby $climits";
$comment_key = md5( $comments_request );
$comment_last_changed = wp_cache_get_last_changed( 'comment' );
$comment_cache_key = "comment_feed:$comment_key:$comment_last_changed";
$comment_ids = wp_cache_get( $comment_cache_key, 'comment' );
if ( false === $comment_ids ) {
$comment_ids = $wpdb->get_col( $comments_request );
wp_cache_add( $comment_cache_key, $comment_ids, 'comment' );
}
_prime_comment_caches( $comment_ids, false );
// Convert to WP_Comment.
/** @var WP_Comment[] */
$this->comments = array_map( 'get_comment', $comment_ids );
$this->comment_count = count( $this->comments );
}
// Check post status to determine if post should be displayed.
if ( ! empty( $this->posts ) && ( $this->is_single || $this->is_page ) ) {
$status = get_post_status( $this->posts[0] );
if ( 'attachment' === $this->posts[0]->post_type && 0 === (int) $this->posts[0]->post_parent ) {
$this->is_page = false;
$this->is_single = true;
$this->is_attachment = true;
}
// If the post_status was specifically requested, let it pass through.
if ( ! in_array( $status, $q_status, true ) ) {
$post_status_obj = get_post_status_object( $status );
if ( $post_status_obj && ! $post_status_obj->public ) {
if ( ! is_user_logged_in() ) {
// User must be logged in to view unpublished posts.
$this->posts = array();
} else {
if ( $post_status_obj->protected ) {
// User must have edit permissions on the draft to preview.
if ( ! current_user_can( $edit_cap, $this->posts[0]->ID ) ) {
$this->posts = array();
} else {
$this->is_preview = true;
if ( 'future' !== $status ) {
$this->posts[0]->post_date = current_time( 'mysql' );
}
}
} elseif ( $post_status_obj->private ) {
if ( ! current_user_can( $read_cap, $this->posts[0]->ID ) ) {
$this->posts = array();
}
} else {
$this->posts = array();
}
}
} elseif ( ! $post_status_obj ) {
// Post status is not registered, assume it's not public.
if ( ! current_user_can( $edit_cap, $this->posts[0]->ID ) ) {
$this->posts = array();
}
}
}
if ( $this->is_preview && $this->posts && current_user_can( $edit_cap, $this->posts[0]->ID ) ) {
/**
* Filters the single post for preview mode.
*
* @since 2.7.0
*
* @param WP_Post $post_preview The Post object.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$this->posts[0] = get_post( apply_filters_ref_array( 'the_preview', array( $this->posts[0], &$this ) ) );
}
}
// Put sticky posts at the top of the posts array.
$sticky_posts = get_option( 'sticky_posts' );
if ( $this->is_home && $page <= 1 && is_array( $sticky_posts ) && ! empty( $sticky_posts ) && ! $q['ignore_sticky_posts'] ) {
$num_posts = count( $this->posts );
$sticky_offset = 0;
// Loop over posts and relocate stickies to the front.
for ( $i = 0; $i < $num_posts; $i++ ) {
if ( in_array( $this->posts[ $i ]->ID, $sticky_posts, true ) ) {
$sticky_post = $this->posts[ $i ];
// Remove sticky from current position.
array_splice( $this->posts, $i, 1 );
// Move to front, after other stickies.
array_splice( $this->posts, $sticky_offset, 0, array( $sticky_post ) );
// Increment the sticky offset. The next sticky will be placed at this offset.
$sticky_offset++;
// Remove post from sticky posts array.
$offset = array_search( $sticky_post->ID, $sticky_posts, true );
unset( $sticky_posts[ $offset ] );
}
}
// If any posts have been excluded specifically, Ignore those that are sticky.
if ( ! empty( $sticky_posts ) && ! empty( $q['post__not_in'] ) ) {
$sticky_posts = array_diff( $sticky_posts, $q['post__not_in'] );
}
// Fetch sticky posts that weren't in the query results.
if ( ! empty( $sticky_posts ) ) {
$stickies = get_posts(
array(
'post__in' => $sticky_posts,
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => count( $sticky_posts ),
'suppress_filters' => $q['suppress_filters'],
'cache_results' => $q['cache_results'],
'update_post_meta_cache' => $q['update_post_meta_cache'],
'update_post_term_cache' => $q['update_post_term_cache'],
'lazy_load_term_meta' => $q['lazy_load_term_meta'],
)
);
foreach ( $stickies as $sticky_post ) {
array_splice( $this->posts, $sticky_offset, 0, array( $sticky_post ) );
$sticky_offset++;
}
}
}
// If comments have been fetched as part of the query, make sure comment meta lazy-loading is set up.
if ( ! empty( $this->comments ) ) {
wp_queue_comments_for_comment_meta_lazyload( $this->comments );
}
if ( ! $q['suppress_filters'] ) {
/**
* Filters the array of retrieved posts after they've been fetched and
* internally processed.
*
* @since 1.5.0
*
* @param WP_Post[] $posts Array of post objects.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$this->posts = apply_filters_ref_array( 'the_posts', array( $this->posts, &$this ) );
}
// Ensure that any posts added/modified via one of the filters above are
// of the type WP_Post and are filtered.
if ( $this->posts ) {
$this->post_count = count( $this->posts );
/** @var WP_Post[] */
$this->posts = array_map( 'get_post', $this->posts );
if ( $q['cache_results'] ) {
$post_ids = wp_list_pluck( $this->posts, 'ID' );
_prime_post_caches( $post_ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
}
/** @var WP_Post */
$this->post = reset( $this->posts );
} else {
$this->post_count = 0;
$this->posts = array();
}
if ( ! empty( $this->posts ) && $q['update_menu_item_cache'] ) {
update_menu_item_cache( $this->posts );
}
if ( $q['lazy_load_term_meta'] ) {
wp_queue_posts_for_term_meta_lazyload( $this->posts );
}
return $this->posts;
}
/**
* Set up the amount of found posts and the number of pages (if limit clause was used)
* for the current query.
*
* @since 3.5.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param array $q Query variables.
* @param string $limits LIMIT clauses of the query.
*/
private function set_found_posts( $q, $limits ) {
global $wpdb;
// Bail if posts is an empty array. Continue if posts is an empty string,
// null, or false to accommodate caching plugins that fill posts later.
if ( $q['no_found_rows'] || ( is_array( $this->posts ) && ! $this->posts ) ) {
return;
}
if ( ! empty( $limits ) ) {
/**
* Filters the query to run for retrieving the found posts.
*
* @since 2.1.0
*
* @param string $found_posts_query The query to run to find the found posts.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$found_posts_query = apply_filters_ref_array( 'found_posts_query', array( 'SELECT FOUND_ROWS()', &$this ) );
$this->found_posts = (int) $wpdb->get_var( $found_posts_query );
} else {
if ( is_array( $this->posts ) ) {
$this->found_posts = count( $this->posts );
} else {
if ( null === $this->posts ) {
$this->found_posts = 0;
} else {
$this->found_posts = 1;
}
}
}
/**
* Filters the number of found posts for the query.
*
* @since 2.1.0
*
* @param int $found_posts The number of posts found.
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
$this->found_posts = (int) apply_filters_ref_array( 'found_posts', array( $this->found_posts, &$this ) );
if ( ! empty( $limits ) ) {
$this->max_num_pages = ceil( $this->found_posts / $q['posts_per_page'] );
}
}
/**
* Set up the next post and iterate current post index.
*
* @since 1.5.0
*
* @return WP_Post Next post.
*/
public function next_post() {
$this->current_post++;
/** @var WP_Post */
$this->post = $this->posts[ $this->current_post ];
return $this->post;
}
/**
* Sets up the current post.
*
* Retrieves the next post, sets up the post, sets the 'in the loop'
* property to true.
*
* @since 1.5.0
*
* @global WP_Post $post Global post object.
*/
public function the_post() {
global $post;
if ( ! $this->in_the_loop ) {
update_post_author_caches( $this->posts );
}
$this->in_the_loop = true;
if ( -1 == $this->current_post ) { // Loop has just started.
/**
* Fires once the loop is started.
*
* @since 2.0.0
*
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
do_action_ref_array( 'loop_start', array( &$this ) );
}
$post = $this->next_post();
$this->setup_postdata( $post );
}
/**
* Determines whether there are more posts available in the loop.
*
* Calls the {@see 'loop_end'} action when the loop is complete.
*
* @since 1.5.0
*
* @return bool True if posts are available, false if end of the loop.
*/
public function have_posts() {
if ( $this->current_post + 1 < $this->post_count ) {
return true;
} elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
/**
* Fires once the loop has ended.
*
* @since 2.0.0
*
* @param WP_Query $query The WP_Query instance (passed by reference).
*/
do_action_ref_array( 'loop_end', array( &$this ) );
// Do some cleaning up after the loop.
$this->rewind_posts();
} elseif ( 0 === $this->post_count ) {
/**
* Fires if no results are found in a post query.
*
* @since 4.9.0
*
* @param WP_Query $query The WP_Query instance.
*/
do_action( 'loop_no_results', $this );
}
$this->in_the_loop = false;
return false;
}
/**
* Rewind the posts and reset post index.
*
* @since 1.5.0
*/
public function rewind_posts() {
$this->current_post = -1;
if ( $this->post_count > 0 ) {
$this->post = $this->posts[0];
}
}
/**
* Iterate current comment index and return WP_Comment object.
*
* @since 2.2.0
*
* @return WP_Comment Comment object.
*/
public function next_comment() {
$this->current_comment++;
/** @var WP_Comment */
$this->comment = $this->comments[ $this->current_comment ];
return $this->comment;
}
/**
* Sets up the current comment.
*
* @since 2.2.0
*
* @global WP_Comment $comment Global comment object.
*/
public function the_comment() {
global $comment;
$comment = $this->next_comment();
if ( 0 == $this->current_comment ) {
/**
* Fires once the comment loop is started.
*
* @since 2.2.0
*/
do_action( 'comment_loop_start' );
}
}
/**
* Whether there are more comments available.
*
* Automatically rewinds comments when finished.
*
* @since 2.2.0
*
* @return bool True if comments are available, false if no more comments.
*/
public function have_comments() {
if ( $this->current_comment + 1 < $this->comment_count ) {
return true;
} elseif ( $this->current_comment + 1 == $this->comment_count ) {
$this->rewind_comments();
}
return false;
}
/**
* Rewind the comments, resets the comment index and comment to first.
*
* @since 2.2.0
*/
public function rewind_comments() {
$this->current_comment = -1;
if ( $this->comment_count > 0 ) {
$this->comment = $this->comments[0];
}
}
/**
* Sets up the WordPress query by parsing query string.
*
* @since 1.5.0
*
* @see WP_Query::parse_query() for all available arguments.
*
* @param string|array $query URL query string or array of query arguments.
* @return WP_Post[]|int[] Array of post objects or post IDs.
*/
public function query( $query ) {
$this->init();
$this->query = wp_parse_args( $query );
$this->query_vars = $this->query;
return $this->get_posts();
}
/**
* Retrieves the currently queried object.
*
* If queried object is not set, then the queried object will be set from
* the category, tag, taxonomy, posts page, single post, page, or author
* query variable. After it is set up, it will be returned.
*
* @since 1.5.0
*
* @return WP_Term|WP_Post_Type|WP_Post|WP_User|null The queried object.
*/
public function get_queried_object() {
if ( isset( $this->queried_object ) ) {
return $this->queried_object;
}
$this->queried_object = null;
$this->queried_object_id = null;
if ( $this->is_category || $this->is_tag || $this->is_tax ) {
if ( $this->is_category ) {
$cat = $this->get( 'cat' );
$category_name = $this->get( 'category_name' );
if ( $cat ) {
$term = get_term( $cat, 'category' );
} elseif ( $category_name ) {
$term = get_term_by( 'slug', $category_name, 'category' );
}
} elseif ( $this->is_tag ) {
$tag_id = $this->get( 'tag_id' );
$tag = $this->get( 'tag' );
if ( $tag_id ) {
$term = get_term( $tag_id, 'post_tag' );
} elseif ( $tag ) {
$term = get_term_by( 'slug', $tag, 'post_tag' );
}
} else {
// For other tax queries, grab the first term from the first clause.
if ( ! empty( $this->tax_query->queried_terms ) ) {
$queried_taxonomies = array_keys( $this->tax_query->queried_terms );
$matched_taxonomy = reset( $queried_taxonomies );
$query = $this->tax_query->queried_terms[ $matched_taxonomy ];
if ( ! empty( $query['terms'] ) ) {
if ( 'term_id' === $query['field'] ) {
$term = get_term( reset( $query['terms'] ), $matched_taxonomy );
} else {
$term = get_term_by( $query['field'], reset( $query['terms'] ), $matched_taxonomy );
}
}
}
}
if ( ! empty( $term ) && ! is_wp_error( $term ) ) {
$this->queried_object = $term;
$this->queried_object_id = (int) $term->term_id;
if ( $this->is_category && 'category' === $this->queried_object->taxonomy ) {
_make_cat_compat( $this->queried_object );
}
}
} elseif ( $this->is_post_type_archive ) {
$post_type = $this->get( 'post_type' );
if ( is_array( $post_type ) ) {
$post_type = reset( $post_type );
}
$this->queried_object = get_post_type_object( $post_type );
} elseif ( $this->is_posts_page ) {
$page_for_posts = get_option( 'page_for_posts' );
$this->queried_object = get_post( $page_for_posts );
$this->queried_object_id = (int) $this->queried_object->ID;
} elseif ( $this->is_singular && ! empty( $this->post ) ) {
$this->queried_object = $this->post;
$this->queried_object_id = (int) $this->post->ID;
} elseif ( $this->is_author ) {
$author = (int) $this->get( 'author' );
$author_name = $this->get( 'author_name' );
if ( $author ) {
$this->queried_object_id = $author;
} elseif ( $author_name ) {
$user = get_user_by( 'slug', $author_name );
if ( $user ) {
$this->queried_object_id = $user->ID;
}
}
$this->queried_object = get_userdata( $this->queried_object_id );
}
return $this->queried_object;
}
/**
* Retrieves the ID of the currently queried object.
*
* @since 1.5.0
*
* @return int
*/
public function get_queried_object_id() {
$this->get_queried_object();
if ( isset( $this->queried_object_id ) ) {
return $this->queried_object_id;
}
return 0;
}
/**
* Constructor.
*
* Sets up the WordPress query, if parameter is not empty.
*
* @since 1.5.0
*
* @see WP_Query::parse_query() for all available arguments.
*
* @param string|array $query URL query string or array of vars.
*/
public function __construct( $query = '' ) {
if ( ! empty( $query ) ) {
$this->query( $query );
}
}
/**
* 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 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 );
}
}
/**
* 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 ( in_array( $name, $this->compat_methods, true ) ) {
return $this->$name( ...$arguments );
}
return false;
}
/**
* Is the query for an existing archive page?
*
* Archive pages include category, tag, author, date, custom post type,
* and custom taxonomy based archives.
*
* @since 3.1.0
*
* @see WP_Query::is_category()
* @see WP_Query::is_tag()
* @see WP_Query::is_author()
* @see WP_Query::is_date()
* @see WP_Query::is_post_type_archive()
* @see WP_Query::is_tax()
*
* @return bool Whether the query is for an existing archive page.
*/
public function is_archive() {
return (bool) $this->is_archive;
}
/**
* Is the query for an existing post type archive page?
*
* @since 3.1.0
*
* @param string|string[] $post_types Optional. Post type or array of posts types
* to check against. Default empty.
* @return bool Whether the query is for an existing post type archive page.
*/
public function is_post_type_archive( $post_types = '' ) {
if ( empty( $post_types ) || ! $this->is_post_type_archive ) {
return (bool) $this->is_post_type_archive;
}
$post_type = $this->get( 'post_type' );
if ( is_array( $post_type ) ) {
$post_type = reset( $post_type );
}
$post_type_object = get_post_type_object( $post_type );
if ( ! $post_type_object ) {
return false;
}
return in_array( $post_type_object->name, (array) $post_types, true );
}
/**
* Is the query for an existing attachment page?
*
* @since 3.1.0
*
* @param int|string|int[]|string[] $attachment Optional. Attachment ID, title, slug, or array of such
* to check against. Default empty.
* @return bool Whether the query is for an existing attachment page.
*/
public function is_attachment( $attachment = '' ) {
if ( ! $this->is_attachment ) {
return false;
}
if ( empty( $attachment ) ) {
return true;
}
$attachment = array_map( 'strval', (array) $attachment );
$post_obj = $this->get_queried_object();
if ( ! $post_obj ) {
return false;
}
if ( in_array( (string) $post_obj->ID, $attachment, true ) ) {
return true;
} elseif ( in_array( $post_obj->post_title, $attachment, true ) ) {
return true;
} elseif ( in_array( $post_obj->post_name, $attachment, true ) ) {
return true;
}
return false;
}
/**
* Is the query for an existing author archive page?
*
* If the $author parameter is specified, this function will additionally
* check if the query is for one of the authors specified.
*
* @since 3.1.0
*
* @param int|string|int[]|string[] $author Optional. User ID, nickname, nicename, or array of such
* to check against. Default empty.
* @return bool Whether the query is for an existing author archive page.
*/
public function is_author( $author = '' ) {
if ( ! $this->is_author ) {
return false;
}
if ( empty( $author ) ) {
return true;
}
$author_obj = $this->get_queried_object();
if ( ! $author_obj ) {
return false;
}
$author = array_map( 'strval', (array) $author );
if ( in_array( (string) $author_obj->ID, $author, true ) ) {
return true;
} elseif ( in_array( $author_obj->nickname, $author, true ) ) {
return true;
} elseif ( in_array( $author_obj->user_nicename, $author, true ) ) {
return true;
}
return false;
}
/**
* Is the query for an existing category archive page?
*
* If the $category parameter is specified, this function will additionally
* check if the query is for one of the categories specified.
*
* @since 3.1.0
*
* @param int|string|int[]|string[] $category Optional. Category ID, name, slug, or array of such
* to check against. Default empty.
* @return bool Whether the query is for an existing category archive page.
*/
public function is_category( $category = '' ) {
if ( ! $this->is_category ) {
return false;
}
if ( empty( $category ) ) {
return true;
}
$cat_obj = $this->get_queried_object();
if ( ! $cat_obj ) {
return false;
}
$category = array_map( 'strval', (array) $category );
if ( in_array( (string) $cat_obj->term_id, $category, true ) ) {
return true;
} elseif ( in_array( $cat_obj->name, $category, true ) ) {
return true;
} elseif ( in_array( $cat_obj->slug, $category, true ) ) {
return true;
}
return false;
}
/**
* Is the query for an existing tag archive page?
*
* If the $tag parameter is specified, this function will additionally
* check if the query is for one of the tags specified.
*
* @since 3.1.0
*
* @param int|string|int[]|string[] $tag Optional. Tag ID, name, slug, or array of such
* to check against. Default empty.
* @return bool Whether the query is for an existing tag archive page.
*/
public function is_tag( $tag = '' ) {
if ( ! $this->is_tag ) {
return false;
}
if ( empty( $tag ) ) {
return true;
}
$tag_obj = $this->get_queried_object();
if ( ! $tag_obj ) {
return false;
}
$tag = array_map( 'strval', (array) $tag );
if ( in_array( (string) $tag_obj->term_id, $tag, true ) ) {
return true;
} elseif ( in_array( $tag_obj->name, $tag, true ) ) {
return true;
} elseif ( in_array( $tag_obj->slug, $tag, true ) ) {
return true;
}
return false;
}
/**
* Is the query for an existing custom taxonomy archive page?
*
* If the $taxonomy parameter is specified, this function will additionally
* check if the query is for that specific $taxonomy.
*
* If the $term parameter is specified in addition to the $taxonomy parameter,
* this function will additionally check if the query is for one of the terms
* specified.
*
* @since 3.1.0
*
* @global WP_Taxonomy[] $wp_taxonomies Registered taxonomies.
*
* @param string|string[] $taxonomy Optional. Taxonomy slug or slugs to check against.
* Default empty.
* @param int|string|int[]|string[] $term Optional. Term ID, name, slug, or array of such
* to check against. Default empty.
* @return bool Whether the query is for an existing custom taxonomy archive page.
* True for custom taxonomy archive pages, false for built-in taxonomies
* (category and tag archives).
*/
public function is_tax( $taxonomy = '', $term = '' ) {
global $wp_taxonomies;
if ( ! $this->is_tax ) {
return false;
}
if ( empty( $taxonomy ) ) {
return true;
}
$queried_object = $this->get_queried_object();
$tax_array = array_intersect( array_keys( $wp_taxonomies ), (array) $taxonomy );
$term_array = (array) $term;
// Check that the taxonomy matches.
if ( ! ( isset( $queried_object->taxonomy ) && count( $tax_array ) && in_array( $queried_object->taxonomy, $tax_array, true ) ) ) {
return false;
}
// Only a taxonomy provided.
if ( empty( $term ) ) {
return true;
}
return isset( $queried_object->term_id ) &&
count(
array_intersect(
array( $queried_object->term_id, $queried_object->name, $queried_object->slug ),
$term_array
)
);
}
/**
* Whether the current URL is within the comments popup window.
*
* @since 3.1.0
* @deprecated 4.5.0
*
* @return false Always returns false.
*/
public function is_comments_popup() {
_deprecated_function( __FUNCTION__, '4.5.0' );
return false;
}
/**
* Is the query for an existing date archive?
*
* @since 3.1.0
*
* @return bool Whether the query is for an existing date archive.
*/
public function is_date() {
return (bool) $this->is_date;
}
/**
* Is the query for an existing day archive?
*
* @since 3.1.0
*
* @return bool Whether the query is for an existing day archive.
*/
public function is_day() {
return (bool) $this->is_day;
}
/**
* Is the query for a feed?
*
* @since 3.1.0
*
* @param string|string[] $feeds Optional. Feed type or array of feed types
* to check against. Default empty.
* @return bool Whether the query is for a feed.
*/
public function is_feed( $feeds = '' ) {
if ( empty( $feeds ) || ! $this->is_feed ) {
return (bool) $this->is_feed;
}
$qv = $this->get( 'feed' );
if ( 'feed' === $qv ) {
$qv = get_default_feed();
}
return in_array( $qv, (array) $feeds, true );
}
/**
* Is the query for a comments feed?
*
* @since 3.1.0
*
* @return bool Whether the query is for a comments feed.
*/
public function is_comment_feed() {
return (bool) $this->is_comment_feed;
}
/**
* Is the query for the front page of the site?
*
* This is for what is displayed at your site's main URL.
*
* Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'.
*
* If you set a static page for the front page of your site, this function will return
* true when viewing that page.
*
* Otherwise the same as @see WP_Query::is_home()
*
* @since 3.1.0
*
* @return bool Whether the query is for the front page of the site.
*/
public function is_front_page() {
// Most likely case.
if ( 'posts' === get_option( 'show_on_front' ) && $this->is_home() ) {
return true;
} elseif ( 'page' === get_option( 'show_on_front' ) && get_option( 'page_on_front' )
&& $this->is_page( get_option( 'page_on_front' ) )
) {
return true;
} else {
return false;
}
}
/**
* Is the query for the blog homepage?
*
* This is the page which shows the time based blog content of your site.
*
* Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'.
*
* If you set a static page for the front page of your site, this function will return
* true only on the page you set as the "Posts page".
*
* @since 3.1.0
*
* @see WP_Query::is_front_page()
*
* @return bool Whether the query is for the blog homepage.
*/
public function is_home() {
return (bool) $this->is_home;
}
/**
* Is the query for the Privacy Policy page?
*
* This is the page which shows the Privacy Policy content of your site.
*
* Depends on the site's "Change your Privacy Policy page" Privacy Settings 'wp_page_for_privacy_policy'.
*
* This function will return true only on the page you set as the "Privacy Policy page".
*
* @since 5.2.0
*
* @return bool Whether the query is for the Privacy Policy page.
*/
public function is_privacy_policy() {
if ( get_option( 'wp_page_for_privacy_policy' )
&& $this->is_page( get_option( 'wp_page_for_privacy_policy' ) )
) {
return true;
} else {
return false;
}
}
/**
* Is the query for an existing month archive?
*
* @since 3.1.0
*
* @return bool Whether the query is for an existing month archive.
*/
public function is_month() {
return (bool) $this->is_month;
}
/**
* Is the query for an existing single page?
*
* If the $page parameter is specified, this function will additionally
* check if the query is for one of the pages specified.
*
* @since 3.1.0
*
* @see WP_Query::is_single()
* @see WP_Query::is_singular()
*
* @param int|string|int[]|string[] $page Optional. Page ID, title, slug, path, or array of such
* to check against. Default empty.
* @return bool Whether the query is for an existing single page.
*/
public function is_page( $page = '' ) {
if ( ! $this->is_page ) {
return false;
}
if ( empty( $page ) ) {
return true;
}
$page_obj = $this->get_queried_object();
if ( ! $page_obj ) {
return false;
}
$page = array_map( 'strval', (array) $page );
if ( in_array( (string) $page_obj->ID, $page, true ) ) {
return true;
} elseif ( in_array( $page_obj->post_title, $page, true ) ) {
return true;
} elseif ( in_array( $page_obj->post_name, $page, true ) ) {
return true;
} else {
foreach ( $page as $pagepath ) {
if ( ! strpos( $pagepath, '/' ) ) {
continue;
}
$pagepath_obj = get_page_by_path( $pagepath );
if ( $pagepath_obj && ( $pagepath_obj->ID == $page_obj->ID ) ) {
return true;
}
}
}
return false;
}
/**
* Is the query for a paged result and not for the first page?
*
* @since 3.1.0
*
* @return bool Whether the query is for a paged result.
*/
public function is_paged() {
return (bool) $this->is_paged;
}
/**
* Is the query for a post or page preview?
*
* @since 3.1.0
*
* @return bool Whether the query is for a post or page preview.
*/
public function is_preview() {
return (bool) $this->is_preview;
}
/**
* Is the query for the robots.txt file?
*
* @since 3.1.0
*
* @return bool Whether the query is for the robots.txt file.
*/
public function is_robots() {
return (bool) $this->is_robots;
}
/**
* Is the query for the favicon.ico file?
*
* @since 5.4.0
*
* @return bool Whether the query is for the favicon.ico file.
*/
public function is_favicon() {
return (bool) $this->is_favicon;
}
/**
* Is the query for a search?
*
* @since 3.1.0
*
* @return bool Whether the query is for a search.
*/
public function is_search() {
return (bool) $this->is_search;
}
/**
* Is the query for an existing single post?
*
* Works for any post type excluding pages.
*
* If the $post parameter is specified, this function will additionally
* check if the query is for one of the Posts specified.
*
* @since 3.1.0
*
* @see WP_Query::is_page()
* @see WP_Query::is_singular()
*
* @param int|string|int[]|string[] $post Optional. Post ID, title, slug, path, or array of such
* to check against. Default empty.
* @return bool Whether the query is for an existing single post.
*/
public function is_single( $post = '' ) {
if ( ! $this->is_single ) {
return false;
}
if ( empty( $post ) ) {
return true;
}
$post_obj = $this->get_queried_object();
if ( ! $post_obj ) {
return false;
}
$post = array_map( 'strval', (array) $post );
if ( in_array( (string) $post_obj->ID, $post, true ) ) {
return true;
} elseif ( in_array( $post_obj->post_title, $post, true ) ) {
return true;
} elseif ( in_array( $post_obj->post_name, $post, true ) ) {
return true;
} else {
foreach ( $post as $postpath ) {
if ( ! strpos( $postpath, '/' ) ) {
continue;
}
$postpath_obj = get_page_by_path( $postpath, OBJECT, $post_obj->post_type );
if ( $postpath_obj && ( $postpath_obj->ID == $post_obj->ID ) ) {
return true;
}
}
}
return false;
}
/**
* Is the query for an existing single post of any post type (post, attachment, page,
* custom post types)?
*
* If the $post_types parameter is specified, this function will additionally
* check if the query is for one of the Posts Types specified.
*
* @since 3.1.0
*
* @see WP_Query::is_page()
* @see WP_Query::is_single()
*
* @param string|string[] $post_types Optional. Post type or array of post types
* to check against. Default empty.
* @return bool Whether the query is for an existing single post
* or any of the given post types.
*/
public function is_singular( $post_types = '' ) {
if ( empty( $post_types ) || ! $this->is_singular ) {
return (bool) $this->is_singular;
}
$post_obj = $this->get_queried_object();
if ( ! $post_obj ) {
return false;
}
return in_array( $post_obj->post_type, (array) $post_types, true );
}
/**
* Is the query for a specific time?
*
* @since 3.1.0
*
* @return bool Whether the query is for a specific time.
*/
public function is_time() {
return (bool) $this->is_time;
}
/**
* Is the query for a trackback endpoint call?
*
* @since 3.1.0
*
* @return bool Whether the query is for a trackback endpoint call.
*/
public function is_trackback() {
return (bool) $this->is_trackback;
}
/**
* Is the query for an existing year archive?
*
* @since 3.1.0
*
* @return bool Whether the query is for an existing year archive.
*/
public function is_year() {
return (bool) $this->is_year;
}
/**
* Is the query a 404 (returns no results)?
*
* @since 3.1.0
*
* @return bool Whether the query is a 404 error.
*/
public function is_404() {
return (bool) $this->is_404;
}
/**
* Is the query for an embedded post?
*
* @since 4.4.0
*
* @return bool Whether the query is for an embedded post.
*/
public function is_embed() {
return (bool) $this->is_embed;
}
/**
* Is the query the main query?
*
* @since 3.3.0
*
* @global WP_Query $wp_query WordPress Query object.
*
* @return bool Whether the query is the main query.
*/
public function is_main_query() {
global $wp_the_query;
return $wp_the_query === $this;
}
/**
* Set up global post data.
*
* @since 4.1.0
* @since 4.4.0 Added the ability to pass a post ID to `$post`.
*
* @global int $id
* @global WP_User $authordata
* @global string $currentday
* @global string $currentmonth
* @global int $page
* @global array $pages
* @global int $multipage
* @global int $more
* @global int $numpages
*
* @param WP_Post|object|int $post WP_Post instance or Post ID/object.
* @return true True when finished.
*/
public function setup_postdata( $post ) {
global $id, $authordata, $currentday, $currentmonth, $page, $pages, $multipage, $more, $numpages;
if ( ! ( $post instanceof WP_Post ) ) {
$post = get_post( $post );
}
if ( ! $post ) {
return;
}
$elements = $this->generate_postdata( $post );
if ( false === $elements ) {
return;
}
$id = $elements['id'];
$authordata = $elements['authordata'];
$currentday = $elements['currentday'];
$currentmonth = $elements['currentmonth'];
$page = $elements['page'];
$pages = $elements['pages'];
$multipage = $elements['multipage'];
$more = $elements['more'];
$numpages = $elements['numpages'];
/**
* Fires once the post data has been set up.
*
* @since 2.8.0
* @since 4.1.0 Introduced `$query` parameter.
*
* @param WP_Post $post The Post object (passed by reference).
* @param WP_Query $query The current Query object (passed by reference).
*/
do_action_ref_array( 'the_post', array( &$post, &$this ) );
return true;
}
/**
* Generate post data.
*
* @since 5.2.0
*
* @param WP_Post|object|int $post WP_Post instance or Post ID/object.
* @return array|false Elements of post or false on failure.
*/
public function generate_postdata( $post ) {
if ( ! ( $post instanceof WP_Post ) ) {
$post = get_post( $post );
}
if ( ! $post ) {
return false;
}
$id = (int) $post->ID;
$authordata = get_userdata( $post->post_author );
$currentday = mysql2date( 'd.m.y', $post->post_date, false );
$currentmonth = mysql2date( 'm', $post->post_date, false );
$numpages = 1;
$multipage = 0;
$page = $this->get( 'page' );
if ( ! $page ) {
$page = 1;
}
/*
* Force full post content when viewing the permalink for the $post,
* or when on an RSS feed. Otherwise respect the 'more' tag.
*/
if ( get_queried_object_id() === $post->ID && ( $this->is_page() || $this->is_single() ) ) {
$more = 1;
} elseif ( $this->is_feed() ) {
$more = 1;
} else {
$more = 0;
}
$content = $post->post_content;
if ( false !== strpos( $content, '<!--nextpage-->' ) ) {
$content = str_replace( "\n<!--nextpage-->\n", '<!--nextpage-->', $content );
$content = str_replace( "\n<!--nextpage-->", '<!--nextpage-->', $content );
$content = str_replace( "<!--nextpage-->\n", '<!--nextpage-->', $content );
// Remove the nextpage block delimiters, to avoid invalid block structures in the split content.
$content = str_replace( '<!-- wp:nextpage -->', '', $content );
$content = str_replace( '<!-- /wp:nextpage -->', '', $content );
// Ignore nextpage at the beginning of the content.
if ( 0 === strpos( $content, '<!--nextpage-->' ) ) {
$content = substr( $content, 15 );
}
$pages = explode( '<!--nextpage-->', $content );
} else {
$pages = array( $post->post_content );
}
/**
* Filters the "pages" derived from splitting the post content.
*
* "Pages" are determined by splitting the post content based on the presence
* of `<!-- nextpage -->` tags.
*
* @since 4.4.0
*
* @param string[] $pages Array of "pages" from the post content split by `<!-- nextpage -->` tags.
* @param WP_Post $post Current post object.
*/
$pages = apply_filters( 'content_pagination', $pages, $post );
$numpages = count( $pages );
if ( $numpages > 1 ) {
if ( $page > 1 ) {
$more = 1;
}
$multipage = 1;
} else {
$multipage = 0;
}
$elements = compact( 'id', 'authordata', 'currentday', 'currentmonth', 'page', 'pages', 'multipage', 'more', 'numpages' );
return $elements;
}
/**
* Generate cache key.
*
* @since 6.1.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param array $args Query arguments.
* @param string $sql SQL statement.
*
* @return string Cache key.
*/
protected function generate_cache_key( array $args, $sql ) {
global $wpdb;
unset(
$args['cache_results'],
$args['fields'],
$args['lazy_load_term_meta'],
$args['update_post_meta_cache'],
$args['update_post_term_cache'],
$args['update_menu_item_cache'],
$args['suppress_filters']
);
$placeholder = $wpdb->placeholder_escape();
array_walk_recursive(
$args,
/*
* Replace wpdb placeholders with the string used in the database
* query to avoid unreachable cache keys. This is necessary because
* the placeholder is randomly generated in each request.
*
* $value is passed by reference to allow it to be modified.
* array_walk_recursive() does not return an array.
*/
function ( &$value ) use ( $wpdb, $placeholder ) {
if ( is_string( $value ) && str_contains( $value, $placeholder ) ) {
$value = $wpdb->remove_placeholder_escape( $value );
}
}
);
// Replace wpdb placeholder in the SQL statement used by the cache key.
$sql = $wpdb->remove_placeholder_escape( $sql );
$key = md5( serialize( $args ) . $sql );
$last_changed = wp_cache_get_last_changed( 'posts' );
if ( ! empty( $this->tax_query->queries ) ) {
$last_changed .= wp_cache_get_last_changed( 'terms' );
}
return "wp_query:$key:$last_changed";
}
/**
* After looping through a nested query, this function
* restores the $post global to the current post in this query.
*
* @since 3.7.0
*
* @global WP_Post $post Global post object.
*/
public function reset_postdata() {
if ( ! empty( $this->post ) ) {
$GLOBALS['post'] = $this->post;
$this->setup_postdata( $this->post );
}
}
/**
* Lazyload term meta for posts in the loop.
*
* @since 4.4.0
* @deprecated 4.5.0 See wp_queue_posts_for_term_meta_lazyload().
*
* @param mixed $check
* @param int $term_id
* @return mixed
*/
public function lazyload_term_meta( $check, $term_id ) {
_deprecated_function( __METHOD__, '4.5.0' );
return $check;
}
/**
* Lazyload comment meta for comments in the loop.
*
* @since 4.4.0
* @deprecated 4.5.0 See wp_queue_comments_for_comment_meta_lazyload().
*
* @param mixed $check
* @param int $comment_id
* @return mixed
*/
public function lazyload_comment_meta( $check, $comment_id ) {
_deprecated_function( __METHOD__, '4.5.0' );
return $check;
}
}
```
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Removed the `$comments_popup` property. |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
| programming_docs |
wordpress class WP_Http_Cookie {} class WP\_Http\_Cookie {}
=========================
Core class used to encapsulate a single cookie object for internal use.
Returned cookies are represented using this class, and when cookies are set, if they are not already a [WP\_Http\_Cookie](wp_http_cookie)() object, then they are turned into one.
* [\_\_construct](wp_http_cookie/__construct) — Sets up this cookie object.
* [get\_attributes](wp_http_cookie/get_attributes) — Retrieves cookie attributes.
* [getFullHeader](wp_http_cookie/getfullheader) — Retrieve cookie header for usage in the rest of the WordPress HTTP API.
* [getHeaderValue](wp_http_cookie/getheadervalue) — Convert cookie name and value back to header string.
* [test](wp_http_cookie/test) — Confirms that it's OK to send this cookie to the URL checked against.
File: `wp-includes/class-wp-http-cookie.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-http-cookie.php/)
```
class WP_Http_Cookie {
/**
* Cookie name.
*
* @since 2.8.0
*
* @var string
*/
public $name;
/**
* Cookie value.
*
* @since 2.8.0
*
* @var string
*/
public $value;
/**
* When the cookie expires. Unix timestamp or formatted date.
*
* @since 2.8.0
*
* @var string|int|null
*/
public $expires;
/**
* Cookie URL path.
*
* @since 2.8.0
*
* @var string
*/
public $path;
/**
* Cookie Domain.
*
* @since 2.8.0
*
* @var string
*/
public $domain;
/**
* Cookie port or comma-separated list of ports.
*
* @since 2.8.0
*
* @var int|string
*/
public $port;
/**
* host-only flag.
*
* @since 5.2.0
*
* @var bool
*/
public $host_only;
/**
* Sets up this cookie object.
*
* The parameter $data should be either an associative array containing the indices names below
* or a header string detailing it.
*
* @since 2.8.0
* @since 5.2.0 Added `host_only` to the `$data` parameter.
*
* @param string|array $data {
* Raw cookie data as header string or data array.
*
* @type string $name Cookie name.
* @type mixed $value Value. Should NOT already be urlencoded.
* @type string|int|null $expires Optional. Unix timestamp or formatted date. Default null.
* @type string $path Optional. Path. Default '/'.
* @type string $domain Optional. Domain. Default host of parsed $requested_url.
* @type int|string $port Optional. Port or comma-separated list of ports. Default null.
* @type bool $host_only Optional. host-only storage flag. Default true.
* }
* @param string $requested_url The URL which the cookie was set on, used for default $domain
* and $port values.
*/
public function __construct( $data, $requested_url = '' ) {
if ( $requested_url ) {
$parsed_url = parse_url( $requested_url );
}
if ( isset( $parsed_url['host'] ) ) {
$this->domain = $parsed_url['host'];
}
$this->path = isset( $parsed_url['path'] ) ? $parsed_url['path'] : '/';
if ( '/' !== substr( $this->path, -1 ) ) {
$this->path = dirname( $this->path ) . '/';
}
if ( is_string( $data ) ) {
// Assume it's a header string direct from a previous request.
$pairs = explode( ';', $data );
// Special handling for first pair; name=value. Also be careful of "=" in value.
$name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) );
$value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 );
$this->name = $name;
$this->value = urldecode( $value );
// Removes name=value from items.
array_shift( $pairs );
// Set everything else as a property.
foreach ( $pairs as $pair ) {
$pair = rtrim( $pair );
// Handle the cookie ending in ; which results in a empty final pair.
if ( empty( $pair ) ) {
continue;
}
list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' );
$key = strtolower( trim( $key ) );
if ( 'expires' === $key ) {
$val = strtotime( $val );
}
$this->$key = $val;
}
} else {
if ( ! isset( $data['name'] ) ) {
return;
}
// Set properties based directly on parameters.
foreach ( array( 'name', 'value', 'path', 'domain', 'port', 'host_only' ) as $field ) {
if ( isset( $data[ $field ] ) ) {
$this->$field = $data[ $field ];
}
}
if ( isset( $data['expires'] ) ) {
$this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] );
} else {
$this->expires = null;
}
}
}
/**
* Confirms that it's OK to send this cookie to the URL checked against.
*
* Decision is based on RFC 2109/2965, so look there for details on validity.
*
* @since 2.8.0
*
* @param string $url URL you intend to send this cookie to
* @return bool true if allowed, false otherwise.
*/
public function test( $url ) {
if ( is_null( $this->name ) ) {
return false;
}
// Expires - if expired then nothing else matters.
if ( isset( $this->expires ) && time() > $this->expires ) {
return false;
}
// Get details on the URL we're thinking about sending to.
$url = parse_url( $url );
$url['port'] = isset( $url['port'] ) ? $url['port'] : ( 'https' === $url['scheme'] ? 443 : 80 );
$url['path'] = isset( $url['path'] ) ? $url['path'] : '/';
// Values to use for comparison against the URL.
$path = isset( $this->path ) ? $this->path : '/';
$port = isset( $this->port ) ? $this->port : null;
$domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] );
if ( false === stripos( $domain, '.' ) ) {
$domain .= '.local';
}
// Host - very basic check that the request URL ends with the domain restriction (minus leading dot).
$domain = ( '.' === substr( $domain, 0, 1 ) ) ? substr( $domain, 1 ) : $domain;
if ( substr( $url['host'], -strlen( $domain ) ) !== $domain ) {
return false;
}
// Port - supports "port-lists" in the format: "80,8000,8080".
if ( ! empty( $port ) && ! in_array( $url['port'], array_map( 'intval', explode( ',', $port ) ), true ) ) {
return false;
}
// Path - request path must start with path restriction.
if ( substr( $url['path'], 0, strlen( $path ) ) !== $path ) {
return false;
}
return true;
}
/**
* Convert cookie name and value back to header string.
*
* @since 2.8.0
*
* @return string Header encoded cookie name and value.
*/
public function getHeaderValue() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
if ( ! isset( $this->name ) || ! isset( $this->value ) ) {
return '';
}
/**
* Filters the header-encoded cookie value.
*
* @since 3.4.0
*
* @param string $value The cookie value.
* @param string $name The cookie name.
*/
return $this->name . '=' . apply_filters( 'wp_http_cookie_value', $this->value, $this->name );
}
/**
* Retrieve cookie header for usage in the rest of the WordPress HTTP API.
*
* @since 2.8.0
*
* @return string
*/
public function getFullHeader() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
return 'Cookie: ' . $this->getHeaderValue();
}
/**
* Retrieves cookie attributes.
*
* @since 4.6.0
*
* @return array {
* List of attributes.
*
* @type string|int|null $expires When the cookie expires. Unix timestamp or formatted date.
* @type string $path Cookie URL path.
* @type string $domain Cookie domain.
* }
*/
public function get_attributes() {
return array(
'expires' => $this->expires,
'path' => $this->path,
'domain' => $this->domain,
);
}
}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress class Requests_Exception_HTTP_414 {} class Requests\_Exception\_HTTP\_414 {}
=======================================
Exception for 414 Request-URI Too Large responses
File: `wp-includes/Requests/Exception/HTTP/414.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/414.php/)
```
class Requests_Exception_HTTP_414 extends Requests_Exception_HTTP {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 414;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Request-URI Too Large';
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response |
wordpress class WP_Widget_Meta {} class WP\_Widget\_Meta {}
=========================
Core class used to implement a Meta widget.
Displays log in/out, RSS feed links, etc.
* [WP\_Widget](wp_widget)
* [\_\_construct](wp_widget_meta/__construct) — Sets up a new Meta widget instance.
* [form](wp_widget_meta/form) — Outputs the settings form for the Meta widget.
* [update](wp_widget_meta/update) — Handles updating settings for the current Meta widget instance.
* [widget](wp_widget_meta/widget) — Outputs the content for the current Meta widget instance.
File: `wp-includes/widgets/class-wp-widget-meta.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-meta.php/)
```
class WP_Widget_Meta extends WP_Widget {
/**
* Sets up a new Meta widget instance.
*
* @since 2.8.0
*/
public function __construct() {
$widget_ops = array(
'classname' => 'widget_meta',
'description' => __( 'Login, RSS, & WordPress.org links.' ),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
);
parent::__construct( 'meta', __( 'Meta' ), $widget_ops );
}
/**
* Outputs the content for the current Meta 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 Meta widget instance.
*/
public function widget( $args, $instance ) {
$default_title = __( 'Meta' );
$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 );
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 wp_register(); ?>
<li><?php wp_loginout(); ?></li>
<li><a href="<?php echo esc_url( get_bloginfo( 'rss2_url' ) ); ?>"><?php _e( 'Entries feed' ); ?></a></li>
<li><a href="<?php echo esc_url( get_bloginfo( 'comments_rss2_url' ) ); ?>"><?php _e( 'Comments feed' ); ?></a></li>
<?php
/**
* Filters the "WordPress.org" list item HTML in the Meta widget.
*
* @since 3.6.0
* @since 4.9.0 Added the `$instance` parameter.
*
* @param string $html Default HTML for the WordPress.org list item.
* @param array $instance Array of settings for the current widget.
*/
echo apply_filters(
'widget_meta_poweredby',
sprintf(
'<li><a href="%1$s">%2$s</a></li>',
esc_url( __( 'https://wordpress.org/' ) ),
__( 'WordPress.org' )
),
$instance
);
wp_meta();
?>
</ul>
<?php
if ( 'html5' === $format ) {
echo '</nav>';
}
echo $args['after_widget'];
}
/**
* Handles updating settings for the current Meta 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 Meta 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_Customize_Nav_Menu_Location_Control {} class WP\_Customize\_Nav\_Menu\_Location\_Control {}
====================================================
Customize Menu Location Control Class.
This custom control is only needed for JS.
* [WP\_Customize\_Control](wp_customize_control)
* [render\_content](wp_customize_nav_menu_location_control/render_content) — Render content just like a normal select control.
* [to\_json](wp_customize_nav_menu_location_control/to_json) — Refresh the parameters passed to JavaScript via JSON.
File: `wp-includes/customize/class-wp-customize-nav-menu-location-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-location-control.php/)
```
class WP_Customize_Nav_Menu_Location_Control extends WP_Customize_Control {
/**
* Control type.
*
* @since 4.3.0
* @var string
*/
public $type = 'nav_menu_location';
/**
* Location ID.
*
* @since 4.3.0
* @var string
*/
public $location_id = '';
/**
* Refresh the parameters passed to JavaScript via JSON.
*
* @since 4.3.0
*
* @see WP_Customize_Control::to_json()
*/
public function to_json() {
parent::to_json();
$this->json['locationId'] = $this->location_id;
}
/**
* Render content just like a normal select control.
*
* @since 4.3.0
* @since 4.9.0 Added a button to create menus.
*/
public function render_content() {
if ( empty( $this->choices ) ) {
return;
}
$value_hidden_class = '';
$no_value_hidden_class = '';
if ( $this->value() ) {
$value_hidden_class = ' hidden';
} else {
$no_value_hidden_class = ' hidden';
}
?>
<label>
<?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 class="description customize-control-description"><?php echo $this->description; ?></span>
<?php endif; ?>
<select <?php $this->link(); ?>>
<?php
foreach ( $this->choices as $value => $label ) :
echo '<option value="' . esc_attr( $value ) . '"' . selected( $this->value(), $value, false ) . '>' . $label . '</option>';
endforeach;
?>
</select>
</label>
<button type="button" class="button-link create-menu<?php echo $value_hidden_class; ?>" data-location-id="<?php echo esc_attr( $this->location_id ); ?>" aria-label="<?php esc_attr_e( 'Create a menu for this location' ); ?>"><?php _e( '+ Create New Menu' ); ?></button>
<button type="button" class="button-link edit-menu<?php echo $no_value_hidden_class; ?>" aria-label="<?php esc_attr_e( 'Edit selected menu' ); ?>"><?php _e( 'Edit Menu' ); ?></button>
<?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 Walker_Page {} class Walker\_Page {}
=====================
Core walker class used to create an HTML list of pages.
* [Walker](walker)
The [Walker\_Page](walker_page) class was implemented to help create HTML list of pages. It extends the [Walker](walker) class. You can also extend this class to add your own logic.
* [end\_el](walker_page/end_el) — Outputs the end of the current element in the tree.
* [end\_lvl](walker_page/end_lvl) — Outputs the end of the current level in the tree after elements are output.
* [start\_el](walker_page/start_el) — Outputs the beginning of the current element in the tree.
* [start\_lvl](walker_page/start_lvl) — Outputs the beginning of the current level in the tree before elements are output.
File: `wp-includes/class-walker-page.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-page.php/)
```
class Walker_Page extends Walker {
/**
* What the class handles.
*
* @since 2.1.0
* @var string
*
* @see Walker::$tree_type
*/
public $tree_type = 'page';
/**
* Database fields to use.
*
* @since 2.1.0
* @var string[]
*
* @see Walker::$db_fields
* @todo Decouple this.
*/
public $db_fields = array(
'parent' => 'post_parent',
'id' => 'ID',
);
/**
* Outputs the beginning of the current level in the tree before elements are output.
*
* @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 page. Used for padding. Default 0.
* @param array $args Optional. Arguments for outputting the next level.
* Default empty array.
*/
public function start_lvl( &$output, $depth = 0, $args = array() ) {
if ( isset( $args['item_spacing'] ) && 'preserve' === $args['item_spacing'] ) {
$t = "\t";
$n = "\n";
} else {
$t = '';
$n = '';
}
$indent = str_repeat( $t, $depth );
$output .= "{$n}{$indent}<ul class='children'>{$n}";
}
/**
* Outputs the end of the current level in the tree after elements are output.
*
* @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 page. Used for padding. Default 0.
* @param array $args Optional. Arguments for outputting the end of the current level.
* Default empty array.
*/
public function end_lvl( &$output, $depth = 0, $args = array() ) {
if ( isset( $args['item_spacing'] ) && 'preserve' === $args['item_spacing'] ) {
$t = "\t";
$n = "\n";
} else {
$t = '';
$n = '';
}
$indent = str_repeat( $t, $depth );
$output .= "{$indent}</ul>{$n}";
}
/**
* Outputs the beginning of the current element in the tree.
*
* @see Walker::start_el()
* @since 2.1.0
* @since 5.9.0 Renamed `$page` to `$data_object` and `$current_page` 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_Post $data_object Page data object.
* @param int $depth Optional. Depth of page. Used for padding. Default 0.
* @param array $args Optional. Array of arguments. Default empty array.
* @param int $current_object_id Optional. ID of the current page. 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.
$page = $data_object;
$current_page_id = $current_object_id;
if ( isset( $args['item_spacing'] ) && 'preserve' === $args['item_spacing'] ) {
$t = "\t";
$n = "\n";
} else {
$t = '';
$n = '';
}
if ( $depth ) {
$indent = str_repeat( $t, $depth );
} else {
$indent = '';
}
$css_class = array( 'page_item', 'page-item-' . $page->ID );
if ( isset( $args['pages_with_children'][ $page->ID ] ) ) {
$css_class[] = 'page_item_has_children';
}
if ( ! empty( $current_page_id ) ) {
$_current_page = get_post( $current_page_id );
if ( $_current_page && in_array( $page->ID, $_current_page->ancestors, true ) ) {
$css_class[] = 'current_page_ancestor';
}
if ( $page->ID == $current_page_id ) {
$css_class[] = 'current_page_item';
} elseif ( $_current_page && $page->ID === $_current_page->post_parent ) {
$css_class[] = 'current_page_parent';
}
} elseif ( get_option( 'page_for_posts' ) == $page->ID ) {
$css_class[] = 'current_page_parent';
}
/**
* Filters the list of CSS classes to include with each page item in the list.
*
* @since 2.8.0
*
* @see wp_list_pages()
*
* @param string[] $css_class An array of CSS classes to be applied to each list item.
* @param WP_Post $page Page data object.
* @param int $depth Depth of page, used for padding.
* @param array $args An array of arguments.
* @param int $current_page_id ID of the current page.
*/
$css_classes = implode( ' ', apply_filters( 'page_css_class', $css_class, $page, $depth, $args, $current_page_id ) );
$css_classes = $css_classes ? ' class="' . esc_attr( $css_classes ) . '"' : '';
if ( '' === $page->post_title ) {
/* translators: %d: ID of a post. */
$page->post_title = sprintf( __( '#%d (no title)' ), $page->ID );
}
$args['link_before'] = empty( $args['link_before'] ) ? '' : $args['link_before'];
$args['link_after'] = empty( $args['link_after'] ) ? '' : $args['link_after'];
$atts = array();
$atts['href'] = get_permalink( $page->ID );
$atts['aria-current'] = ( $page->ID == $current_page_id ) ? 'page' : '';
/**
* Filters the HTML attributes applied to a page menu item's anchor element.
*
* @since 4.8.0
*
* @param array $atts {
* The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.
*
* @type string $href The href attribute.
* @type string $aria-current The aria-current attribute.
* }
* @param WP_Post $page Page data object.
* @param int $depth Depth of page, used for padding.
* @param array $args An array of arguments.
* @param int $current_page_id ID of the current page.
*/
$atts = apply_filters( 'page_menu_link_attributes', $atts, $page, $depth, $args, $current_page_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 . '"';
}
}
$output .= $indent . sprintf(
'<li%s><a%s>%s%s%s</a>',
$css_classes,
$attributes,
$args['link_before'],
/** This filter is documented in wp-includes/post-template.php */
apply_filters( 'the_title', $page->post_title, $page->ID ),
$args['link_after']
);
if ( ! empty( $args['show_date'] ) ) {
if ( 'modified' === $args['show_date'] ) {
$time = $page->post_modified;
} else {
$time = $page->post_date;
}
$date_format = empty( $args['date_format'] ) ? '' : $args['date_format'];
$output .= ' ' . mysql2date( $date_format, $time );
}
}
/**
* Outputs the end of the current element in the tree.
*
* @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 WP_Post $data_object Page data object. Not used.
* @param int $depth Optional. Depth of page. Default 0 (unused).
* @param array $args Optional. Array of arguments. Default empty array.
*/
public function end_el( &$output, $data_object, $depth = 0, $args = array() ) {
if ( isset( $args['item_spacing'] ) && 'preserve' === $args['item_spacing'] ) {
$t = "\t";
$n = "\n";
} else {
$t = '';
$n = '';
}
$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. |
| programming_docs |
wordpress class Requests_Exception_HTTP_415 {} class Requests\_Exception\_HTTP\_415 {}
=======================================
Exception for 415 Unsupported Media Type responses
File: `wp-includes/Requests/Exception/HTTP/415.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/415.php/)
```
class Requests_Exception_HTTP_415 extends Requests_Exception_HTTP {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 415;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Unsupported Media Type';
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response |
wordpress class WP_REST_User_Meta_Fields {} class WP\_REST\_User\_Meta\_Fields {}
=====================================
Core class used to manage meta values for users via the REST API.
* [WP\_REST\_Meta\_Fields](wp_rest_meta_fields)
* [get\_meta\_subtype](wp_rest_user_meta_fields/get_meta_subtype) — Retrieves the user meta subtype.
* [get\_meta\_type](wp_rest_user_meta_fields/get_meta_type) — Retrieves the user meta type.
* [get\_rest\_field\_type](wp_rest_user_meta_fields/get_rest_field_type) — Retrieves the type for register\_rest\_field().
File: `wp-includes/rest-api/fields/class-wp-rest-user-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-user-meta-fields.php/)
```
class WP_REST_User_Meta_Fields extends WP_REST_Meta_Fields {
/**
* Retrieves the user meta type.
*
* @since 4.7.0
*
* @return string The user meta type.
*/
protected function get_meta_type() {
return 'user';
}
/**
* Retrieves the user meta subtype.
*
* @since 4.9.8
*
* @return string 'user' There are no subtypes.
*/
protected function get_meta_subtype() {
return 'user';
}
/**
* Retrieves the type for register_rest_field().
*
* @since 4.7.0
*
* @return string The user REST field type.
*/
public function get_rest_field_type() {
return 'user';
}
}
```
| 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_atom_server {} class wp\_atom\_server {}
=========================
* [\_\_call](wp_atom_server/__call)
* [\_\_callStatic](wp_atom_server/__callstatic)
File: `wp-includes/pluggable-deprecated.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pluggable-deprecated.php/)
```
class wp_atom_server {
public function __call( $name, $arguments ) {
_deprecated_function( __CLASS__ . '::' . $name, '3.5.0', 'the Atom Publishing Protocol plugin' );
}
public static function __callStatic( $name, $arguments ) {
_deprecated_function( __CLASS__ . '::' . $name, '3.5.0', 'the Atom Publishing Protocol plugin' );
}
}
```
wordpress class Bulk_Plugin_Upgrader_Skin {} class Bulk\_Plugin\_Upgrader\_Skin {}
=====================================
Bulk Plugin Upgrader Skin for WordPress Plugin Upgrades.
* [Bulk\_Upgrader\_Skin](bulk_upgrader_skin)
* [add\_strings](bulk_plugin_upgrader_skin/add_strings)
* [after](bulk_plugin_upgrader_skin/after)
* [before](bulk_plugin_upgrader_skin/before)
* [bulk\_footer](bulk_plugin_upgrader_skin/bulk_footer)
File: `wp-admin/includes/class-bulk-plugin-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-bulk-plugin-upgrader-skin.php/)
```
class Bulk_Plugin_Upgrader_Skin extends Bulk_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();
public function add_strings() {
parent::add_strings();
/* translators: 1: Plugin name, 2: Number of the plugin, 3: Total number of plugins being updated. */
$this->upgrader->strings['skin_before_update_header'] = __( 'Updating Plugin %1$s (%2$d/%3$d)' );
}
/**
* @param string $title
*/
public function before( $title = '' ) {
parent::before( $this->plugin_info['Title'] );
}
/**
* @param string $title
*/
public function after( $title = '' ) {
parent::after( $this->plugin_info['Title'] );
$this->decrement_update_count( 'plugin' );
}
/**
*/
public function bulk_footer() {
parent::bulk_footer();
$update_actions = array(
'plugins_page' => sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'plugins.php' ),
__( 'Go to Plugins page' )
),
'updates_page' => sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'update-core.php' ),
__( 'Go to WordPress Updates page' )
),
);
if ( ! current_user_can( 'activate_plugins' ) ) {
unset( $update_actions['plugins_page'] );
}
/**
* Filters the list of action links available following bulk plugin updates.
*
* @since 3.0.0
*
* @param string[] $update_actions Array of plugin action links.
* @param array $plugin_info Array of information for the last-updated plugin.
*/
$update_actions = apply_filters( 'update_bulk_plugins_complete_actions', $update_actions, $this->plugin_info );
if ( ! empty( $update_actions ) ) {
$this->feedback( implode( ' | ', (array) $update_actions ) );
}
}
}
```
| Uses | Description |
| --- | --- |
| [Bulk\_Upgrader\_Skin](bulk_upgrader_skin) wp-admin/includes/class-bulk-upgrader-skin.php | Generic Bulk Upgrader Skin for 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.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress class WP_REST_Menu_Items_Controller {} class WP\_REST\_Menu\_Items\_Controller {}
==========================================
Core class to access nav items via the REST API.
* [WP\_REST\_Posts\_Controller](wp_rest_posts_controller)
* [check\_has\_read\_only\_access](wp_rest_menu_items_controller/check_has_read_only_access) — Checks whether the current user has read permission for the endpoint.
* [create\_item](wp_rest_menu_items_controller/create_item) — Creates a single post.
* [delete\_item](wp_rest_menu_items_controller/delete_item) — Deletes a single menu item.
* [get\_collection\_params](wp_rest_menu_items_controller/get_collection_params) — Retrieves the query params for the posts collection.
* [get\_item\_permissions\_check](wp_rest_menu_items_controller/get_item_permissions_check) — Checks if a given request has access to read a menu item if they have access to edit them.
* [get\_item\_schema](wp_rest_menu_items_controller/get_item_schema) — Retrieves the term's schema, conforming to JSON Schema.
* [get\_items\_permissions\_check](wp_rest_menu_items_controller/get_items_permissions_check) — Checks if a given request has access to read menu items.
* [get\_menu\_id](wp_rest_menu_items_controller/get_menu_id) — Gets the id of the menu that the given menu item belongs to.
* [get\_nav\_menu\_item](wp_rest_menu_items_controller/get_nav_menu_item) — Gets the nav menu item, if the ID is valid.
* [get\_schema\_links](wp_rest_menu_items_controller/get_schema_links) — Retrieves Link Description Objects that should be added to the Schema for the posts collection.
* [prepare\_item\_for\_database](wp_rest_menu_items_controller/prepare_item_for_database) — Prepares a single post for create or update.
* [prepare\_item\_for\_response](wp_rest_menu_items_controller/prepare_item_for_response) — Prepares a single post output for response.
* [prepare\_items\_query](wp_rest_menu_items_controller/prepare_items_query) — Determines the allowed query\_vars for a get\_items() response and prepares them for WP\_Query.
* [prepare\_links](wp_rest_menu_items_controller/prepare_links) — Prepares links for the request.
* [update\_item](wp_rest_menu_items_controller/update_item) — Updates a single nav menu item.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php/)
```
class WP_REST_Menu_Items_Controller extends WP_REST_Posts_Controller {
/**
* Gets the nav menu item, if the ID is valid.
*
* @since 5.9.0
*
* @param int $id Supplied ID.
* @return object|WP_Error Post object if ID is valid, WP_Error otherwise.
*/
protected function get_nav_menu_item( $id ) {
$post = $this->get_post( $id );
if ( is_wp_error( $post ) ) {
return $post;
}
return wp_setup_nav_menu_item( $post );
}
/**
* Checks if a given request has access to read menu items.
*
* @since 5.9.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 ) {
$has_permission = parent::get_items_permissions_check( $request );
if ( true !== $has_permission ) {
return $has_permission;
}
return $this->check_has_read_only_access( $request );
}
/**
* Checks if a given request has access to read a menu item if they have access to edit them.
*
* @since 5.9.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, WP_Error object otherwise.
*/
public function get_item_permissions_check( $request ) {
$permission_check = parent::get_item_permissions_check( $request );
if ( true !== $permission_check ) {
return $permission_check;
}
return $this->check_has_read_only_access( $request );
}
/**
* Checks whether the current user has read permission for the endpoint.
*
* This allows for any user that can `edit_theme_options` or edit any REST API available post type.
*
* @since 5.9.0
*
* @param WP_REST_Request $request Full details about the request.
* @return bool|WP_Error Whether the current user has permission.
*/
protected function check_has_read_only_access( $request ) {
if ( current_user_can( 'edit_theme_options' ) ) {
return true;
}
if ( current_user_can( 'edit_posts' ) ) {
return true;
}
foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
if ( current_user_can( $post_type->cap->edit_posts ) ) {
return true;
}
}
return new WP_Error(
'rest_cannot_view',
__( 'Sorry, you are not allowed to view menu items.' ),
array( 'status' => rest_authorization_required_code() )
);
}
/**
* Creates a single post.
*
* @since 5.9.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_nav_item = $this->prepare_item_for_database( $request );
if ( is_wp_error( $prepared_nav_item ) ) {
return $prepared_nav_item;
}
$prepared_nav_item = (array) $prepared_nav_item;
$nav_menu_item_id = wp_update_nav_menu_item( $prepared_nav_item['menu-id'], $prepared_nav_item['menu-item-db-id'], wp_slash( $prepared_nav_item ), false );
if ( is_wp_error( $nav_menu_item_id ) ) {
if ( 'db_insert_error' === $nav_menu_item_id->get_error_code() ) {
$nav_menu_item_id->add_data( array( 'status' => 500 ) );
} else {
$nav_menu_item_id->add_data( array( 'status' => 400 ) );
}
return $nav_menu_item_id;
}
$nav_menu_item = $this->get_nav_menu_item( $nav_menu_item_id );
if ( is_wp_error( $nav_menu_item ) ) {
$nav_menu_item->add_data( array( 'status' => 404 ) );
return $nav_menu_item;
}
/**
* Fires after a single menu item is created or updated via the REST API.
*
* @since 5.9.0
*
* @param object $nav_menu_item Inserted or updated menu item object.
* @param WP_REST_Request $request Request object.
* @param bool $creating True when creating a menu item, false when updating.
*/
do_action( 'rest_insert_nav_menu_item', $nav_menu_item, $request, true );
$schema = $this->get_item_schema();
if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
$meta_update = $this->meta->update_value( $request['meta'], $nav_menu_item_id );
if ( is_wp_error( $meta_update ) ) {
return $meta_update;
}
}
$nav_menu_item = $this->get_nav_menu_item( $nav_menu_item_id );
$fields_update = $this->update_additional_fields_for_object( $nav_menu_item, $request );
if ( is_wp_error( $fields_update ) ) {
return $fields_update;
}
$request->set_param( 'context', 'edit' );
/**
* Fires after a single menu item is completely created or updated via the REST API.
*
* @since 5.9.0
*
* @param object $nav_menu_item Inserted or updated menu item object.
* @param WP_REST_Request $request Request object.
* @param bool $creating True when creating a menu item, false when updating.
*/
do_action( 'rest_after_insert_nav_menu_item', $nav_menu_item, $request, true );
$post = get_post( $nav_menu_item_id );
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( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $nav_menu_item_id ) ) );
return $response;
}
/**
* Updates a single nav menu item.
*
* @since 5.9.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_nav_menu_item( $request['id'] );
if ( is_wp_error( $valid_check ) ) {
return $valid_check;
}
$post_before = get_post( $request['id'] );
$prepared_nav_item = $this->prepare_item_for_database( $request );
if ( is_wp_error( $prepared_nav_item ) ) {
return $prepared_nav_item;
}
$prepared_nav_item = (array) $prepared_nav_item;
$nav_menu_item_id = wp_update_nav_menu_item( $prepared_nav_item['menu-id'], $prepared_nav_item['menu-item-db-id'], wp_slash( $prepared_nav_item ), false );
if ( is_wp_error( $nav_menu_item_id ) ) {
if ( 'db_update_error' === $nav_menu_item_id->get_error_code() ) {
$nav_menu_item_id->add_data( array( 'status' => 500 ) );
} else {
$nav_menu_item_id->add_data( array( 'status' => 400 ) );
}
return $nav_menu_item_id;
}
$nav_menu_item = $this->get_nav_menu_item( $nav_menu_item_id );
if ( is_wp_error( $nav_menu_item ) ) {
$nav_menu_item->add_data( array( 'status' => 404 ) );
return $nav_menu_item;
}
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php */
do_action( 'rest_insert_nav_menu_item', $nav_menu_item, $request, false );
$schema = $this->get_item_schema();
if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
$meta_update = $this->meta->update_value( $request['meta'], $nav_menu_item->ID );
if ( is_wp_error( $meta_update ) ) {
return $meta_update;
}
}
$post = get_post( $nav_menu_item_id );
$nav_menu_item = $this->get_nav_menu_item( $nav_menu_item_id );
$fields_update = $this->update_additional_fields_for_object( $nav_menu_item, $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-menu-items-controller.php */
do_action( 'rest_after_insert_nav_menu_item', $nav_menu_item, $request, false );
wp_after_insert_post( $post, true, $post_before );
$response = $this->prepare_item_for_response( get_post( $nav_menu_item_id ), $request );
return rest_ensure_response( $response );
}
/**
* Deletes a single menu item.
*
* @since 5.9.0
*
* @param WP_REST_Request $request Full details about the request.
* @return WP_REST_Response|WP_Error True on success, or WP_Error object on failure.
*/
public function delete_item( $request ) {
$menu_item = $this->get_nav_menu_item( $request['id'] );
if ( is_wp_error( $menu_item ) ) {
return $menu_item;
}
// We don't support trashing for menu items.
if ( ! $request['force'] ) {
/* translators: %s: force=true */
return new WP_Error( 'rest_trash_not_supported', sprintf( __( "Menu items do not support trashing. Set '%s' to delete." ), 'force=true' ), array( 'status' => 501 ) );
}
$previous = $this->prepare_item_for_response( get_post( $request['id'] ), $request );
$result = wp_delete_post( $request['id'], true );
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(),
)
);
/**
* Fires immediately after a single menu item is deleted via the REST API.
*
* @since 5.9.0
*
* @param object $nav_menu_item Inserted or updated menu item object.
* @param WP_REST_Response $response The response data.
* @param WP_REST_Request $request Request object.
*/
do_action( 'rest_delete_nav_menu_item', $menu_item, $response, $request );
return $response;
}
/**
* Prepares a single post for create or update.
*
* @since 5.9.0
*
* @param WP_REST_Request $request Request object.
*
* @return object|WP_Error
*/
protected function prepare_item_for_database( $request ) {
$menu_item_db_id = $request['id'];
$menu_item_obj = $this->get_nav_menu_item( $menu_item_db_id );
// Need to persist the menu item data. See https://core.trac.wordpress.org/ticket/28138
if ( ! is_wp_error( $menu_item_obj ) ) {
// Correct the menu position if this was the first item. See https://core.trac.wordpress.org/ticket/28140
$position = ( 0 === $menu_item_obj->menu_order ) ? 1 : $menu_item_obj->menu_order;
$prepared_nav_item = array(
'menu-item-db-id' => $menu_item_db_id,
'menu-item-object-id' => $menu_item_obj->object_id,
'menu-item-object' => $menu_item_obj->object,
'menu-item-parent-id' => $menu_item_obj->menu_item_parent,
'menu-item-position' => $position,
'menu-item-type' => $menu_item_obj->type,
'menu-item-title' => $menu_item_obj->title,
'menu-item-url' => $menu_item_obj->url,
'menu-item-description' => $menu_item_obj->description,
'menu-item-attr-title' => $menu_item_obj->attr_title,
'menu-item-target' => $menu_item_obj->target,
'menu-item-classes' => $menu_item_obj->classes,
// Stored in the database as a string.
'menu-item-xfn' => explode( ' ', $menu_item_obj->xfn ),
'menu-item-status' => $menu_item_obj->post_status,
'menu-id' => $this->get_menu_id( $menu_item_db_id ),
);
} else {
$prepared_nav_item = array(
'menu-id' => 0,
'menu-item-db-id' => 0,
'menu-item-object-id' => 0,
'menu-item-object' => '',
'menu-item-parent-id' => 0,
'menu-item-position' => 1,
'menu-item-type' => 'custom',
'menu-item-title' => '',
'menu-item-url' => '',
'menu-item-description' => '',
'menu-item-attr-title' => '',
'menu-item-target' => '',
'menu-item-classes' => array(),
'menu-item-xfn' => array(),
'menu-item-status' => 'publish',
);
}
$mapping = array(
'menu-item-db-id' => 'id',
'menu-item-object-id' => 'object_id',
'menu-item-object' => 'object',
'menu-item-parent-id' => 'parent',
'menu-item-position' => 'menu_order',
'menu-item-type' => 'type',
'menu-item-url' => 'url',
'menu-item-description' => 'description',
'menu-item-attr-title' => 'attr_title',
'menu-item-target' => 'target',
'menu-item-classes' => 'classes',
'menu-item-xfn' => 'xfn',
'menu-item-status' => 'status',
);
$schema = $this->get_item_schema();
foreach ( $mapping as $original => $api_request ) {
if ( isset( $request[ $api_request ] ) ) {
$prepared_nav_item[ $original ] = $request[ $api_request ];
}
}
$taxonomy = get_taxonomy( 'nav_menu' );
$base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
// If menus submitted, cast to int.
if ( ! empty( $request[ $base ] ) ) {
$prepared_nav_item['menu-id'] = absint( $request[ $base ] );
}
// Nav menu title.
if ( ! empty( $schema['properties']['title'] ) && isset( $request['title'] ) ) {
if ( is_string( $request['title'] ) ) {
$prepared_nav_item['menu-item-title'] = $request['title'];
} elseif ( ! empty( $request['title']['raw'] ) ) {
$prepared_nav_item['menu-item-title'] = $request['title']['raw'];
}
}
$error = new WP_Error();
// Check if object id exists before saving.
if ( ! $prepared_nav_item['menu-item-object'] ) {
// If taxonomy, check if term exists.
if ( 'taxonomy' === $prepared_nav_item['menu-item-type'] ) {
$original = get_term( absint( $prepared_nav_item['menu-item-object-id'] ) );
if ( empty( $original ) || is_wp_error( $original ) ) {
$error->add( 'rest_term_invalid_id', __( 'Invalid term ID.' ), array( 'status' => 400 ) );
} else {
$prepared_nav_item['menu-item-object'] = get_term_field( 'taxonomy', $original );
}
// If post, check if post object exists.
} elseif ( 'post_type' === $prepared_nav_item['menu-item-type'] ) {
$original = get_post( absint( $prepared_nav_item['menu-item-object-id'] ) );
if ( empty( $original ) ) {
$error->add( 'rest_post_invalid_id', __( 'Invalid post ID.' ), array( 'status' => 400 ) );
} else {
$prepared_nav_item['menu-item-object'] = get_post_type( $original );
}
}
}
// If post type archive, check if post type exists.
if ( 'post_type_archive' === $prepared_nav_item['menu-item-type'] ) {
$post_type = $prepared_nav_item['menu-item-object'] ? $prepared_nav_item['menu-item-object'] : false;
$original = get_post_type_object( $post_type );
if ( ! $original ) {
$error->add( 'rest_post_invalid_type', __( 'Invalid post type.' ), array( 'status' => 400 ) );
}
}
// Check if menu item is type custom, then title and url are required.
if ( 'custom' === $prepared_nav_item['menu-item-type'] ) {
if ( '' === $prepared_nav_item['menu-item-title'] ) {
$error->add( 'rest_title_required', __( 'The title is required when using a custom menu item type.' ), array( 'status' => 400 ) );
}
if ( empty( $prepared_nav_item['menu-item-url'] ) ) {
$error->add( 'rest_url_required', __( 'The url is required when using a custom menu item type.' ), array( 'status' => 400 ) );
}
}
if ( $error->has_errors() ) {
return $error;
}
// The xfn and classes properties are arrays, but passed to wp_update_nav_menu_item as a string.
foreach ( array( 'menu-item-xfn', 'menu-item-classes' ) as $key ) {
$prepared_nav_item[ $key ] = implode( ' ', $prepared_nav_item[ $key ] );
}
// Only draft / publish are valid post status for menu items.
if ( 'publish' !== $prepared_nav_item['menu-item-status'] ) {
$prepared_nav_item['menu-item-status'] = 'draft';
}
$prepared_nav_item = (object) $prepared_nav_item;
/**
* Filters a menu item before it is inserted via the REST API.
*
* @since 5.9.0
*
* @param object $prepared_nav_item An object representing a single menu item prepared
* for inserting or updating the database.
* @param WP_REST_Request $request Request object.
*/
return apply_filters( 'rest_pre_insert_nav_menu_item', $prepared_nav_item, $request );
}
/**
* Prepares a single post output for response.
*
* @since 5.9.0
*
* @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 ) {
// Base fields for every post.
$fields = $this->get_fields_for_response( $request );
$menu_item = $this->get_nav_menu_item( $item->ID );
$data = array();
if ( rest_is_field_included( 'id', $fields ) ) {
$data['id'] = $menu_item->ID;
}
if ( rest_is_field_included( 'title', $fields ) ) {
$data['title'] = array();
}
if ( rest_is_field_included( 'title.raw', $fields ) ) {
$data['title']['raw'] = $menu_item->title;
}
if ( rest_is_field_included( 'title.rendered', $fields ) ) {
add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
/** This filter is documented in wp-includes/post-template.php */
$title = apply_filters( 'the_title', $menu_item->title, $menu_item->ID );
$data['title']['rendered'] = $title;
remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
}
if ( rest_is_field_included( 'status', $fields ) ) {
$data['status'] = $menu_item->post_status;
}
if ( rest_is_field_included( 'url', $fields ) ) {
$data['url'] = $menu_item->url;
}
if ( rest_is_field_included( 'attr_title', $fields ) ) {
// Same as post_excerpt.
$data['attr_title'] = $menu_item->attr_title;
}
if ( rest_is_field_included( 'description', $fields ) ) {
// Same as post_content.
$data['description'] = $menu_item->description;
}
if ( rest_is_field_included( 'type', $fields ) ) {
$data['type'] = $menu_item->type;
}
if ( rest_is_field_included( 'type_label', $fields ) ) {
$data['type_label'] = $menu_item->type_label;
}
if ( rest_is_field_included( 'object', $fields ) ) {
$data['object'] = $menu_item->object;
}
if ( rest_is_field_included( 'object_id', $fields ) ) {
// It is stored as a string, but should be exposed as an integer.
$data['object_id'] = absint( $menu_item->object_id );
}
if ( rest_is_field_included( 'parent', $fields ) ) {
// Same as post_parent, exposed as an integer.
$data['parent'] = (int) $menu_item->menu_item_parent;
}
if ( rest_is_field_included( 'menu_order', $fields ) ) {
// Same as post_parent, exposed as an integer.
$data['menu_order'] = (int) $menu_item->menu_order;
}
if ( rest_is_field_included( 'target', $fields ) ) {
$data['target'] = $menu_item->target;
}
if ( rest_is_field_included( 'classes', $fields ) ) {
$data['classes'] = (array) $menu_item->classes;
}
if ( rest_is_field_included( 'xfn', $fields ) ) {
$data['xfn'] = array_map( 'sanitize_html_class', explode( ' ', $menu_item->xfn ) );
}
if ( rest_is_field_included( 'invalid', $fields ) ) {
$data['invalid'] = (bool) $menu_item->_invalid;
}
if ( rest_is_field_included( 'meta', $fields ) ) {
$data['meta'] = $this->meta->get_value( $menu_item->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( $item, $taxonomy->name );
if ( ! is_array( $terms ) ) {
continue;
}
$term_ids = $terms ? array_values( wp_list_pluck( $terms, 'term_id' ) ) : array();
if ( 'nav_menu' === $taxonomy->name ) {
$data[ $base ] = $term_ids ? array_shift( $term_ids ) : 0;
} else {
$data[ $base ] = $term_ids;
}
}
}
$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( $item );
$response->add_links( $links );
if ( ! empty( $links['self']['href'] ) ) {
$actions = $this->get_available_actions( $item, $request );
$self = $links['self']['href'];
foreach ( $actions as $rel ) {
$response->add_link( $rel, $self );
}
}
}
/**
* Filters the menu item data for a REST API response.
*
* @since 5.9.0
*
* @param WP_REST_Response $response The response object.
* @param object $menu_item Menu item setup by {@see wp_setup_nav_menu_item()}.
* @param WP_REST_Request $request Request object.
*/
return apply_filters( 'rest_prepare_nav_menu_item', $response, $menu_item, $request );
}
/**
* Prepares links for the request.
*
* @since 5.9.0
*
* @param WP_Post $post Post object.
* @return array Links for the given post.
*/
protected function prepare_links( $post ) {
$links = parent::prepare_links( $post );
$menu_item = $this->get_nav_menu_item( $post->ID );
if ( empty( $menu_item->object_id ) ) {
return $links;
}
$path = '';
$type = '';
$key = $menu_item->type;
if ( 'post_type' === $menu_item->type ) {
$path = rest_get_route_for_post( $menu_item->object_id );
$type = get_post_type( $menu_item->object_id );
} elseif ( 'taxonomy' === $menu_item->type ) {
$path = rest_get_route_for_term( $menu_item->object_id );
$type = get_term_field( 'taxonomy', $menu_item->object_id );
}
if ( $path && $type ) {
$links['https://api.w.org/menu-item-object'][] = array(
'href' => rest_url( $path ),
$key => $type,
'embeddable' => true,
);
}
return $links;
}
/**
* Retrieves Link Description Objects that should be added to the Schema for the posts collection.
*
* @since 5.9.0
*
* @return array
*/
protected function get_schema_links() {
$links = parent::get_schema_links();
$href = rest_url( "{$this->namespace}/{$this->rest_base}/{id}" );
$links[] = array(
'rel' => 'https://api.w.org/menu-item-object',
'title' => __( 'Get linked object.' ),
'href' => $href,
'targetSchema' => array(
'type' => 'object',
'properties' => array(
'object' => array(
'type' => 'integer',
),
),
),
);
return $links;
}
/**
* Retrieves the term's schema, conforming to JSON Schema.
*
* @since 5.9.0
*
* @return array Item schema data.
*/
public function get_item_schema() {
$schema = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => $this->post_type,
'type' => 'object',
);
$schema['properties']['title'] = array(
'description' => __( 'The title for the object.' ),
'type' => array( 'string', 'object' ),
'context' => array( 'view', 'edit', 'embed' ),
'properties' => array(
'raw' => array(
'description' => __( 'Title for the object, as it exists in the database.' ),
'type' => 'string',
'context' => array( 'edit' ),
),
'rendered' => array(
'description' => __( 'HTML title for the object, transformed for display.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
'readonly' => true,
),
),
);
$schema['properties']['id'] = array(
'description' => __( 'Unique identifier for the object.' ),
'type' => 'integer',
'default' => 0,
'minimum' => 0,
'context' => array( 'view', 'edit', 'embed' ),
'readonly' => true,
);
$schema['properties']['type_label'] = array(
'description' => __( 'The singular label used to describe this type of menu item.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
'readonly' => true,
);
$schema['properties']['type'] = array(
'description' => __( 'The family of objects originally represented, such as "post_type" or "taxonomy".' ),
'type' => 'string',
'enum' => array( 'taxonomy', 'post_type', 'post_type_archive', 'custom' ),
'context' => array( 'view', 'edit', 'embed' ),
'default' => 'custom',
);
$schema['properties']['status'] = array(
'description' => __( 'A named status for the object.' ),
'type' => 'string',
'enum' => array_keys( get_post_stati( array( 'internal' => false ) ) ),
'default' => 'publish',
'context' => array( 'view', 'edit', 'embed' ),
);
$schema['properties']['parent'] = array(
'description' => __( 'The ID for the parent of the object.' ),
'type' => 'integer',
'minimum' => 0,
'default' => 0,
'context' => array( 'view', 'edit', 'embed' ),
);
$schema['properties']['attr_title'] = array(
'description' => __( 'Text for the title attribute of the link element for this menu item.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
'arg_options' => array(
'sanitize_callback' => 'sanitize_text_field',
),
);
$schema['properties']['classes'] = array(
'description' => __( 'Class names for the link element of this menu item.' ),
'type' => 'array',
'items' => array(
'type' => 'string',
),
'context' => array( 'view', 'edit', 'embed' ),
'arg_options' => array(
'sanitize_callback' => function ( $value ) {
return array_map( 'sanitize_html_class', wp_parse_list( $value ) );
},
),
);
$schema['properties']['description'] = array(
'description' => __( 'The description of this menu item.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
'arg_options' => array(
'sanitize_callback' => 'sanitize_text_field',
),
);
$schema['properties']['menu_order'] = array(
'description' => __( 'The DB ID of the nav_menu_item that is this item\'s menu parent, if any, otherwise 0.' ),
'context' => array( 'view', 'edit', 'embed' ),
'type' => 'integer',
'minimum' => 1,
'default' => 1,
);
$schema['properties']['object'] = array(
'description' => __( 'The type of object originally represented, such as "category", "post", or "attachment".' ),
'context' => array( 'view', 'edit', 'embed' ),
'type' => 'string',
'arg_options' => array(
'sanitize_callback' => 'sanitize_key',
),
);
$schema['properties']['object_id'] = array(
'description' => __( 'The database ID of the original object this menu item represents, for example the ID for posts or the term_id for categories.' ),
'context' => array( 'view', 'edit', 'embed' ),
'type' => 'integer',
'minimum' => 0,
'default' => 0,
);
$schema['properties']['target'] = array(
'description' => __( 'The target attribute of the link element for this menu item.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
'enum' => array(
'_blank',
'',
),
);
$schema['properties']['url'] = array(
'description' => __( 'The URL to which this menu item points.' ),
'type' => 'string',
'format' => 'uri',
'context' => array( 'view', 'edit', 'embed' ),
'arg_options' => array(
'validate_callback' => static function ( $url ) {
if ( '' === $url ) {
return true;
}
if ( sanitize_url( $url ) ) {
return true;
}
return new WP_Error(
'rest_invalid_url',
__( 'Invalid URL.' )
);
},
),
);
$schema['properties']['xfn'] = array(
'description' => __( 'The XFN relationship expressed in the link of this menu item.' ),
'type' => 'array',
'items' => array(
'type' => 'string',
),
'context' => array( 'view', 'edit', 'embed' ),
'arg_options' => array(
'sanitize_callback' => function ( $value ) {
return array_map( 'sanitize_html_class', wp_parse_list( $value ) );
},
),
);
$schema['properties']['invalid'] = array(
'description' => __( 'Whether the menu item represents an object that no longer exists.' ),
'context' => array( 'view', 'edit', 'embed' ),
'type' => 'boolean',
'readonly' => true,
);
$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;
$schema['properties'][ $base ] = array(
/* translators: %s: taxonomy name */
'description' => sprintf( __( 'The terms assigned to the object in the %s taxonomy.' ), $taxonomy->name ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'context' => array( 'view', 'edit' ),
);
if ( 'nav_menu' === $taxonomy->name ) {
$schema['properties'][ $base ]['type'] = 'integer';
unset( $schema['properties'][ $base ]['items'] );
}
}
$schema['properties']['meta'] = $this->meta->get_field_schema();
$schema_links = $this->get_schema_links();
if ( $schema_links ) {
$schema['links'] = $schema_links;
}
return $this->add_additional_fields_schema( $schema );
}
/**
* Retrieves the query params for the posts collection.
*
* @since 5.9.0
*
* @return array Collection parameters.
*/
public function get_collection_params() {
$query_params = parent::get_collection_params();
$query_params['menu_order'] = array(
'description' => __( 'Limit result set to posts with a specific menu_order value.' ),
'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 object attribute.' ),
'type' => 'string',
'default' => 'menu_order',
'enum' => array(
'author',
'date',
'id',
'include',
'modified',
'parent',
'relevance',
'slug',
'include_slugs',
'title',
'menu_order',
),
);
// Change default to 100 items.
$query_params['per_page']['default'] = 100;
return $query_params;
}
/**
* Determines the allowed query_vars for a get_items() response and prepares
* them for WP_Query.
*
* @since 5.9.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 = parent::prepare_items_query( $prepared_args, $request );
// Map to proper WP_Query orderby param.
if ( isset( $query_args['orderby'], $request['orderby'] ) ) {
$orderby_mappings = array(
'id' => 'ID',
'include' => 'post__in',
'slug' => 'post_name',
'include_slugs' => 'post_name__in',
'menu_order' => 'menu_order',
);
if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) {
$query_args['orderby'] = $orderby_mappings[ $request['orderby'] ];
}
}
$query_args['update_menu_item_cache'] = true;
return $query_args;
}
/**
* Gets the id of the menu that the given menu item belongs to.
*
* @since 5.9.0
*
* @param int $menu_item_id Menu item id.
* @return int
*/
protected function get_menu_id( $menu_item_id ) {
$menu_ids = wp_get_post_terms( $menu_item_id, 'nav_menu', array( 'fields' => 'ids' ) );
$menu_id = 0;
if ( $menu_ids && ! is_wp_error( $menu_ids ) ) {
$menu_id = array_shift( $menu_ids );
}
return $menu_id;
}
}
```
| 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 |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
| programming_docs |
wordpress class IXR_Error {} class IXR\_Error {}
===================
[IXR\_Error](ixr_error)
* [\_\_construct](ixr_error/__construct) — PHP5 constructor.
* [getXml](ixr_error/getxml)
* [IXR\_Error](ixr_error/ixr_error) — PHP4 constructor.
File: `wp-includes/IXR/class-IXR-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-error.php/)
```
class IXR_Error
{
var $code;
var $message;
/**
* PHP5 constructor.
*/
function __construct( $code, $message )
{
$this->code = $code;
$this->message = htmlspecialchars($message);
}
/**
* PHP4 constructor.
*/
public function IXR_Error( $code, $message ) {
self::__construct( $code, $message );
}
function getXml()
{
$xml = <<<EOD
<methodResponse>
<fault>
<value>
<struct>
<member>
<name>faultCode</name>
<value><int>{$this->code}</int></value>
</member>
<member>
<name>faultString</name>
<value><string>{$this->message}</string></value>
</member>
</struct>
</value>
</fault>
</methodResponse>
EOD;
return $xml;
}
}
```
| Version | Description |
| --- | --- |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
wordpress class WP_Customize_Nav_Menu_Control {} class WP\_Customize\_Nav\_Menu\_Control {}
==========================================
Customize Nav Menu Control Class.
* [WP\_Customize\_Control](wp_customize_control)
* [content\_template](wp_customize_nav_menu_control/content_template) — JS/Underscore template for the control UI.
* [json](wp_customize_nav_menu_control/json) — Return parameters for this control.
* [render\_content](wp_customize_nav_menu_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-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-control.php/)
```
class WP_Customize_Nav_Menu_Control extends WP_Customize_Control {
/**
* Control type.
*
* @since 4.3.0
* @var string
*/
public $type = 'nav_menu';
/**
* Don't render the control's content - it uses a JS template instead.
*
* @since 4.3.0
*/
public function render_content() {}
/**
* JS/Underscore template for the control UI.
*
* @since 4.3.0
*/
public function content_template() {
$add_items = __( 'Add Items' );
?>
<p class="new-menu-item-invitation">
<?php
printf(
/* translators: %s: "Add Items" button text. */
__( 'Time to add some links! Click “%s” to start putting pages, categories, and custom links in your menu. Add as many things as you would like.' ),
$add_items
);
?>
</p>
<div class="customize-control-nav_menu-buttons">
<button type="button" class="button add-new-menu-item" aria-label="<?php esc_attr_e( 'Add or remove menu items' ); ?>" aria-expanded="false" aria-controls="available-menu-items">
<?php echo $add_items; ?>
</button>
<button type="button" class="button-link reorder-toggle" aria-label="<?php esc_attr_e( 'Reorder menu items' ); ?>" aria-describedby="reorder-items-desc-{{ data.menu_id }}">
<span class="reorder"><?php _e( 'Reorder' ); ?></span>
<span class="reorder-done"><?php _e( 'Done' ); ?></span>
</button>
</div>
<p class="screen-reader-text" id="reorder-items-desc-{{ data.menu_id }}"><?php _e( 'When in reorder mode, additional controls to reorder menu items will be available in the items list above.' ); ?></p>
<?php
}
/**
* Return parameters for this control.
*
* @since 4.3.0
*
* @return array Exported parameters.
*/
public function json() {
$exported = parent::json();
$exported['menu_id'] = $this->setting->term_id;
return $exported;
}
}
```
| 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 Requests_Exception_HTTP_511 {} class Requests\_Exception\_HTTP\_511 {}
=======================================
Exception for 511 Network Authentication Required responses
* <https://tools.ietf.org/html/rfc6585>
File: `wp-includes/Requests/Exception/HTTP/511.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/511.php/)
```
class Requests_Exception_HTTP_511 extends Requests_Exception_HTTP {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 511;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Network Authentication Required';
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response |
wordpress class WP_Importer {} class WP\_Importer {}
=====================
[WP\_Importer](wp_importer) base class
* [\_\_construct](wp_importer/__construct) — Class Constructor
* [bump\_request\_timeout](wp_importer/bump_request_timeout) — Bump up the request timeout for http requests
* [cmpr\_strlen](wp_importer/cmpr_strlen) — Sort by strlen, longest string first
* [count\_imported\_posts](wp_importer/count_imported_posts) — Return count of imported permalinks from WordPress database
* [get\_imported\_comments](wp_importer/get_imported_comments) — Set array with imported comments from WordPress database
* [get\_imported\_posts](wp_importer/get_imported_posts) — Returns array with imported permalinks from WordPress database
* [get\_page](wp_importer/get_page) — GET URL
* [is\_user\_over\_quota](wp_importer/is_user_over_quota) — Check if user has exceeded disk quota
* [min\_whitespace](wp_importer/min_whitespace) — Replace newlines, tabs, and multiple spaces with a single space.
* [set\_blog](wp_importer/set_blog)
* [set\_user](wp_importer/set_user)
* [stop\_the\_insanity](wp_importer/stop_the_insanity) — Resets global variables that grow out of control during imports.
File: `wp-admin/includes/class-wp-importer.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-importer.php/)
```
class WP_Importer {
/**
* Class Constructor
*/
public function __construct() {}
/**
* Returns array with imported permalinks from WordPress database
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $importer_name
* @param string $blog_id
* @return array
*/
public function get_imported_posts( $importer_name, $blog_id ) {
global $wpdb;
$hashtable = array();
$limit = 100;
$offset = 0;
// Grab all posts in chunks.
do {
$meta_key = $importer_name . '_' . $blog_id . '_permalink';
$sql = $wpdb->prepare( "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = %s LIMIT %d,%d", $meta_key, $offset, $limit );
$results = $wpdb->get_results( $sql );
// Increment offset.
$offset = ( $limit + $offset );
if ( ! empty( $results ) ) {
foreach ( $results as $r ) {
// Set permalinks into array.
$hashtable[ $r->meta_value ] = (int) $r->post_id;
}
}
} while ( count( $results ) == $limit );
return $hashtable;
}
/**
* Return count of imported permalinks from WordPress database
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $importer_name
* @param string $blog_id
* @return int
*/
public function count_imported_posts( $importer_name, $blog_id ) {
global $wpdb;
$count = 0;
// Get count of permalinks.
$meta_key = $importer_name . '_' . $blog_id . '_permalink';
$sql = $wpdb->prepare( "SELECT COUNT( post_id ) AS cnt FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key );
$result = $wpdb->get_results( $sql );
if ( ! empty( $result ) ) {
$count = (int) $result[0]->cnt;
}
return $count;
}
/**
* Set array with imported comments from WordPress database
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $blog_id
* @return array
*/
public function get_imported_comments( $blog_id ) {
global $wpdb;
$hashtable = array();
$limit = 100;
$offset = 0;
// Grab all comments in chunks.
do {
$sql = $wpdb->prepare( "SELECT comment_ID, comment_agent FROM $wpdb->comments LIMIT %d,%d", $offset, $limit );
$results = $wpdb->get_results( $sql );
// Increment offset.
$offset = ( $limit + $offset );
if ( ! empty( $results ) ) {
foreach ( $results as $r ) {
// Explode comment_agent key.
list ( $comment_agent_blog_id, $source_comment_id ) = explode( '-', $r->comment_agent );
$source_comment_id = (int) $source_comment_id;
// Check if this comment came from this blog.
if ( $blog_id == $comment_agent_blog_id ) {
$hashtable[ $source_comment_id ] = (int) $r->comment_ID;
}
}
}
} while ( count( $results ) == $limit );
return $hashtable;
}
/**
* @param int $blog_id
* @return int|void
*/
public function set_blog( $blog_id ) {
if ( is_numeric( $blog_id ) ) {
$blog_id = (int) $blog_id;
} else {
$blog = 'http://' . preg_replace( '#^https?://#', '', $blog_id );
$parsed = parse_url( $blog );
if ( ! $parsed || empty( $parsed['host'] ) ) {
fwrite( STDERR, "Error: can not determine blog_id from $blog_id\n" );
exit;
}
if ( empty( $parsed['path'] ) ) {
$parsed['path'] = '/';
}
$blogs = get_sites(
array(
'domain' => $parsed['host'],
'number' => 1,
'path' => $parsed['path'],
)
);
if ( ! $blogs ) {
fwrite( STDERR, "Error: Could not find blog\n" );
exit;
}
$blog = array_shift( $blogs );
$blog_id = (int) $blog->blog_id;
}
if ( function_exists( 'is_multisite' ) ) {
if ( is_multisite() ) {
switch_to_blog( $blog_id );
}
}
return $blog_id;
}
/**
* @param int $user_id
* @return int|void
*/
public function set_user( $user_id ) {
if ( is_numeric( $user_id ) ) {
$user_id = (int) $user_id;
} else {
$user_id = (int) username_exists( $user_id );
}
if ( ! $user_id || ! wp_set_current_user( $user_id ) ) {
fwrite( STDERR, "Error: can not find user\n" );
exit;
}
return $user_id;
}
/**
* Sort by strlen, longest string first
*
* @param string $a
* @param string $b
* @return int
*/
public function cmpr_strlen( $a, $b ) {
return strlen( $b ) - strlen( $a );
}
/**
* GET URL
*
* @param string $url
* @param string $username
* @param string $password
* @param bool $head
* @return array
*/
public function get_page( $url, $username = '', $password = '', $head = false ) {
// Increase the timeout.
add_filter( 'http_request_timeout', array( $this, 'bump_request_timeout' ) );
$headers = array();
$args = array();
if ( true === $head ) {
$args['method'] = 'HEAD';
}
if ( ! empty( $username ) && ! empty( $password ) ) {
$headers['Authorization'] = 'Basic ' . base64_encode( "$username:$password" );
}
$args['headers'] = $headers;
return wp_safe_remote_request( $url, $args );
}
/**
* Bump up the request timeout for http requests
*
* @param int $val
* @return int
*/
public function bump_request_timeout( $val ) {
return 60;
}
/**
* Check if user has exceeded disk quota
*
* @return bool
*/
public function is_user_over_quota() {
if ( function_exists( 'upload_is_user_over_quota' ) ) {
if ( upload_is_user_over_quota() ) {
return true;
}
}
return false;
}
/**
* Replace newlines, tabs, and multiple spaces with a single space.
*
* @param string $text
* @return string
*/
public function min_whitespace( $text ) {
return preg_replace( '|[\r\n\t ]+|', ' ', $text );
}
/**
* Resets global variables that grow out of control during imports.
*
* @since 3.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global int[] $wp_actions
*/
public function stop_the_insanity() {
global $wpdb, $wp_actions;
// Or define( 'WP_IMPORTING', true );
$wpdb->queries = array();
// Reset $wp_actions to keep it from growing out of control.
$wp_actions = array();
}
}
```
wordpress class Requests_Exception_HTTP_403 {} class Requests\_Exception\_HTTP\_403 {}
=======================================
Exception for 403 Forbidden responses
File: `wp-includes/Requests/Exception/HTTP/403.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/http/403.php/)
```
class Requests_Exception_HTTP_403 extends Requests_Exception_HTTP {
/**
* HTTP status code
*
* @var integer
*/
protected $code = 403;
/**
* Reason phrase
*
* @var string
*/
protected $reason = 'Forbidden';
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception\_HTTP](requests_exception_http) wp-includes/Requests/Exception/HTTP.php | Exception based on HTTP response |
wordpress class WP_Recovery_Mode_Key_Service {} class WP\_Recovery\_Mode\_Key\_Service {}
=========================================
Core class used to generate and validate keys used to enter Recovery Mode.
* [clean\_expired\_keys](wp_recovery_mode_key_service/clean_expired_keys) — Removes expired recovery mode keys.
* [generate\_and\_store\_recovery\_mode\_key](wp_recovery_mode_key_service/generate_and_store_recovery_mode_key) — Creates a recovery mode key.
* [generate\_recovery\_mode\_token](wp_recovery_mode_key_service/generate_recovery_mode_token) — Creates a recovery mode token.
* [get\_keys](wp_recovery_mode_key_service/get_keys) — Gets the recovery key records.
* [remove\_key](wp_recovery_mode_key_service/remove_key) — Removes a used recovery key.
* [update\_keys](wp_recovery_mode_key_service/update_keys) — Updates the recovery key records.
* [validate\_recovery\_mode\_key](wp_recovery_mode_key_service/validate_recovery_mode_key) — Verifies if the recovery mode key is correct.
File: `wp-includes/class-wp-recovery-mode-key-service.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-recovery-mode-key-service.php/)
```
final class WP_Recovery_Mode_Key_Service {
/**
* The option name used to store the keys.
*
* @since 5.2.0
* @var string
*/
private $option_name = 'recovery_keys';
/**
* Creates a recovery mode token.
*
* @since 5.2.0
*
* @return string A random string to identify its associated key in storage.
*/
public function generate_recovery_mode_token() {
return wp_generate_password( 22, false );
}
/**
* Creates a recovery mode key.
*
* @since 5.2.0
*
* @global PasswordHash $wp_hasher
*
* @param string $token A token generated by {@see generate_recovery_mode_token()}.
* @return string Recovery mode key.
*/
public function generate_and_store_recovery_mode_key( $token ) {
global $wp_hasher;
$key = wp_generate_password( 22, false );
if ( empty( $wp_hasher ) ) {
require_once ABSPATH . WPINC . '/class-phpass.php';
$wp_hasher = new PasswordHash( 8, true );
}
$hashed = $wp_hasher->HashPassword( $key );
$records = $this->get_keys();
$records[ $token ] = array(
'hashed_key' => $hashed,
'created_at' => time(),
);
$this->update_keys( $records );
/**
* Fires when a recovery mode key is generated.
*
* @since 5.2.0
*
* @param string $token The recovery data token.
* @param string $key The recovery mode key.
*/
do_action( 'generate_recovery_mode_key', $token, $key );
return $key;
}
/**
* Verifies if the recovery mode key is correct.
*
* Recovery mode keys can only be used once; the key will be consumed in the process.
*
* @since 5.2.0
*
* @param string $token The token used when generating the given key.
* @param string $key The unhashed key.
* @param int $ttl Time in seconds for the key to be valid for.
* @return true|WP_Error True on success, error object on failure.
*/
public function validate_recovery_mode_key( $token, $key, $ttl ) {
$records = $this->get_keys();
if ( ! isset( $records[ $token ] ) ) {
return new WP_Error( 'token_not_found', __( 'Recovery Mode not initialized.' ) );
}
$record = $records[ $token ];
$this->remove_key( $token );
if ( ! is_array( $record ) || ! isset( $record['hashed_key'], $record['created_at'] ) ) {
return new WP_Error( 'invalid_recovery_key_format', __( 'Invalid recovery key format.' ) );
}
if ( ! wp_check_password( $key, $record['hashed_key'] ) ) {
return new WP_Error( 'hash_mismatch', __( 'Invalid recovery key.' ) );
}
if ( time() > $record['created_at'] + $ttl ) {
return new WP_Error( 'key_expired', __( 'Recovery key expired.' ) );
}
return true;
}
/**
* Removes expired recovery mode keys.
*
* @since 5.2.0
*
* @param int $ttl Time in seconds for the keys to be valid for.
*/
public function clean_expired_keys( $ttl ) {
$records = $this->get_keys();
foreach ( $records as $key => $record ) {
if ( ! isset( $record['created_at'] ) || time() > $record['created_at'] + $ttl ) {
unset( $records[ $key ] );
}
}
$this->update_keys( $records );
}
/**
* Removes a used recovery key.
*
* @since 5.2.0
*
* @param string $token The token used when generating a recovery mode key.
*/
private function remove_key( $token ) {
$records = $this->get_keys();
if ( ! isset( $records[ $token ] ) ) {
return;
}
unset( $records[ $token ] );
$this->update_keys( $records );
}
/**
* Gets the recovery key records.
*
* @since 5.2.0
*
* @return array Associative array of $token => $data pairs, where $data has keys 'hashed_key'
* and 'created_at'.
*/
private function get_keys() {
return (array) get_option( $this->option_name, array() );
}
/**
* Updates the recovery key records.
*
* @since 5.2.0
*
* @param array $keys Associative array of $token => $data pairs, where $data has keys 'hashed_key'
* and 'created_at'.
* @return bool True on success, false on failure.
*/
private function update_keys( array $keys ) {
return update_option( $this->option_name, $keys );
}
}
```
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress class WP_Comment {} class WP\_Comment {}
====================
Core class used to organize comments as instantiated objects with defined members.
* [\_\_construct](wp_comment/__construct) — Constructor.
* [\_\_get](wp_comment/__get) — Magic getter.
* [\_\_isset](wp_comment/__isset) — Check whether a non-public property is set.
* [add\_child](wp_comment/add_child) — Add a child to the comment.
* [get\_child](wp_comment/get_child) — Get a child comment by ID.
* [get\_children](wp_comment/get_children) — Get the children of a comment.
* [get\_instance](wp_comment/get_instance) — Retrieves a WP\_Comment instance.
* [populated\_children](wp_comment/populated_children) — Set the 'populated\_children' flag.
* [to\_array](wp_comment/to_array) — Convert object to array.
File: `wp-includes/class-wp-comment.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment.php/)
```
final class WP_Comment {
/**
* Comment ID.
*
* A numeric string, for compatibility reasons.
*
* @since 4.4.0
* @var string
*/
public $comment_ID;
/**
* ID of the post the comment is associated with.
*
* A numeric string, for compatibility reasons.
*
* @since 4.4.0
* @var string
*/
public $comment_post_ID = 0;
/**
* Comment author name.
*
* @since 4.4.0
* @var string
*/
public $comment_author = '';
/**
* Comment author email address.
*
* @since 4.4.0
* @var string
*/
public $comment_author_email = '';
/**
* Comment author URL.
*
* @since 4.4.0
* @var string
*/
public $comment_author_url = '';
/**
* Comment author IP address (IPv4 format).
*
* @since 4.4.0
* @var string
*/
public $comment_author_IP = '';
/**
* Comment date in YYYY-MM-DD HH:MM:SS format.
*
* @since 4.4.0
* @var string
*/
public $comment_date = '0000-00-00 00:00:00';
/**
* Comment GMT date in YYYY-MM-DD HH::MM:SS format.
*
* @since 4.4.0
* @var string
*/
public $comment_date_gmt = '0000-00-00 00:00:00';
/**
* Comment content.
*
* @since 4.4.0
* @var string
*/
public $comment_content;
/**
* Comment karma count.
*
* A numeric string, for compatibility reasons.
*
* @since 4.4.0
* @var string
*/
public $comment_karma = 0;
/**
* Comment approval status.
*
* @since 4.4.0
* @var string
*/
public $comment_approved = '1';
/**
* Comment author HTTP user agent.
*
* @since 4.4.0
* @var string
*/
public $comment_agent = '';
/**
* Comment type.
*
* @since 4.4.0
* @since 5.5.0 Default value changed to `comment`.
* @var string
*/
public $comment_type = 'comment';
/**
* Parent comment ID.
*
* A numeric string, for compatibility reasons.
*
* @since 4.4.0
* @var string
*/
public $comment_parent = 0;
/**
* Comment author ID.
*
* A numeric string, for compatibility reasons.
*
* @since 4.4.0
* @var string
*/
public $user_id = 0;
/**
* Comment children.
*
* @since 4.4.0
* @var array
*/
protected $children;
/**
* Whether children have been populated for this comment object.
*
* @since 4.4.0
* @var bool
*/
protected $populated_children = false;
/**
* Post fields.
*
* @since 4.4.0
* @var array
*/
protected $post_fields = array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_excerpt', 'post_status', 'comment_status', 'ping_status', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_content_filtered', 'post_parent', 'guid', 'menu_order', 'post_type', 'post_mime_type', 'comment_count' );
/**
* Retrieves a WP_Comment instance.
*
* @since 4.4.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $id Comment ID.
* @return WP_Comment|false Comment object, otherwise false.
*/
public static function get_instance( $id ) {
global $wpdb;
$comment_id = (int) $id;
if ( ! $comment_id ) {
return false;
}
$_comment = wp_cache_get( $comment_id, 'comment' );
if ( ! $_comment ) {
$_comment = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment_id ) );
if ( ! $_comment ) {
return false;
}
wp_cache_add( $_comment->comment_ID, $_comment, 'comment' );
}
return new WP_Comment( $_comment );
}
/**
* Constructor.
*
* Populates properties with object vars.
*
* @since 4.4.0
*
* @param WP_Comment $comment Comment object.
*/
public function __construct( $comment ) {
foreach ( get_object_vars( $comment ) as $key => $value ) {
$this->$key = $value;
}
}
/**
* Convert object to array.
*
* @since 4.4.0
*
* @return array Object as array.
*/
public function to_array() {
return get_object_vars( $this );
}
/**
* Get the children of a comment.
*
* @since 4.4.0
*
* @param array $args {
* Array of arguments used to pass to get_comments() and determine format.
*
* @type string $format Return value format. 'tree' for a hierarchical tree, 'flat' for a flattened array.
* Default 'tree'.
* @type string $status Comment status to limit results by. Accepts 'hold' (`comment_status=0`),
* 'approve' (`comment_status=1`), 'all', or a custom comment status.
* Default 'all'.
* @type 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.
* Pass `false` to leave out descendants.
* The parameter is ignored (forced to `false`) when `$fields` is 'ids' or 'counts'.
* Accepts 'threaded', 'flat', or false. Default: 'threaded'.
* @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, and the array keys of
* `$meta_query`. Also accepts false, an empty array, or
* 'none' to disable `ORDER BY` clause.
* }
* @return WP_Comment[] Array of `WP_Comment` objects.
*/
public function get_children( $args = array() ) {
$defaults = array(
'format' => 'tree',
'status' => 'all',
'hierarchical' => 'threaded',
'orderby' => '',
);
$_args = wp_parse_args( $args, $defaults );
$_args['parent'] = $this->comment_ID;
if ( is_null( $this->children ) ) {
if ( $this->populated_children ) {
$this->children = array();
} else {
$this->children = get_comments( $_args );
}
}
if ( 'flat' === $_args['format'] ) {
$children = array();
foreach ( $this->children as $child ) {
$child_args = $_args;
$child_args['format'] = 'flat';
// get_children() resets this value automatically.
unset( $child_args['parent'] );
$children = array_merge( $children, array( $child ), $child->get_children( $child_args ) );
}
} else {
$children = $this->children;
}
return $children;
}
/**
* Add a child to the comment.
*
* Used by `WP_Comment_Query` when bulk-filling descendants.
*
* @since 4.4.0
*
* @param WP_Comment $child Child comment.
*/
public function add_child( WP_Comment $child ) {
$this->children[ $child->comment_ID ] = $child;
}
/**
* Get a child comment by ID.
*
* @since 4.4.0
*
* @param int $child_id ID of the child.
* @return WP_Comment|false Returns the comment object if found, otherwise false.
*/
public function get_child( $child_id ) {
if ( isset( $this->children[ $child_id ] ) ) {
return $this->children[ $child_id ];
}
return false;
}
/**
* Set the 'populated_children' flag.
*
* This flag is important for ensuring that calling `get_children()` on a childless comment will not trigger
* unneeded database queries.
*
* @since 4.4.0
*
* @param bool $set Whether the comment's children have already been populated.
*/
public function populated_children( $set ) {
$this->populated_children = (bool) $set;
}
/**
* Check whether a non-public property is set.
*
* If `$name` matches a post field, the comment post will be loaded and the post's value checked.
*
* @since 4.4.0
*
* @param string $name Property name.
* @return bool
*/
public function __isset( $name ) {
if ( in_array( $name, $this->post_fields, true ) && 0 !== (int) $this->comment_post_ID ) {
$post = get_post( $this->comment_post_ID );
return property_exists( $post, $name );
}
}
/**
* Magic getter.
*
* If `$name` matches a post field, the comment post will be loaded and the post's value returned.
*
* @since 4.4.0
*
* @param string $name
* @return mixed
*/
public function __get( $name ) {
if ( in_array( $name, $this->post_fields, true ) ) {
$post = get_post( $this->comment_post_ID );
return $post->$name;
}
}
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress class Requests_Auth_Basic {} class Requests\_Auth\_Basic {}
==============================
Basic Authentication provider
Provides a handler for Basic HTTP authentication via the Authorization header.
* [\_\_construct](requests_auth_basic/__construct) — Constructor
* [curl\_before\_send](requests_auth_basic/curl_before_send) — Set cURL parameters before the data is sent
* [fsockopen\_header](requests_auth_basic/fsockopen_header) — Add extra headers to the request before sending
* [getAuthString](requests_auth_basic/getauthstring) — Get the authentication string (user:pass)
* [register](requests_auth_basic/register) — Register the necessary callbacks
File: `wp-includes/Requests/Auth/Basic.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/auth/basic.php/)
```
class Requests_Auth_Basic implements Requests_Auth {
/**
* Username
*
* @var string
*/
public $user;
/**
* Password
*
* @var string
*/
public $pass;
/**
* Constructor
*
* @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_array($args)) {
if (count($args) !== 2) {
throw new Requests_Exception('Invalid number of arguments', 'authbasicbadargs');
}
list($this->user, $this->pass) = $args;
}
}
/**
* Register the necessary callbacks
*
* @see curl_before_send
* @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.after_headers', array($this, 'fsockopen_header'));
}
/**
* Set cURL parameters before the data is sent
*
* @param resource $handle cURL resource
*/
public function curl_before_send(&$handle) {
curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($handle, CURLOPT_USERPWD, $this->getAuthString());
}
/**
* Add extra headers to the request before sending
*
* @param string $out HTTP header string
*/
public function fsockopen_header(&$out) {
$out .= sprintf("Authorization: Basic %s\r\n", base64_encode($this->getAuthString()));
}
/**
* Get the authentication string (user:pass)
*
* @return string
*/
public function getAuthString() {
return $this->user . ':' . $this->pass;
}
}
```
wordpress class WP_Image_Editor {} class WP\_Image\_Editor {}
==========================
Base image editor class from which implementations extend
[WP\_Image\_Editor](wp_image_editor) is an abstract class, so it can’t be called directly. It is used for implementations like [WP\_Image\_Editor\_GD](wp_image_editor_gd) and [WP\_Image\_Editor\_Imagick](wp_image_editor_imagick). It has some base functionality that can be used by those implementations.
You shouldn’t call an implementation directly. Instead, use [wp\_get\_image\_editor()](../functions/wp_get_image_editor) , which looks at which implementation is the best.
* [\_\_construct](wp_image_editor/__construct) — Each instance handles a single file.
* [crop](wp_image_editor/crop) — Crops Image.
* [flip](wp_image_editor/flip) — Flips current image.
* [generate\_filename](wp_image_editor/generate_filename) — Builds an output filename based on current file, and adding proper suffix
* [get\_default\_quality](wp_image_editor/get_default_quality) — Returns the default compression quality setting for the mime type.
* [get\_extension](wp_image_editor/get_extension) — Returns first matched extension from Mime-type, as mapped from wp\_get\_mime\_types()
* [get\_mime\_type](wp_image_editor/get_mime_type) — Returns first matched mime-type from extension, as mapped from wp\_get\_mime\_types()
* [get\_output\_format](wp_image_editor/get_output_format) — Returns preferred mime-type and extension based on provided file's extension and mime, or current file's extension and mime.
* [get\_quality](wp_image_editor/get_quality) — Gets the Image Compression quality on a 1-100% scale.
* [get\_size](wp_image_editor/get_size) — Gets dimensions of image.
* [get\_suffix](wp_image_editor/get_suffix) — Builds and returns proper suffix for file based on height and width.
* [load](wp_image_editor/load) — Loads image from $this->file into editor.
* [make\_image](wp_image_editor/make_image) — Either calls editor's save function or handles file as a stream.
* [maybe\_exif\_rotate](wp_image_editor/maybe_exif_rotate) — Check if a JPEG image has EXIF Orientation tag and rotate it if needed.
* [multi\_resize](wp_image_editor/multi_resize) — Resize multiple images from a single source.
* [resize](wp_image_editor/resize) — Resizes current image.
* [rotate](wp_image_editor/rotate) — Rotates current image counter-clockwise by $angle.
* [save](wp_image_editor/save) — Saves current image to file.
* [set\_quality](wp_image_editor/set_quality) — Sets Image Compression quality on a 1-100% scale.
* [stream](wp_image_editor/stream) — Streams current image to browser.
* [supports\_mime\_type](wp_image_editor/supports_mime_type) — Checks to see if editor supports the mime-type specified.
* [test](wp_image_editor/test) — Checks to see if current environment supports the editor chosen.
* [update\_size](wp_image_editor/update_size) — Sets current image size.
File: `wp-includes/class-wp-image-editor.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-image-editor.php/)
```
abstract class WP_Image_Editor {
protected $file = null;
protected $size = null;
protected $mime_type = null;
protected $output_mime_type = null;
protected $default_mime_type = 'image/jpeg';
protected $quality = false;
// Deprecated since 5.8.1. See get_default_quality() below.
protected $default_quality = 82;
/**
* Each instance handles a single file.
*
* @param string $file Path to the file to load.
*/
public function __construct( $file ) {
$this->file = $file;
}
/**
* Checks to see if current environment supports the editor chosen.
* Must be overridden in a subclass.
*
* @since 3.5.0
*
* @abstract
*
* @param array $args
* @return bool
*/
public static function test( $args = array() ) {
return false;
}
/**
* Checks to see if editor supports the mime-type specified.
* Must be overridden in a subclass.
*
* @since 3.5.0
*
* @abstract
*
* @param string $mime_type
* @return bool
*/
public static function supports_mime_type( $mime_type ) {
return false;
}
/**
* Loads image from $this->file into editor.
*
* @since 3.5.0
* @abstract
*
* @return true|WP_Error True if loaded; WP_Error on failure.
*/
abstract public function load();
/**
* Saves current image to file.
*
* @since 3.5.0
* @since 6.0.0 The `$filesize` value was added to the returned array.
* @abstract
*
* @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.
* }
*/
abstract public function save( $destfilename = null, $mime_type = null );
/**
* 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
* @abstract
*
* @param int|null $max_w Image width.
* @param int|null $max_h Image height.
* @param bool $crop
* @return true|WP_Error
*/
abstract public function resize( $max_w, $max_h, $crop = false );
/**
* Resize multiple images from a single source.
*
* @since 3.5.0
* @abstract
*
* @param array $sizes {
* An array of image size arrays. Default sizes are 'small', 'medium', 'large'.
*
* @type array ...$0 {
* @type int $width Image width.
* @type int $height Image height.
* @type bool $crop Optional. Whether to crop the image. Default false.
* }
* }
* @return array An array of resized images metadata by size.
*/
abstract public function multi_resize( $sizes );
/**
* Crops Image.
*
* @since 3.5.0
* @abstract
*
* @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
*/
abstract public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false );
/**
* Rotates current image counter-clockwise by $angle.
*
* @since 3.5.0
* @abstract
*
* @param float $angle
* @return true|WP_Error
*/
abstract public function rotate( $angle );
/**
* Flips current image.
*
* @since 3.5.0
* @abstract
*
* @param bool $horz Flip along Horizontal Axis
* @param bool $vert Flip along Vertical Axis
* @return true|WP_Error
*/
abstract public function flip( $horz, $vert );
/**
* Streams current image to browser.
*
* @since 3.5.0
* @abstract
*
* @param string $mime_type The mime type of the image.
* @return true|WP_Error True on success, WP_Error object on failure.
*/
abstract public function stream( $mime_type = null );
/**
* Gets dimensions of image.
*
* @since 3.5.0
*
* @return int[] {
* Dimensions of the image.
*
* @type int $width The image width.
* @type int $height The image height.
* }
*/
public function get_size() {
return $this->size;
}
/**
* Sets current image size.
*
* @since 3.5.0
*
* @param int $width
* @param int $height
* @return true
*/
protected function update_size( $width = null, $height = null ) {
$this->size = array(
'width' => (int) $width,
'height' => (int) $height,
);
return true;
}
/**
* Gets the Image Compression quality on a 1-100% scale.
*
* @since 4.0.0
*
* @return int Compression Quality. Range: [1,100]
*/
public function get_quality() {
if ( ! $this->quality ) {
$this->set_quality();
}
return $this->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 ) {
// Use the output mime type if present. If not, fall back to the input/initial mime type.
$mime_type = ! empty( $this->output_mime_type ) ? $this->output_mime_type : $this->mime_type;
// Get the default quality setting for the mime type.
$default_quality = $this->get_default_quality( $mime_type );
if ( null === $quality ) {
/**
* Filters the default image compression quality setting.
*
* Applies only during initial editor instantiation, or when set_quality() is run
* manually without the `$quality` argument.
*
* The WP_Image_Editor::set_quality() method has priority over the filter.
*
* @since 3.5.0
*
* @param int $quality Quality level between 1 (low) and 100 (high).
* @param string $mime_type Image mime type.
*/
$quality = apply_filters( 'wp_editor_set_quality', $default_quality, $mime_type );
if ( 'image/jpeg' === $mime_type ) {
/**
* Filters the JPEG compression quality for backward-compatibility.
*
* Applies only during initial editor instantiation, or when set_quality() is run
* manually without the `$quality` argument.
*
* The WP_Image_Editor::set_quality() method has priority over the filter.
*
* The filter is evaluated under two contexts: 'image_resize', and 'edit_image',
* (when a JPEG image is saved to file).
*
* @since 2.5.0
*
* @param int $quality Quality level between 0 (low) and 100 (high) of the JPEG.
* @param string $context Context of the filter.
*/
$quality = apply_filters( 'jpeg_quality', $quality, 'image_resize' );
}
if ( $quality < 0 || $quality > 100 ) {
$quality = $default_quality;
}
}
// Allow 0, but squash to 1 due to identical images in GD, and for backward compatibility.
if ( 0 === $quality ) {
$quality = 1;
}
if ( ( $quality >= 1 ) && ( $quality <= 100 ) ) {
$this->quality = $quality;
return true;
} else {
return new WP_Error( 'invalid_image_quality', __( 'Attempted to set image quality outside of the range [1,100].' ) );
}
}
/**
* Returns the default compression quality setting for the mime type.
*
* @since 5.8.1
*
* @param string $mime_type
* @return int The default quality setting for the mime type.
*/
protected function get_default_quality( $mime_type ) {
switch ( $mime_type ) {
case 'image/webp':
$quality = 86;
break;
case 'image/jpeg':
default:
$quality = $this->default_quality;
}
return $quality;
}
/**
* Returns preferred mime-type and extension based on provided
* file's extension and mime, or current file's extension and mime.
*
* Will default to $this->default_mime_type if requested is not supported.
*
* Provides corrected filename only if filename is provided.
*
* @since 3.5.0
*
* @param string $filename
* @param string $mime_type
* @return array { filename|null, extension, mime-type }
*/
protected function get_output_format( $filename = null, $mime_type = null ) {
$new_ext = null;
// By default, assume specified type takes priority.
if ( $mime_type ) {
$new_ext = $this->get_extension( $mime_type );
}
if ( $filename ) {
$file_ext = strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) );
$file_mime = $this->get_mime_type( $file_ext );
} else {
// If no file specified, grab editor's current extension and mime-type.
$file_ext = strtolower( pathinfo( $this->file, PATHINFO_EXTENSION ) );
$file_mime = $this->mime_type;
}
// Check to see if specified mime-type is the same as type implied by
// file extension. If so, prefer extension from file.
if ( ! $mime_type || ( $file_mime == $mime_type ) ) {
$mime_type = $file_mime;
$new_ext = $file_ext;
}
/**
* Filters the image editor output format mapping.
*
* Enables filtering the mime type used to save images. By default,
* the mapping array is empty, so the mime type matches the source image.
*
* @see WP_Image_Editor::get_output_format()
*
* @since 5.8.0
*
* @param string[] $output_format {
* An array of mime type mappings. Maps a source mime type to a new
* destination mime type. Default empty array.
*
* @type string ...$0 The new mime type.
* }
* @param string $filename Path to the image.
* @param string $mime_type The source image mime type.
*/
$output_format = apply_filters( 'image_editor_output_format', array(), $filename, $mime_type );
if ( isset( $output_format[ $mime_type ] )
&& $this->supports_mime_type( $output_format[ $mime_type ] )
) {
$mime_type = $output_format[ $mime_type ];
$new_ext = $this->get_extension( $mime_type );
}
// Double-check that the mime-type selected is supported by the editor.
// If not, choose a default instead.
if ( ! $this->supports_mime_type( $mime_type ) ) {
/**
* Filters default mime type prior to getting the file extension.
*
* @see wp_get_mime_types()
*
* @since 3.5.0
*
* @param string $mime_type Mime type string.
*/
$mime_type = apply_filters( 'image_editor_default_mime_type', $this->default_mime_type );
$new_ext = $this->get_extension( $mime_type );
}
// Ensure both $filename and $new_ext are not empty.
// $this->get_extension() returns false on error which would effectively remove the extension
// from $filename. That shouldn't happen, files without extensions are not supported.
if ( $filename && $new_ext ) {
$dir = pathinfo( $filename, PATHINFO_DIRNAME );
$ext = pathinfo( $filename, PATHINFO_EXTENSION );
$filename = trailingslashit( $dir ) . wp_basename( $filename, ".$ext" ) . ".{$new_ext}";
}
if ( $mime_type && ( $mime_type !== $this->mime_type ) ) {
// The image will be converted when saving. Set the quality for the new mime-type if not already set.
if ( $mime_type !== $this->output_mime_type ) {
$this->output_mime_type = $mime_type;
}
$this->set_quality();
} elseif ( ! empty( $this->output_mime_type ) ) {
// Reset output_mime_type and quality.
$this->output_mime_type = null;
$this->set_quality();
}
return array( $filename, $new_ext, $mime_type );
}
/**
* Builds an output filename based on current file, and adding proper suffix
*
* @since 3.5.0
*
* @param string $suffix
* @param string $dest_path
* @param string $extension
* @return string filename
*/
public function generate_filename( $suffix = null, $dest_path = null, $extension = null ) {
// $suffix will be appended to the destination filename, just before the extension.
if ( ! $suffix ) {
$suffix = $this->get_suffix();
}
$dir = pathinfo( $this->file, PATHINFO_DIRNAME );
$ext = pathinfo( $this->file, PATHINFO_EXTENSION );
$name = wp_basename( $this->file, ".$ext" );
$new_ext = strtolower( $extension ? $extension : $ext );
if ( ! is_null( $dest_path ) ) {
if ( ! wp_is_stream( $dest_path ) ) {
$_dest_path = realpath( $dest_path );
if ( $_dest_path ) {
$dir = $_dest_path;
}
} else {
$dir = $dest_path;
}
}
return trailingslashit( $dir ) . "{$name}-{$suffix}.{$new_ext}";
}
/**
* Builds and returns proper suffix for file based on height and width.
*
* @since 3.5.0
*
* @return string|false suffix
*/
public function get_suffix() {
if ( ! $this->get_size() ) {
return false;
}
return "{$this->size['width']}x{$this->size['height']}";
}
/**
* Check if a JPEG image has EXIF Orientation tag and rotate it if needed.
*
* @since 5.3.0
*
* @return bool|WP_Error True if the image was rotated. False if not rotated (no EXIF data or the image doesn't need to be rotated).
* WP_Error if error while rotating.
*/
public function maybe_exif_rotate() {
$orientation = null;
if ( is_callable( 'exif_read_data' ) && 'image/jpeg' === $this->mime_type ) {
$exif_data = @exif_read_data( $this->file );
if ( ! empty( $exif_data['Orientation'] ) ) {
$orientation = (int) $exif_data['Orientation'];
}
}
/**
* Filters the `$orientation` value to correct it before rotating or to prevent rotating the image.
*
* @since 5.3.0
*
* @param int $orientation EXIF Orientation value as retrieved from the image file.
* @param string $file Path to the image file.
*/
$orientation = apply_filters( 'wp_image_maybe_exif_rotate', $orientation, $this->file );
if ( ! $orientation || 1 === $orientation ) {
return false;
}
switch ( $orientation ) {
case 2:
// Flip horizontally.
$result = $this->flip( false, true );
break;
case 3:
// Rotate 180 degrees or flip horizontally and vertically.
// Flipping seems faster and uses less resources.
$result = $this->flip( true, true );
break;
case 4:
// Flip vertically.
$result = $this->flip( true, false );
break;
case 5:
// Rotate 90 degrees counter-clockwise and flip vertically.
$result = $this->rotate( 90 );
if ( ! is_wp_error( $result ) ) {
$result = $this->flip( true, false );
}
break;
case 6:
// Rotate 90 degrees clockwise (270 counter-clockwise).
$result = $this->rotate( 270 );
break;
case 7:
// Rotate 90 degrees counter-clockwise and flip horizontally.
$result = $this->rotate( 90 );
if ( ! is_wp_error( $result ) ) {
$result = $this->flip( false, true );
}
break;
case 8:
// Rotate 90 degrees counter-clockwise.
$result = $this->rotate( 90 );
break;
}
return $result;
}
/**
* 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 ) {
$stream = wp_is_stream( $filename );
if ( $stream ) {
ob_start();
} else {
// The directory containing the original file may no longer exist when using a replication plugin.
wp_mkdir_p( dirname( $filename ) );
}
$result = call_user_func_array( $callback, $arguments );
if ( $result && $stream ) {
$contents = ob_get_contents();
$fp = fopen( $filename, 'w' );
if ( ! $fp ) {
ob_end_clean();
return false;
}
fwrite( $fp, $contents );
fclose( $fp );
}
if ( $stream ) {
ob_end_clean();
}
return $result;
}
/**
* Returns first matched mime-type from extension,
* as mapped from wp_get_mime_types()
*
* @since 3.5.0
*
* @param string $extension
* @return string|false
*/
protected static function get_mime_type( $extension = null ) {
if ( ! $extension ) {
return false;
}
$mime_types = wp_get_mime_types();
$extensions = array_keys( $mime_types );
foreach ( $extensions as $_extension ) {
if ( preg_match( "/{$extension}/i", $_extension ) ) {
return $mime_types[ $_extension ];
}
}
return false;
}
/**
* Returns first matched extension from Mime-type,
* as mapped from wp_get_mime_types()
*
* @since 3.5.0
*
* @param string $mime_type
* @return string|false
*/
protected static function get_extension( $mime_type = null ) {
if ( empty( $mime_type ) ) {
return false;
}
return wp_get_default_extension_for_mime_type( $mime_type );
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Image\_Editor\_Imagick](wp_image_editor_imagick) wp-includes/class-wp-image-editor-imagick.php | WordPress Image Editor Class for Image Manipulation through Imagick PHP Module |
| [WP\_Image\_Editor\_GD](wp_image_editor_gd) wp-includes/class-wp-image-editor-gd.php | WordPress Image Editor Class for Image Manipulation through GD |
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
| programming_docs |
wordpress class WP_REST_Menus_Controller {} class WP\_REST\_Menus\_Controller {}
====================================
Core class used to managed menu terms associated via the REST API.
* [WP\_REST\_Controller](wp_rest_controller)
* [check\_has\_read\_only\_access](wp_rest_menus_controller/check_has_read_only_access) — Checks whether the current user has read permission for the endpoint.
* [create\_item](wp_rest_menus_controller/create_item) — Creates a single term in a taxonomy.
* [delete\_item](wp_rest_menus_controller/delete_item) — Deletes a single term from a taxonomy.
* [get\_item\_permissions\_check](wp_rest_menus_controller/get_item_permissions_check) — Checks if a request has access to read or edit the specified menu.
* [get\_item\_schema](wp_rest_menus_controller/get_item_schema) — Retrieves the term's schema, conforming to JSON Schema.
* [get\_items\_permissions\_check](wp_rest_menus_controller/get_items_permissions_check) — Checks if a request has access to read menus.
* [get\_menu\_auto\_add](wp_rest_menus_controller/get_menu_auto_add) — Returns the value of a menu's auto\_add setting.
* [get\_menu\_locations](wp_rest_menus_controller/get_menu_locations) — Returns the names of the locations assigned to the menu.
* [get\_term](wp_rest_menus_controller/get_term) — Gets the term, if the ID is valid.
* [handle\_auto\_add](wp_rest_menus_controller/handle_auto_add) — Updates the menu's auto add from a REST request.
* [handle\_locations](wp_rest_menus_controller/handle_locations) — Updates the menu's locations from a REST request.
* [prepare\_item\_for\_database](wp_rest_menus_controller/prepare_item_for_database) — Prepares a single term for create or update.
* [prepare\_item\_for\_response](wp_rest_menus_controller/prepare_item_for_response) — Prepares a single term output for response.
* [prepare\_links](wp_rest_menus_controller/prepare_links) — Prepares links for the request.
* [update\_item](wp_rest_menus_controller/update_item) — Updates a single term from a taxonomy.
File: `wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php/)
```
class WP_REST_Menus_Controller extends WP_REST_Terms_Controller {
/**
* Checks if a request has access to read menus.
*
* @since 5.9.0
*
* @param WP_REST_Request $request Full details about the request.
* @return bool|WP_Error True if the request has read access, otherwise false or WP_Error object.
*/
public function get_items_permissions_check( $request ) {
$has_permission = parent::get_items_permissions_check( $request );
if ( true !== $has_permission ) {
return $has_permission;
}
return $this->check_has_read_only_access( $request );
}
/**
* Checks if a request has access to read or edit the specified menu.
*
* @since 5.9.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 false or WP_Error object.
*/
public function get_item_permissions_check( $request ) {
$has_permission = parent::get_item_permissions_check( $request );
if ( true !== $has_permission ) {
return $has_permission;
}
return $this->check_has_read_only_access( $request );
}
/**
* Gets the term, if the ID is valid.
*
* @since 5.9.0
*
* @param int $id Supplied ID.
* @return WP_Term|WP_Error Term object if ID is valid, WP_Error otherwise.
*/
protected function get_term( $id ) {
$term = parent::get_term( $id );
if ( is_wp_error( $term ) ) {
return $term;
}
$nav_term = wp_get_nav_menu_object( $term );
$nav_term->auto_add = $this->get_menu_auto_add( $nav_term->term_id );
return $nav_term;
}
/**
* Checks whether the current user has read permission for the endpoint.
*
* This allows for any user that can `edit_theme_options` or edit any REST API available post type.
*
* @since 5.9.0
*
* @param WP_REST_Request $request Full details about the request.
* @return bool|WP_Error Whether the current user has permission.
*/
protected function check_has_read_only_access( $request ) {
if ( current_user_can( 'edit_theme_options' ) ) {
return true;
}
if ( current_user_can( 'edit_posts' ) ) {
return true;
}
foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
if ( current_user_can( $post_type->cap->edit_posts ) ) {
return true;
}
}
return new WP_Error(
'rest_cannot_view',
__( 'Sorry, you are not allowed to view menus.' ),
array( 'status' => rest_authorization_required_code() )
);
}
/**
* Prepares a single term output for response.
*
* @since 5.9.0
*
* @param WP_Term $term Term object.
* @param WP_REST_Request $request Request object.
* @return WP_REST_Response Response object.
*/
public function prepare_item_for_response( $term, $request ) {
$nav_menu = wp_get_nav_menu_object( $term );
$response = parent::prepare_item_for_response( $nav_menu, $request );
$fields = $this->get_fields_for_response( $request );
$data = $response->get_data();
if ( rest_is_field_included( 'locations', $fields ) ) {
$data['locations'] = $this->get_menu_locations( $nav_menu->term_id );
}
if ( rest_is_field_included( 'auto_add', $fields ) ) {
$data['auto_add'] = $this->get_menu_auto_add( $nav_menu->term_id );
}
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
$response = rest_ensure_response( $data );
if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
$response->add_links( $this->prepare_links( $term ) );
}
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
return apply_filters( "rest_prepare_{$this->taxonomy}", $response, $term, $request );
}
/**
* Prepares links for the request.
*
* @since 5.9.0
*
* @param WP_Term $term Term object.
* @return array Links for the given term.
*/
protected function prepare_links( $term ) {
$links = parent::prepare_links( $term );
$locations = $this->get_menu_locations( $term->term_id );
foreach ( $locations as $location ) {
$url = rest_url( sprintf( 'wp/v2/menu-locations/%s', $location ) );
$links['https://api.w.org/menu-location'][] = array(
'href' => $url,
'embeddable' => true,
);
}
return $links;
}
/**
* Prepares a single term for create or update.
*
* @since 5.9.0
*
* @param WP_REST_Request $request Request object.
* @return object Prepared term data.
*/
public function prepare_item_for_database( $request ) {
$prepared_term = parent::prepare_item_for_database( $request );
$schema = $this->get_item_schema();
if ( isset( $request['name'] ) && ! empty( $schema['properties']['name'] ) ) {
$prepared_term->{'menu-name'} = $request['name'];
}
return $prepared_term;
}
/**
* Creates a single term in a taxonomy.
*
* @since 5.9.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 = wp_get_nav_menu_object( (int) $request['parent'] );
if ( ! $parent ) {
return new WP_Error( 'rest_term_invalid', __( 'Parent term does not exist.' ), array( 'status' => 400 ) );
}
}
$prepared_term = $this->prepare_item_for_database( $request );
$term = wp_update_nav_menu_object( 0, wp_slash( (array) $prepared_term ) );
if ( is_wp_error( $term ) ) {
/*
* If we're going to inform the client that the term already exists,
* give them the identifier for future use.
*/
if ( in_array( 'menu_exists', $term->get_error_codes(), true ) ) {
$existing_term = get_term_by( 'name', $prepared_term->{'menu-name'}, $this->taxonomy );
$term->add_data( $existing_term->term_id, 'menu_exists' );
$term->add_data(
array(
'status' => 400,
'term_id' => $existing_term->term_id,
)
);
} else {
$term->add_data( array( 'status' => 400 ) );
}
return $term;
}
$term = $this->get_term( $term );
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
do_action( "rest_insert_{$this->taxonomy}", $term, $request, true );
$schema = $this->get_item_schema();
if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
$meta_update = $this->meta->update_value( $request['meta'], $term->term_id );
if ( is_wp_error( $meta_update ) ) {
return $meta_update;
}
}
$locations_update = $this->handle_locations( $term->term_id, $request );
if ( is_wp_error( $locations_update ) ) {
return $locations_update;
}
$this->handle_auto_add( $term->term_id, $request );
$fields_update = $this->update_additional_fields_for_object( $term, $request );
if ( is_wp_error( $fields_update ) ) {
return $fields_update;
}
$request->set_param( 'context', 'view' );
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
do_action( "rest_after_insert_{$this->taxonomy}", $term, $request, true );
$response = $this->prepare_item_for_response( $term, $request );
$response = rest_ensure_response( $response );
$response->set_status( 201 );
$response->header( 'Location', rest_url( $this->namespace . '/' . $this->rest_base . '/' . $term->term_id ) );
return $response;
}
/**
* Updates a single term from a taxonomy.
*
* @since 5.9.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 ) ) {
if ( ! isset( $prepared_term->{'menu-name'} ) ) {
// wp_update_nav_menu_object() requires that the menu-name is always passed.
$prepared_term->{'menu-name'} = $term->name;
}
$update = wp_update_nav_menu_object( $term->term_id, wp_slash( (array) $prepared_term ) );
if ( is_wp_error( $update ) ) {
return $update;
}
}
$term = get_term( $term->term_id, $this->taxonomy );
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
do_action( "rest_insert_{$this->taxonomy}", $term, $request, false );
$schema = $this->get_item_schema();
if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
$meta_update = $this->meta->update_value( $request['meta'], $term->term_id );
if ( is_wp_error( $meta_update ) ) {
return $meta_update;
}
}
$locations_update = $this->handle_locations( $term->term_id, $request );
if ( is_wp_error( $locations_update ) ) {
return $locations_update;
}
$this->handle_auto_add( $term->term_id, $request );
$fields_update = $this->update_additional_fields_for_object( $term, $request );
if ( is_wp_error( $fields_update ) ) {
return $fields_update;
}
$request->set_param( 'context', 'view' );
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
do_action( "rest_after_insert_{$this->taxonomy}", $term, $request, false );
$response = $this->prepare_item_for_response( $term, $request );
return rest_ensure_response( $response );
}
/**
* Deletes a single term from a taxonomy.
*
* @since 5.9.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;
}
// We don't support trashing for terms.
if ( ! $request['force'] ) {
/* translators: %s: force=true */
return new WP_Error( 'rest_trash_not_supported', sprintf( __( "Menus do not support trashing. Set '%s' to delete." ), 'force=true' ), array( 'status' => 501 ) );
}
$request->set_param( 'context', 'view' );
$previous = $this->prepare_item_for_response( $term, $request );
$result = wp_delete_nav_menu( $term );
if ( ! $result || is_wp_error( $result ) ) {
return new WP_Error( 'rest_cannot_delete', __( 'The menu cannot be deleted.' ), array( 'status' => 500 ) );
}
$response = new WP_REST_Response();
$response->set_data(
array(
'deleted' => true,
'previous' => $previous->get_data(),
)
);
/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */
do_action( "rest_delete_{$this->taxonomy}", $term, $response, $request );
return $response;
}
/**
* Returns the value of a menu's auto_add setting.
*
* @since 5.9.0
*
* @param int $menu_id The menu id to query.
* @return bool The value of auto_add.
*/
protected function get_menu_auto_add( $menu_id ) {
$nav_menu_option = (array) get_option( 'nav_menu_options', array( 'auto_add' => array() ) );
return in_array( $menu_id, $nav_menu_option['auto_add'], true );
}
/**
* Updates the menu's auto add from a REST request.
*
* @since 5.9.0
*
* @param int $menu_id The menu id to update.
* @param WP_REST_Request $request Full details about the request.
* @return bool True if the auto add setting was successfully updated.
*/
protected function handle_auto_add( $menu_id, $request ) {
if ( ! isset( $request['auto_add'] ) ) {
return true;
}
$nav_menu_option = (array) get_option( 'nav_menu_options', array( 'auto_add' => array() ) );
if ( ! isset( $nav_menu_option['auto_add'] ) ) {
$nav_menu_option['auto_add'] = array();
}
$auto_add = $request['auto_add'];
$i = array_search( $menu_id, $nav_menu_option['auto_add'], true );
if ( $auto_add && false === $i ) {
$nav_menu_option['auto_add'][] = $menu_id;
} elseif ( ! $auto_add && false !== $i ) {
array_splice( $nav_menu_option['auto_add'], $i, 1 );
}
$update = update_option( 'nav_menu_options', $nav_menu_option );
/** This action is documented in wp-includes/nav-menu.php */
do_action( 'wp_update_nav_menu', $menu_id );
return $update;
}
/**
* Returns the names of the locations assigned to the menu.
*
* @since 5.9.0
*
* @param int $menu_id The menu id.
* @return string[] The locations assigned to the menu.
*/
protected function get_menu_locations( $menu_id ) {
$locations = get_nav_menu_locations();
$menu_locations = array();
foreach ( $locations as $location => $assigned_menu_id ) {
if ( $menu_id === $assigned_menu_id ) {
$menu_locations[] = $location;
}
}
return $menu_locations;
}
/**
* Updates the menu's locations from a REST request.
*
* @since 5.9.0
*
* @param int $menu_id The menu id to update.
* @param WP_REST_Request $request Full details about the request.
* @return true|WP_Error True on success, a WP_Error on an error updating any of the locations.
*/
protected function handle_locations( $menu_id, $request ) {
if ( ! isset( $request['locations'] ) ) {
return true;
}
$menu_locations = get_registered_nav_menus();
$menu_locations = array_keys( $menu_locations );
$new_locations = array();
foreach ( $request['locations'] as $location ) {
if ( ! in_array( $location, $menu_locations, true ) ) {
return new WP_Error(
'rest_invalid_menu_location',
__( 'Invalid menu location.' ),
array(
'status' => 400,
'location' => $location,
)
);
}
$new_locations[ $location ] = $menu_id;
}
$assigned_menu = get_nav_menu_locations();
foreach ( $assigned_menu as $location => $term_id ) {
if ( $term_id === $menu_id ) {
unset( $assigned_menu[ $location ] );
}
}
$new_assignments = array_merge( $assigned_menu, $new_locations );
set_theme_mod( 'nav_menu_locations', $new_assignments );
return true;
}
/**
* Retrieves the term's schema, conforming to JSON Schema.
*
* @since 5.9.0
*
* @return array Item schema data.
*/
public function get_item_schema() {
$schema = parent::get_item_schema();
unset( $schema['properties']['count'], $schema['properties']['link'], $schema['properties']['taxonomy'] );
$schema['properties']['locations'] = array(
'description' => __( 'The locations assigned to the menu.' ),
'type' => 'array',
'items' => array(
'type' => 'string',
),
'context' => array( 'view', 'edit' ),
'arg_options' => array(
'validate_callback' => function ( $locations, $request, $param ) {
$valid = rest_validate_request_arg( $locations, $request, $param );
if ( true !== $valid ) {
return $valid;
}
$locations = rest_sanitize_request_arg( $locations, $request, $param );
foreach ( $locations as $location ) {
if ( ! array_key_exists( $location, get_registered_nav_menus() ) ) {
return new WP_Error(
'rest_invalid_menu_location',
__( 'Invalid menu location.' ),
array(
'location' => $location,
)
);
}
}
return true;
},
),
);
$schema['properties']['auto_add'] = array(
'description' => __( 'Whether to automatically add top level pages to this menu.' ),
'context' => array( 'view', 'edit' ),
'type' => 'boolean',
);
return $schema;
}
}
```
| Uses | Description |
| --- | --- |
| [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. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress class WP_Customize_Site_Icon_Control {} class WP\_Customize\_Site\_Icon\_Control {}
===========================================
Customize Site Icon control class.
Used only for custom functionality in JavaScript.
* [WP\_Customize\_Cropped\_Image\_Control](wp_customize_cropped_image_control)
* [\_\_construct](wp_customize_site_icon_control/__construct) — Constructor.
* [content\_template](wp_customize_site_icon_control/content_template) — Renders a JS template for the content of the site icon control.
File: `wp-includes/customize/class-wp-customize-site-icon-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-site-icon-control.php/)
```
class WP_Customize_Site_Icon_Control extends WP_Customize_Cropped_Image_Control {
/**
* Control type.
*
* @since 4.3.0
* @var string
*/
public $type = 'site_icon';
/**
* Constructor.
*
* @since 4.3.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() ) {
parent::__construct( $manager, $id, $args );
add_action( 'customize_controls_print_styles', 'wp_site_icon', 99 );
}
/**
* Renders a JS template for the content of the site icon control.
*
* @since 4.5.0
*/
public function content_template() {
?>
<# if ( data.label ) { #>
<span class="customize-control-title">{{ data.label }}</span>
<# } #>
<# if ( data.description ) { #>
<span class="description customize-control-description">{{{ data.description }}}</span>
<# } #>
<# if ( data.attachment && data.attachment.id ) { #>
<div class="attachment-media-view">
<# if ( data.attachment.sizes ) { #>
<div class="site-icon-preview wp-clearfix">
<div class="favicon-preview">
<img src="<?php echo esc_url( admin_url( 'images/' . ( is_rtl() ? 'browser-rtl.png' : 'browser.png' ) ) ); ?>" class="browser-preview" width="182" alt="" />
<div class="favicon">
<img src="{{ data.attachment.sizes.full ? data.attachment.sizes.full.url : data.attachment.url }}" alt="<?php esc_attr_e( 'Preview as a browser icon' ); ?>" />
</div>
<span class="browser-title" aria-hidden="true"><# print( '<?php echo esc_js( get_bloginfo( 'name' ) ); ?>' ) #></span>
</div>
<img class="app-icon-preview" src="{{ data.attachment.sizes.full ? data.attachment.sizes.full.url : data.attachment.url }}" alt="<?php esc_attr_e( 'Preview as an app icon' ); ?>" />
</div>
<# } #>
<div class="actions">
<# if ( data.canUpload ) { #>
<button type="button" class="button remove-button"><?php echo $this->button_labels['remove']; ?></button>
<button type="button" class="button upload-button"><?php echo $this->button_labels['change']; ?></button>
<# } #>
</div>
</div>
<# } else { #>
<div class="attachment-media-view">
<# if ( data.canUpload ) { #>
<button type="button" class="upload-button button-add-media"><?php echo $this->button_labels['site_icon']; ?></button>
<# } #>
<div class="actions">
<# if ( data.defaultAttachment ) { #>
<button type="button" class="button default-button"><?php echo $this->button_labels['default']; ?></button>
<# } #>
</div>
</div>
<# } #>
<?php
}
}
```
| Uses | 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. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
| programming_docs |
wordpress class WP_REST_Pattern_Directory_Controller {} class WP\_REST\_Pattern\_Directory\_Controller {}
=================================================
Controller which provides REST endpoint for block patterns.
This simply proxies the endpoint at <https://api.wordpress.org/patterns/1.0/>. That isn’t necessary for functionality, but is desired for privacy. It prevents api.wordpress.org from knowing the user’s IP address.
* [WP\_REST\_Controller](wp_rest_controller)
* [\_\_construct](wp_rest_pattern_directory_controller/__construct) — Constructs the controller.
* [get\_collection\_params](wp_rest_pattern_directory_controller/get_collection_params) — Retrieves the search parameters for the block pattern's collection.
* [get\_item\_schema](wp_rest_pattern_directory_controller/get_item_schema) — Retrieves the block pattern's schema, conforming to JSON Schema.
* [get\_items](wp_rest_pattern_directory_controller/get_items) — Search and retrieve block patterns metadata
* [get\_items\_permissions\_check](wp_rest_pattern_directory_controller/get_items_permissions_check) — Checks whether a given request has permission to view the local block pattern directory.
* [get\_transient\_key](wp_rest_pattern_directory_controller/get_transient_key)
* [prepare\_item\_for\_response](wp_rest_pattern_directory_controller/prepare_item_for_response) — Prepare a raw block pattern before it gets output in a REST API response.
* [register\_routes](wp_rest_pattern_directory_controller/register_routes) — Registers the necessary REST API routes.
File: `wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php/)
```
class WP_REST_Pattern_Directory_Controller extends WP_REST_Controller {
/**
* Constructs the controller.
*
* @since 5.8.0
*/
public function __construct() {
$this->namespace = 'wp/v2';
$this->rest_base = 'pattern-directory';
}
/**
* Registers the necessary REST API routes.
*
* @since 5.8.0
*/
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/patterns',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => $this->get_collection_params(),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);
}
/**
* Checks whether a given request has permission to view the local block pattern directory.
*
* @since 5.8.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( 'edit_posts' ) ) {
return true;
}
foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
if ( current_user_can( $post_type->cap->edit_posts ) ) {
return true;
}
}
return new WP_Error(
'rest_pattern_directory_cannot_view',
__( 'Sorry, you are not allowed to browse the local block pattern directory.' ),
array( 'status' => rest_authorization_required_code() )
);
}
/**
* Search and retrieve block patterns metadata
*
* @since 5.8.0
* @since 6.0.0 Added 'slug' to request.
*
* @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 ) {
/*
* Include an unmodified `$wp_version`, so the API can craft a response that's tailored to
* it. Some plugins modify the version in a misguided attempt to improve security by
* obscuring the version, which can cause invalid requests.
*/
require ABSPATH . WPINC . '/version.php';
$query_args = array(
'locale' => get_user_locale(),
'wp-version' => $wp_version,
);
$category_id = $request['category'];
$keyword_id = $request['keyword'];
$search_term = $request['search'];
$slug = $request['slug'];
if ( $category_id ) {
$query_args['pattern-categories'] = $category_id;
}
if ( $keyword_id ) {
$query_args['pattern-keywords'] = $keyword_id;
}
if ( $search_term ) {
$query_args['search'] = $search_term;
}
if ( $slug ) {
$query_args['slug'] = $slug;
}
$transient_key = $this->get_transient_key( $query_args );
/*
* Use network-wide transient to improve performance. The locale is the only site
* configuration that affects the response, and it's included in the transient key.
*/
$raw_patterns = get_site_transient( $transient_key );
if ( ! $raw_patterns ) {
$api_url = 'http://api.wordpress.org/patterns/1.0/?' . build_query( $query_args );
if ( wp_http_supports( array( 'ssl' ) ) ) {
$api_url = set_url_scheme( $api_url, 'https' );
}
/*
* Default to a short TTL, to mitigate cache stampedes on high-traffic sites.
* This assumes that most errors will be short-lived, e.g., packet loss that causes the
* first request to fail, but a follow-up one will succeed. The value should be high
* enough to avoid stampedes, but low enough to not interfere with users manually
* re-trying a failed request.
*/
$cache_ttl = 5;
$wporg_response = wp_remote_get( $api_url );
$raw_patterns = json_decode( wp_remote_retrieve_body( $wporg_response ) );
if ( is_wp_error( $wporg_response ) ) {
$raw_patterns = $wporg_response;
} elseif ( ! is_array( $raw_patterns ) ) {
// HTTP request succeeded, but response data is invalid.
$raw_patterns = new WP_Error(
'pattern_api_failed',
sprintf(
/* translators: %s: Support forums URL. */
__( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the <a href="%s">support forums</a>.' ),
__( 'https://wordpress.org/support/forums/' )
),
array(
'response' => wp_remote_retrieve_body( $wporg_response ),
)
);
} else {
// Response has valid data.
$cache_ttl = HOUR_IN_SECONDS;
}
set_site_transient( $transient_key, $raw_patterns, $cache_ttl );
}
if ( is_wp_error( $raw_patterns ) ) {
$raw_patterns->add_data( array( 'status' => 500 ) );
return $raw_patterns;
}
$response = array();
if ( $raw_patterns ) {
foreach ( $raw_patterns as $pattern ) {
$response[] = $this->prepare_response_for_collection(
$this->prepare_item_for_response( $pattern, $request )
);
}
}
return new WP_REST_Response( $response );
}
/**
* Prepare a raw block pattern before it gets output in a REST API response.
*
* @since 5.8.0
* @since 5.9.0 Renamed `$raw_pattern` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param object $item Raw pattern from api.wordpress.org, before any changes.
* @param WP_REST_Request $request Request object.
* @return WP_REST_Response
*/
public function prepare_item_for_response( $item, $request ) {
// Restores the more descriptive, specific name for use within this method.
$raw_pattern = $item;
$prepared_pattern = array(
'id' => absint( $raw_pattern->id ),
'title' => sanitize_text_field( $raw_pattern->title->rendered ),
'content' => wp_kses_post( $raw_pattern->pattern_content ),
'categories' => array_map( 'sanitize_title', $raw_pattern->category_slugs ),
'keywords' => array_map( 'sanitize_text_field', explode( ',', $raw_pattern->meta->wpop_keywords ) ),
'description' => sanitize_text_field( $raw_pattern->meta->wpop_description ),
'viewport_width' => absint( $raw_pattern->meta->wpop_viewport_width ),
);
$prepared_pattern = $this->add_additional_fields_to_object( $prepared_pattern, $request );
$response = new WP_REST_Response( $prepared_pattern );
/**
* Filters the REST API response for a block pattern.
*
* @since 5.8.0
*
* @param WP_REST_Response $response The response object.
* @param object $raw_pattern The unprepared block pattern.
* @param WP_REST_Request $request The request object.
*/
return apply_filters( 'rest_prepare_block_pattern', $response, $raw_pattern, $request );
}
/**
* Retrieves the block pattern'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' => 'pattern-directory-item',
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'The pattern ID.' ),
'type' => 'integer',
'minimum' => 1,
'context' => array( 'view', 'edit', 'embed' ),
),
'title' => array(
'description' => __( 'The pattern title, in human readable format.' ),
'type' => 'string',
'minLength' => 1,
'context' => array( 'view', 'edit', 'embed' ),
),
'content' => array(
'description' => __( 'The pattern content.' ),
'type' => 'string',
'minLength' => 1,
'context' => array( 'view', 'edit', 'embed' ),
),
'categories' => array(
'description' => __( "The pattern's category slugs." ),
'type' => 'array',
'uniqueItems' => true,
'items' => array( 'type' => 'string' ),
'context' => array( 'view', 'edit', 'embed' ),
),
'keywords' => array(
'description' => __( "The pattern's keywords." ),
'type' => 'array',
'uniqueItems' => true,
'items' => array( 'type' => 'string' ),
'context' => array( 'view', 'edit', 'embed' ),
),
'description' => array(
'description' => __( 'A description of the pattern.' ),
'type' => 'string',
'minLength' => 1,
'context' => array( 'view', 'edit', 'embed' ),
),
'viewport_width' => array(
'description' => __( 'The preferred width of the viewport when previewing a pattern, in pixels.' ),
'type' => 'integer',
'context' => array( 'view', 'edit', 'embed' ),
),
),
);
return $this->add_additional_fields_schema( $this->schema );
}
/**
* Retrieves the search parameters for the block pattern's collection.
*
* @since 5.8.0
*
* @return array Collection parameters.
*/
public function get_collection_params() {
$query_params = parent::get_collection_params();
// Pagination is not supported.
unset( $query_params['page'] );
unset( $query_params['per_page'] );
$query_params['search']['minLength'] = 1;
$query_params['context']['default'] = 'view';
$query_params['category'] = array(
'description' => __( 'Limit results to those matching a category ID.' ),
'type' => 'integer',
'minimum' => 1,
);
$query_params['keyword'] = array(
'description' => __( 'Limit results to those matching a keyword ID.' ),
'type' => 'integer',
'minimum' => 1,
);
$query_params['slug'] = array(
'description' => __( 'Limit results to those matching a pattern (slug).' ),
'type' => 'array',
);
/**
* Filter collection parameters for the block pattern directory controller.
*
* @since 5.8.0
*
* @param array $query_params JSON Schema-formatted collection parameters.
*/
return apply_filters( 'rest_pattern_directory_collection_params', $query_params );
}
/*
* Include a hash of the query args, so that different requests are stored in
* separate caches.
*
* MD5 is chosen for its speed, low-collision rate, universal availability, and to stay
* under the character limit for `_site_transient_timeout_{...}` keys.
*
* @link https://stackoverflow.com/questions/3665247/fastest-hash-for-non-cryptographic-uses
*
* @since 6.0.0
*
* @param array $query_args Query arguments to generate a transient key from.
* @return string Transient key.
*/
protected function get_transient_key( $query_args ) {
if ( isset( $query_args['slug'] ) ) {
// This is an additional precaution because the "sort" function expects an array.
$query_args['slug'] = wp_parse_list( $query_args['slug'] );
// Empty arrays should not affect the transient key.
if ( empty( $query_args['slug'] ) ) {
unset( $query_args['slug'] );
} else {
// Sort the array so that the transient key doesn't depend on the order of slugs.
sort( $query_args['slug'] );
}
}
return 'wp_remote_block_patterns_' . md5( serialize( $query_args ) );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_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. |
wordpress class WP_Customize_Sidebar_Section {} class WP\_Customize\_Sidebar\_Section {}
========================================
Customizer section representing widget area (sidebar).
* [WP\_Customize\_Section](wp_customize_section)
* [active\_callback](wp_customize_sidebar_section/active_callback) — Whether the current sidebar is rendered on the page.
* [json](wp_customize_sidebar_section/json) — Gather the parameters passed to client JavaScript via JSON.
File: `wp-includes/customize/class-wp-customize-sidebar-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-sidebar-section.php/)
```
class WP_Customize_Sidebar_Section extends WP_Customize_Section {
/**
* Type of this section.
*
* @since 4.1.0
* @var string
*/
public $type = 'sidebar';
/**
* Unique identifier.
*
* @since 4.1.0
* @var string
*/
public $sidebar_id;
/**
* Gather the parameters passed to client JavaScript via JSON.
*
* @since 4.1.0
*
* @return array The array to be exported to the client as JSON.
*/
public function json() {
$json = parent::json();
$json['sidebarId'] = $this->sidebar_id;
return $json;
}
/**
* Whether the current sidebar is rendered on the page.
*
* @since 4.1.0
*
* @return bool Whether sidebar is rendered.
*/
public function active_callback() {
return $this->manager->widgets->is_sidebar_rendered( $this->sidebar_id );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Section](wp_customize_section) wp-includes/class-wp-customize-section.php | Customize Section class. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress class WP_Plugin_Install_List_Table {} class WP\_Plugin\_Install\_List\_Table {}
=========================================
Core class used to implement displaying plugins to install in a list table.
* [WP\_List\_Table](wp_list_table)
* [ajax\_user\_can](wp_plugin_install_list_table/ajax_user_can)
* [display](wp_plugin_install_list_table/display) — Displays the plugin install table.
* [display\_rows](wp_plugin_install_list_table/display_rows)
* [display\_tablenav](wp_plugin_install_list_table/display_tablenav)
* [get\_columns](wp_plugin_install_list_table/get_columns)
* [get\_installed\_plugin\_slugs](wp_plugin_install_list_table/get_installed_plugin_slugs) — Returns a list of slugs of installed plugins, if known.
* [get\_installed\_plugins](wp_plugin_install_list_table/get_installed_plugins) — Return the list of known plugins.
* [get\_table\_classes](wp_plugin_install_list_table/get_table_classes)
* [get\_views](wp_plugin_install_list_table/get_views)
* [no\_items](wp_plugin_install_list_table/no_items)
* [order\_callback](wp_plugin_install_list_table/order_callback)
* [prepare\_items](wp_plugin_install_list_table/prepare_items)
* [views](wp_plugin_install_list_table/views) — Overrides parent views so we can use the filter bar display.
File: `wp-admin/includes/class-wp-plugin-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugin-install-list-table.php/)
```
class WP_Plugin_Install_List_Table extends WP_List_Table {
public $order = 'ASC';
public $orderby = null;
public $groups = array();
private $error;
/**
* @return bool
*/
public function ajax_user_can() {
return current_user_can( 'install_plugins' );
}
/**
* Return the list of known plugins.
*
* Uses the transient data from the updates API to determine the known
* installed plugins.
*
* @since 4.9.0
* @access protected
*
* @return array
*/
protected function get_installed_plugins() {
$plugins = array();
$plugin_info = get_site_transient( 'update_plugins' );
if ( isset( $plugin_info->no_update ) ) {
foreach ( $plugin_info->no_update as $plugin ) {
if ( isset( $plugin->slug ) ) {
$plugin->upgrade = false;
$plugins[ $plugin->slug ] = $plugin;
}
}
}
if ( isset( $plugin_info->response ) ) {
foreach ( $plugin_info->response as $plugin ) {
if ( isset( $plugin->slug ) ) {
$plugin->upgrade = true;
$plugins[ $plugin->slug ] = $plugin;
}
}
}
return $plugins;
}
/**
* Returns a list of slugs of installed plugins, if known.
*
* Uses the transient data from the updates API to determine the slugs of
* known installed plugins. This might be better elsewhere, perhaps even
* within get_plugins().
*
* @since 4.0.0
*
* @return array
*/
protected function get_installed_plugin_slugs() {
return array_keys( $this->get_installed_plugins() );
}
/**
* @global array $tabs
* @global string $tab
* @global int $paged
* @global string $type
* @global string $term
*/
public function prepare_items() {
include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
global $tabs, $tab, $paged, $type, $term;
wp_reset_vars( array( 'tab' ) );
$paged = $this->get_pagenum();
$per_page = 36;
// These are the tabs which are shown on the page.
$tabs = array();
if ( 'search' === $tab ) {
$tabs['search'] = __( 'Search Results' );
}
if ( 'beta' === $tab || false !== strpos( get_bloginfo( 'version' ), '-' ) ) {
$tabs['beta'] = _x( 'Beta Testing', 'Plugin Installer' );
}
$tabs['featured'] = _x( 'Featured', 'Plugin Installer' );
$tabs['popular'] = _x( 'Popular', 'Plugin Installer' );
$tabs['recommended'] = _x( 'Recommended', 'Plugin Installer' );
$tabs['favorites'] = _x( 'Favorites', 'Plugin Installer' );
if ( current_user_can( 'upload_plugins' ) ) {
// No longer a real tab. Here for filter compatibility.
// Gets skipped in get_views().
$tabs['upload'] = __( 'Upload Plugin' );
}
$nonmenu_tabs = array( 'plugin-information' ); // Valid actions to perform which do not have a Menu item.
/**
* Filters the tabs shown on the Add Plugins screen.
*
* @since 2.7.0
*
* @param string[] $tabs The tabs shown on the Add Plugins screen. Defaults include
* 'featured', 'popular', 'recommended', 'favorites', and 'upload'.
*/
$tabs = apply_filters( 'install_plugins_tabs', $tabs );
/**
* Filters tabs not associated with a menu item on the Add Plugins screen.
*
* @since 2.7.0
*
* @param string[] $nonmenu_tabs The tabs that don't have a menu item on the Add Plugins screen.
*/
$nonmenu_tabs = apply_filters( 'install_plugins_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 );
}
$installed_plugins = $this->get_installed_plugins();
$args = array(
'page' => $paged,
'per_page' => $per_page,
// Send the locale to the API so it can provide context-sensitive results.
'locale' => get_user_locale(),
);
switch ( $tab ) {
case 'search':
$type = isset( $_REQUEST['type'] ) ? wp_unslash( $_REQUEST['type'] ) : 'term';
$term = isset( $_REQUEST['s'] ) ? wp_unslash( $_REQUEST['s'] ) : '';
switch ( $type ) {
case 'tag':
$args['tag'] = sanitize_title_with_dashes( $term );
break;
case 'term':
$args['search'] = $term;
break;
case 'author':
$args['author'] = $term;
break;
}
break;
case 'featured':
case 'popular':
case 'new':
case 'beta':
$args['browse'] = $tab;
break;
case 'recommended':
$args['browse'] = $tab;
// Include the list of installed plugins so we can get relevant results.
$args['installed_plugins'] = array_keys( $installed_plugins );
break;
case 'favorites':
$action = 'save_wporg_username_' . get_current_user_id();
if ( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( wp_unslash( $_GET['_wpnonce'] ), $action ) ) {
$user = isset( $_GET['user'] ) ? wp_unslash( $_GET['user'] ) : get_user_option( 'wporg_favorites' );
// If the save url parameter is passed with a falsey value, don't save the favorite user.
if ( ! isset( $_GET['save'] ) || $_GET['save'] ) {
update_user_meta( get_current_user_id(), 'wporg_favorites', $user );
}
} else {
$user = get_user_option( 'wporg_favorites' );
}
if ( $user ) {
$args['user'] = $user;
} else {
$args = false;
}
add_action( 'install_plugins_favorites', 'install_plugins_favorites_form', 9, 0 );
break;
default:
$args = false;
break;
}
/**
* Filters API request arguments for each Add Plugins screen tab.
*
* The dynamic portion of the hook name, `$tab`, refers to the plugin install tabs.
*
* Possible hook names include:
*
* - `install_plugins_table_api_args_favorites`
* - `install_plugins_table_api_args_featured`
* - `install_plugins_table_api_args_popular`
* - `install_plugins_table_api_args_recommended`
* - `install_plugins_table_api_args_upload`
* - `install_plugins_table_api_args_search`
* - `install_plugins_table_api_args_beta`
*
* @since 3.7.0
*
* @param array|false $args Plugin install API arguments.
*/
$args = apply_filters( "install_plugins_table_api_args_{$tab}", $args );
if ( ! $args ) {
return;
}
$api = plugins_api( 'query_plugins', $args );
if ( is_wp_error( $api ) ) {
$this->error = $api;
return;
}
$this->items = $api->plugins;
if ( $this->orderby ) {
uasort( $this->items, array( $this, 'order_callback' ) );
}
$this->set_pagination_args(
array(
'total_items' => $api->info['results'],
'per_page' => $args['per_page'],
)
);
if ( isset( $api->info['groups'] ) ) {
$this->groups = $api->info['groups'];
}
if ( $installed_plugins ) {
$js_plugins = array_fill_keys(
array( 'all', 'search', 'active', 'inactive', 'recently_activated', 'mustuse', 'dropins' ),
array()
);
$js_plugins['all'] = array_values( wp_list_pluck( $installed_plugins, 'plugin' ) );
$upgrade_plugins = wp_filter_object_list( $installed_plugins, array( 'upgrade' => true ), 'and', 'plugin' );
if ( $upgrade_plugins ) {
$js_plugins['upgrade'] = array_values( $upgrade_plugins );
}
wp_localize_script(
'updates',
'_wpUpdatesItemCounts',
array(
'plugins' => $js_plugins,
'totals' => wp_get_update_data(),
)
);
}
}
/**
*/
public function no_items() {
if ( isset( $this->error ) ) { ?>
<div class="inline error"><p><?php echo $this->error->get_error_message(); ?></p>
<p class="hide-if-no-js"><button class="button try-again"><?php _e( 'Try Again' ); ?></button></p>
</div>
<?php } else { ?>
<div class="no-plugin-results"><?php _e( 'No plugins found. Try a different search.' ); ?></div>
<?php
}
}
/**
* @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[ 'plugin-install-' . $action ] = array(
'url' => self_admin_url( 'plugin-install.php?tab=' . $action ),
'label' => $text,
'current' => $action === $tab,
);
}
// No longer a real tab.
unset( $display_tabs['plugin-install-upload'] );
return $this->get_views_links( $display_tabs );
}
/**
* Overrides parent views so we can use the filter bar display.
*/
public function views() {
$views = $this->get_views();
/** This filter is documented in wp-admin/inclues/class-wp-list-table.php */
$views = apply_filters( "views_{$this->screen->id}", $views );
$this->screen->render_screen_reader_content( 'heading_views' );
?>
<div class="wp-filter">
<ul class="filter-links">
<?php
if ( ! empty( $views ) ) {
foreach ( $views as $class => $view ) {
$views[ $class ] = "\t<li class='$class'>$view";
}
echo implode( " </li>\n", $views ) . "</li>\n";
}
?>
</ul>
<?php install_search_form(); ?>
</div>
<?php
}
/**
* Displays the plugin install table.
*
* Overrides the parent display() method to provide a different container.
*
* @since 4.0.0
*/
public function display() {
$singular = $this->_args['singular'];
$data_attr = '';
if ( $singular ) {
$data_attr = " data-wp-lists='list:$singular'";
}
$this->display_tablenav( 'top' );
?>
<div class="wp-list-table <?php echo implode( ' ', $this->get_table_classes() ); ?>">
<?php
$this->screen->render_screen_reader_content( 'heading_list' );
?>
<div id="the-list"<?php echo $data_attr; ?>>
<?php $this->display_rows_or_placeholder(); ?>
</div>
</div>
<?php
$this->display_tablenav( 'bottom' );
}
/**
* @global string $tab
*
* @param string $which
*/
protected function display_tablenav( $which ) {
if ( 'featured' === $GLOBALS['tab'] ) {
return;
}
if ( 'top' === $which ) {
wp_referer_field();
?>
<div class="tablenav top">
<div class="alignleft actions">
<?php
/**
* Fires before the Plugin Install table header pagination is displayed.
*
* @since 2.7.0
*/
do_action( 'install_plugins_table_header' );
?>
</div>
<?php $this->pagination( $which ); ?>
<br class="clear" />
</div>
<?php } else { ?>
<div class="tablenav bottom">
<?php $this->pagination( $which ); ?>
<br class="clear" />
</div>
<?php
}
}
/**
* @return array
*/
protected function get_table_classes() {
return array( 'widefat', $this->_args['plural'] );
}
/**
* @return array
*/
public function get_columns() {
return array();
}
/**
* @param object $plugin_a
* @param object $plugin_b
* @return int
*/
private function order_callback( $plugin_a, $plugin_b ) {
$orderby = $this->orderby;
if ( ! isset( $plugin_a->$orderby, $plugin_b->$orderby ) ) {
return 0;
}
$a = $plugin_a->$orderby;
$b = $plugin_b->$orderby;
if ( $a === $b ) {
return 0;
}
if ( 'DESC' === $this->order ) {
return ( $a < $b ) ? 1 : -1;
} else {
return ( $a < $b ) ? -1 : 1;
}
}
public function display_rows() {
$plugins_allowedtags = array(
'a' => array(
'href' => array(),
'title' => array(),
'target' => array(),
),
'abbr' => array( 'title' => array() ),
'acronym' => array( 'title' => array() ),
'code' => array(),
'pre' => array(),
'em' => array(),
'strong' => array(),
'ul' => array(),
'ol' => array(),
'li' => array(),
'p' => array(),
'br' => array(),
);
$plugins_group_titles = array(
'Performance' => _x( 'Performance', 'Plugin installer group title' ),
'Social' => _x( 'Social', 'Plugin installer group title' ),
'Tools' => _x( 'Tools', 'Plugin installer group title' ),
);
$group = null;
foreach ( (array) $this->items as $plugin ) {
if ( is_object( $plugin ) ) {
$plugin = (array) $plugin;
}
// Display the group heading if there is one.
if ( isset( $plugin['group'] ) && $plugin['group'] !== $group ) {
if ( isset( $this->groups[ $plugin['group'] ] ) ) {
$group_name = $this->groups[ $plugin['group'] ];
if ( isset( $plugins_group_titles[ $group_name ] ) ) {
$group_name = $plugins_group_titles[ $group_name ];
}
} else {
$group_name = $plugin['group'];
}
// Starting a new group, close off the divs of the last one.
if ( ! empty( $group ) ) {
echo '</div></div>';
}
echo '<div class="plugin-group"><h3>' . esc_html( $group_name ) . '</h3>';
// Needs an extra wrapping div for nth-child selectors to work.
echo '<div class="plugin-items">';
$group = $plugin['group'];
}
$title = wp_kses( $plugin['name'], $plugins_allowedtags );
// Remove any HTML from the description.
$description = strip_tags( $plugin['short_description'] );
/**
* Filters the plugin card description on the Add Plugins screen.
*
* @since 6.0.0
*
* @param string $description Plugin card description.
* @param array $plugin An array of plugin data. See {@see plugins_api()}
* for the list of possible values.
*/
$description = apply_filters( 'plugin_install_description', $description, $plugin );
$version = wp_kses( $plugin['version'], $plugins_allowedtags );
$name = strip_tags( $title . ' ' . $version );
$author = wp_kses( $plugin['author'], $plugins_allowedtags );
if ( ! empty( $author ) ) {
/* translators: %s: Plugin author. */
$author = ' <cite>' . sprintf( __( 'By %s' ), $author ) . '</cite>';
}
$requires_php = isset( $plugin['requires_php'] ) ? $plugin['requires_php'] : null;
$requires_wp = isset( $plugin['requires'] ) ? $plugin['requires'] : null;
$compatible_php = is_php_version_compatible( $requires_php );
$compatible_wp = is_wp_version_compatible( $requires_wp );
$tested_wp = ( empty( $plugin['tested'] ) || version_compare( get_bloginfo( 'version' ), $plugin['tested'], '<=' ) );
$action_links = array();
if ( current_user_can( 'install_plugins' ) || current_user_can( 'update_plugins' ) ) {
$status = install_plugin_install_status( $plugin );
switch ( $status['status'] ) {
case 'install':
if ( $status['url'] ) {
if ( $compatible_php && $compatible_wp ) {
$action_links[] = sprintf(
'<a class="install-now button" data-slug="%s" href="%s" aria-label="%s" data-name="%s">%s</a>',
esc_attr( $plugin['slug'] ),
esc_url( $status['url'] ),
/* translators: %s: Plugin name and version. */
esc_attr( sprintf( _x( 'Install %s now', 'plugin' ), $name ) ),
esc_attr( $name ),
__( 'Install Now' )
);
} else {
$action_links[] = sprintf(
'<button type="button" class="button button-disabled" disabled="disabled">%s</button>',
_x( 'Cannot Install', 'plugin' )
);
}
}
break;
case 'update_available':
if ( $status['url'] ) {
if ( $compatible_php && $compatible_wp ) {
$action_links[] = sprintf(
'<a class="update-now button aria-button-if-js" data-plugin="%s" data-slug="%s" href="%s" aria-label="%s" data-name="%s">%s</a>',
esc_attr( $status['file'] ),
esc_attr( $plugin['slug'] ),
esc_url( $status['url'] ),
/* translators: %s: Plugin name and version. */
esc_attr( sprintf( _x( 'Update %s now', 'plugin' ), $name ) ),
esc_attr( $name ),
__( 'Update Now' )
);
} else {
$action_links[] = sprintf(
'<button type="button" class="button button-disabled" disabled="disabled">%s</button>',
_x( 'Cannot Update', 'plugin' )
);
}
}
break;
case 'latest_installed':
case 'newer_installed':
if ( is_plugin_active( $status['file'] ) ) {
$action_links[] = sprintf(
'<button type="button" class="button button-disabled" disabled="disabled">%s</button>',
_x( 'Active', 'plugin' )
);
} elseif ( current_user_can( 'activate_plugin', $status['file'] ) ) {
if ( $compatible_php && $compatible_wp ) {
$button_text = __( 'Activate' );
/* translators: %s: Plugin name. */
$button_label = _x( 'Activate %s', 'plugin' );
$activate_url = add_query_arg(
array(
'_wpnonce' => wp_create_nonce( 'activate-plugin_' . $status['file'] ),
'action' => 'activate',
'plugin' => $status['file'],
),
network_admin_url( 'plugins.php' )
);
if ( is_network_admin() ) {
$button_text = __( 'Network Activate' );
/* translators: %s: Plugin name. */
$button_label = _x( 'Network Activate %s', 'plugin' );
$activate_url = add_query_arg( array( 'networkwide' => 1 ), $activate_url );
}
$action_links[] = sprintf(
'<a href="%1$s" class="button activate-now" aria-label="%2$s">%3$s</a>',
esc_url( $activate_url ),
esc_attr( sprintf( $button_label, $plugin['name'] ) ),
$button_text
);
} else {
$action_links[] = sprintf(
'<button type="button" class="button button-disabled" disabled="disabled">%s</button>',
_x( 'Cannot Activate', 'plugin' )
);
}
} else {
$action_links[] = sprintf(
'<button type="button" class="button button-disabled" disabled="disabled">%s</button>',
_x( 'Installed', 'plugin' )
);
}
break;
}
}
$details_link = self_admin_url(
'plugin-install.php?tab=plugin-information&plugin=' . $plugin['slug'] .
'&TB_iframe=true&width=600&height=550'
);
$action_links[] = sprintf(
'<a href="%s" class="thickbox open-plugin-details-modal" aria-label="%s" data-title="%s">%s</a>',
esc_url( $details_link ),
/* translators: %s: Plugin name and version. */
esc_attr( sprintf( __( 'More information about %s' ), $name ) ),
esc_attr( $name ),
__( 'More Details' )
);
if ( ! empty( $plugin['icons']['svg'] ) ) {
$plugin_icon_url = $plugin['icons']['svg'];
} elseif ( ! empty( $plugin['icons']['2x'] ) ) {
$plugin_icon_url = $plugin['icons']['2x'];
} elseif ( ! empty( $plugin['icons']['1x'] ) ) {
$plugin_icon_url = $plugin['icons']['1x'];
} else {
$plugin_icon_url = $plugin['icons']['default'];
}
/**
* Filters the install action links for a plugin.
*
* @since 2.7.0
*
* @param string[] $action_links An array of plugin action links.
* Defaults are links to Details and Install Now.
* @param array $plugin An array of plugin data. See {@see plugins_api()}
* for the list of possible values.
*/
$action_links = apply_filters( 'plugin_install_action_links', $action_links, $plugin );
$last_updated_timestamp = strtotime( $plugin['last_updated'] );
?>
<div class="plugin-card plugin-card-<?php echo sanitize_html_class( $plugin['slug'] ); ?>">
<?php
if ( ! $compatible_php || ! $compatible_wp ) {
echo '<div class="notice inline notice-error notice-alt"><p>';
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>';
}
?>
<div class="plugin-card-top">
<div class="name column-name">
<h3>
<a href="<?php echo esc_url( $details_link ); ?>" class="thickbox open-plugin-details-modal">
<?php echo $title; ?>
<img src="<?php echo esc_url( $plugin_icon_url ); ?>" class="plugin-icon" alt="" />
</a>
</h3>
</div>
<div class="action-links">
<?php
if ( $action_links ) {
echo '<ul class="plugin-action-buttons"><li>' . implode( '</li><li>', $action_links ) . '</li></ul>';
}
?>
</div>
<div class="desc column-description">
<p><?php echo $description; ?></p>
<p class="authors"><?php echo $author; ?></p>
</div>
</div>
<div class="plugin-card-bottom">
<div class="vers column-rating">
<?php
wp_star_rating(
array(
'rating' => $plugin['rating'],
'type' => 'percent',
'number' => $plugin['num_ratings'],
)
);
?>
<span class="num-ratings" aria-hidden="true">(<?php echo number_format_i18n( $plugin['num_ratings'] ); ?>)</span>
</div>
<div class="column-updated">
<strong><?php _e( 'Last Updated:' ); ?></strong>
<?php
/* translators: %s: Human-readable time difference. */
printf( __( '%s ago' ), human_time_diff( $last_updated_timestamp ) );
?>
</div>
<div class="column-downloaded">
<?php
if ( $plugin['active_installs'] >= 1000000 ) {
$active_installs_millions = floor( $plugin['active_installs'] / 1000000 );
$active_installs_text = sprintf(
/* translators: %s: Number of millions. */
_nx( '%s+ Million', '%s+ Million', $active_installs_millions, 'Active plugin installations' ),
number_format_i18n( $active_installs_millions )
);
} elseif ( 0 === $plugin['active_installs'] ) {
$active_installs_text = _x( 'Less Than 10', 'Active plugin installations' );
} else {
$active_installs_text = number_format_i18n( $plugin['active_installs'] ) . '+';
}
/* translators: %s: Number of installations. */
printf( __( '%s Active Installations' ), $active_installs_text );
?>
</div>
<div class="column-compatibility">
<?php
if ( ! $tested_wp ) {
echo '<span class="compatibility-untested">' . __( 'Untested with your version of WordPress' ) . '</span>';
} elseif ( ! $compatible_wp ) {
echo '<span class="compatibility-incompatible">' . __( '<strong>Incompatible</strong> with your version of WordPress' ) . '</span>';
} else {
echo '<span class="compatibility-compatible">' . __( '<strong>Compatible</strong> with your version of WordPress' ) . '</span>';
}
?>
</div>
</div>
</div>
<?php
}
// Close off the group divs of the last one.
if ( ! empty( $group ) ) {
echo '</div></div>';
}
}
}
```
| 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 Bulk_Theme_Upgrader_Skin {} class Bulk\_Theme\_Upgrader\_Skin {}
====================================
Bulk Theme Upgrader Skin for WordPress Theme Upgrades.
* [Bulk\_Upgrader\_Skin](bulk_upgrader_skin)
* [add\_strings](bulk_theme_upgrader_skin/add_strings)
* [after](bulk_theme_upgrader_skin/after)
* [before](bulk_theme_upgrader_skin/before)
* [bulk\_footer](bulk_theme_upgrader_skin/bulk_footer)
File: `wp-admin/includes/class-bulk-theme-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-bulk-theme-upgrader-skin.php/)
```
class Bulk_Theme_Upgrader_Skin extends Bulk_Upgrader_Skin {
/**
* 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;
public function add_strings() {
parent::add_strings();
/* translators: 1: Theme name, 2: Number of the theme, 3: Total number of themes being updated. */
$this->upgrader->strings['skin_before_update_header'] = __( 'Updating Theme %1$s (%2$d/%3$d)' );
}
/**
* @param string $title
*/
public function before( $title = '' ) {
parent::before( $this->theme_info->display( 'Name' ) );
}
/**
* @param string $title
*/
public function after( $title = '' ) {
parent::after( $this->theme_info->display( 'Name' ) );
$this->decrement_update_count( 'theme' );
}
/**
*/
public function bulk_footer() {
parent::bulk_footer();
$update_actions = array(
'themes_page' => sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'themes.php' ),
__( 'Go to Themes page' )
),
'updates_page' => sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'update-core.php' ),
__( 'Go to WordPress Updates page' )
),
);
if ( ! current_user_can( 'switch_themes' ) && ! current_user_can( 'edit_theme_options' ) ) {
unset( $update_actions['themes_page'] );
}
/**
* Filters the list of action links available following bulk theme updates.
*
* @since 3.0.0
*
* @param string[] $update_actions Array of theme action links.
* @param WP_Theme $theme_info Theme object for the last-updated theme.
*/
$update_actions = apply_filters( 'update_bulk_theme_complete_actions', $update_actions, $this->theme_info );
if ( ! empty( $update_actions ) ) {
$this->feedback( implode( ' | ', (array) $update_actions ) );
}
}
}
```
| Uses | Description |
| --- | --- |
| [Bulk\_Upgrader\_Skin](bulk_upgrader_skin) wp-admin/includes/class-bulk-upgrader-skin.php | Generic Bulk Upgrader Skin for 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.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress class WP_Post {} class WP\_Post {}
=================
Core class used to implement the [WP\_Post](wp_post) object.
The [WP\_Post](wp_post) class is used to contain post objects stored by the database and is returned by functions such as [get\_post](../functions/get_post "Function Reference/get post").
* [\_\_construct](wp_post/__construct) — Constructor.
* [\_\_get](wp_post/__get) — Getter.
* [\_\_isset](wp_post/__isset) — Isset-er.
* [filter](wp_post/filter) — {@Missing Summary}
* [get\_instance](wp_post/get_instance) — Retrieve WP\_Post instance.
* [to\_array](wp_post/to_array) — Convert object to array.
File: `wp-includes/class-wp-post.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-post.php/)
```
final class WP_Post {
/**
* Post ID.
*
* @since 3.5.0
* @var int
*/
public $ID;
/**
* ID of post author.
*
* A numeric string, for compatibility reasons.
*
* @since 3.5.0
* @var string
*/
public $post_author = 0;
/**
* The post's local publication time.
*
* @since 3.5.0
* @var string
*/
public $post_date = '0000-00-00 00:00:00';
/**
* The post's GMT publication time.
*
* @since 3.5.0
* @var string
*/
public $post_date_gmt = '0000-00-00 00:00:00';
/**
* The post's content.
*
* @since 3.5.0
* @var string
*/
public $post_content = '';
/**
* The post's title.
*
* @since 3.5.0
* @var string
*/
public $post_title = '';
/**
* The post's excerpt.
*
* @since 3.5.0
* @var string
*/
public $post_excerpt = '';
/**
* The post's status.
*
* @since 3.5.0
* @var string
*/
public $post_status = 'publish';
/**
* Whether comments are allowed.
*
* @since 3.5.0
* @var string
*/
public $comment_status = 'open';
/**
* Whether pings are allowed.
*
* @since 3.5.0
* @var string
*/
public $ping_status = 'open';
/**
* The post's password in plain text.
*
* @since 3.5.0
* @var string
*/
public $post_password = '';
/**
* The post's slug.
*
* @since 3.5.0
* @var string
*/
public $post_name = '';
/**
* URLs queued to be pinged.
*
* @since 3.5.0
* @var string
*/
public $to_ping = '';
/**
* URLs that have been pinged.
*
* @since 3.5.0
* @var string
*/
public $pinged = '';
/**
* The post's local modified time.
*
* @since 3.5.0
* @var string
*/
public $post_modified = '0000-00-00 00:00:00';
/**
* The post's GMT modified time.
*
* @since 3.5.0
* @var string
*/
public $post_modified_gmt = '0000-00-00 00:00:00';
/**
* A utility DB field for post content.
*
* @since 3.5.0
* @var string
*/
public $post_content_filtered = '';
/**
* ID of a post's parent post.
*
* @since 3.5.0
* @var int
*/
public $post_parent = 0;
/**
* The unique identifier for a post, not necessarily a URL, used as the feed GUID.
*
* @since 3.5.0
* @var string
*/
public $guid = '';
/**
* A field used for ordering posts.
*
* @since 3.5.0
* @var int
*/
public $menu_order = 0;
/**
* The post's type, like post or page.
*
* @since 3.5.0
* @var string
*/
public $post_type = 'post';
/**
* An attachment's mime type.
*
* @since 3.5.0
* @var string
*/
public $post_mime_type = '';
/**
* Cached comment count.
*
* A numeric string, for compatibility reasons.
*
* @since 3.5.0
* @var string
*/
public $comment_count = 0;
/**
* Stores the post object's sanitization level.
*
* Does not correspond to a DB field.
*
* @since 3.5.0
* @var string
*/
public $filter;
/**
* Retrieve WP_Post instance.
*
* @since 3.5.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $post_id Post ID.
* @return WP_Post|false Post object, false otherwise.
*/
public static function get_instance( $post_id ) {
global $wpdb;
$post_id = (int) $post_id;
if ( ! $post_id ) {
return false;
}
$_post = wp_cache_get( $post_id, 'posts' );
if ( ! $_post ) {
$_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post_id ) );
if ( ! $_post ) {
return false;
}
$_post = sanitize_post( $_post, 'raw' );
wp_cache_add( $_post->ID, $_post, 'posts' );
} elseif ( empty( $_post->filter ) || 'raw' !== $_post->filter ) {
$_post = sanitize_post( $_post, 'raw' );
}
return new WP_Post( $_post );
}
/**
* Constructor.
*
* @since 3.5.0
*
* @param WP_Post|object $post Post object.
*/
public function __construct( $post ) {
foreach ( get_object_vars( $post ) as $key => $value ) {
$this->$key = $value;
}
}
/**
* Isset-er.
*
* @since 3.5.0
*
* @param string $key Property to check if set.
* @return bool
*/
public function __isset( $key ) {
if ( 'ancestors' === $key ) {
return true;
}
if ( 'page_template' === $key ) {
return true;
}
if ( 'post_category' === $key ) {
return true;
}
if ( 'tags_input' === $key ) {
return true;
}
return metadata_exists( 'post', $this->ID, $key );
}
/**
* Getter.
*
* @since 3.5.0
*
* @param string $key Key to get.
* @return mixed
*/
public function __get( $key ) {
if ( 'page_template' === $key && $this->__isset( $key ) ) {
return get_post_meta( $this->ID, '_wp_page_template', true );
}
if ( 'post_category' === $key ) {
if ( is_object_in_taxonomy( $this->post_type, 'category' ) ) {
$terms = get_the_terms( $this, 'category' );
}
if ( empty( $terms ) ) {
return array();
}
return wp_list_pluck( $terms, 'term_id' );
}
if ( 'tags_input' === $key ) {
if ( is_object_in_taxonomy( $this->post_type, 'post_tag' ) ) {
$terms = get_the_terms( $this, 'post_tag' );
}
if ( empty( $terms ) ) {
return array();
}
return wp_list_pluck( $terms, 'name' );
}
// Rest of the values need filtering.
if ( 'ancestors' === $key ) {
$value = get_post_ancestors( $this );
} else {
$value = get_post_meta( $this->ID, $key, true );
}
if ( $this->filter ) {
$value = sanitize_post_field( $key, $value, $this->ID, $this->filter );
}
return $value;
}
/**
* {@Missing Summary}
*
* @since 3.5.0
*
* @param string $filter Filter.
* @return WP_Post
*/
public function filter( $filter ) {
if ( $this->filter === $filter ) {
return $this;
}
if ( 'raw' === $filter ) {
return self::get_instance( $this->ID );
}
return sanitize_post( $this, $filter );
}
/**
* Convert object to array.
*
* @since 3.5.0
*
* @return array Object as array.
*/
public function to_array() {
$post = get_object_vars( $this );
foreach ( array( 'ancestors', 'page_template', 'post_category', 'tags_input' ) as $key ) {
if ( $this->__isset( $key ) ) {
$post[ $key ] = $this->__get( $key );
}
}
return $post;
}
}
```
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress class WP_REST_Term_Meta_Fields {} class WP\_REST\_Term\_Meta\_Fields {}
=====================================
Core class used to manage meta values for terms via the REST API.
* [WP\_REST\_Meta\_Fields](wp_rest_meta_fields)
* [\_\_construct](wp_rest_term_meta_fields/__construct) — Constructor.
* [get\_meta\_subtype](wp_rest_term_meta_fields/get_meta_subtype) — Retrieves the term meta subtype.
* [get\_meta\_type](wp_rest_term_meta_fields/get_meta_type) — Retrieves the term meta type.
* [get\_rest\_field\_type](wp_rest_term_meta_fields/get_rest_field_type) — Retrieves the type for register\_rest\_field().
File: `wp-includes/rest-api/fields/class-wp-rest-term-meta-fields.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/fields/class-wp-rest-term-meta-fields.php/)
```
class WP_REST_Term_Meta_Fields extends WP_REST_Meta_Fields {
/**
* Taxonomy to register fields for.
*
* @since 4.7.0
* @var string
*/
protected $taxonomy;
/**
* Constructor.
*
* @since 4.7.0
*
* @param string $taxonomy Taxonomy to register fields for.
*/
public function __construct( $taxonomy ) {
$this->taxonomy = $taxonomy;
}
/**
* Retrieves the term meta type.
*
* @since 4.7.0
*
* @return string The meta type.
*/
protected function get_meta_type() {
return 'term';
}
/**
* Retrieves the term meta subtype.
*
* @since 4.9.8
*
* @return string Subtype for the meta type, or empty string if no specific subtype.
*/
protected function get_meta_subtype() {
return $this->taxonomy;
}
/**
* Retrieves the type for register_rest_field().
*
* @since 4.7.0
*
* @return string The REST field type.
*/
public function get_rest_field_type() {
return 'post_tag' === $this->taxonomy ? 'tag' : $this->taxonomy;
}
}
```
| 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 Requests_Transport_cURL {} class Requests\_Transport\_cURL {}
==================================
cURL HTTP transport
* [\_\_construct](requests_transport_curl/__construct) — Constructor
* [\_\_destruct](requests_transport_curl/__destruct) — Destructor
* [format\_get](requests_transport_curl/format_get) — Format a URL given GET data
* [get\_expect\_header](requests_transport_curl/get_expect_header) — Get the correct "Expect" header for the given request data.
* [get\_subrequest\_handle](requests_transport_curl/get_subrequest_handle) — Get the cURL handle for use in a multi-request
* [process\_response](requests_transport_curl/process_response) — Process a response
* [request](requests_transport_curl/request) — Perform a request
* [request\_multiple](requests_transport_curl/request_multiple) — Send multiple requests simultaneously
* [setup\_handle](requests_transport_curl/setup_handle) — Setup the cURL handle for the given data
* [stream\_body](requests_transport_curl/stream_body) — Collect data as it's received
* [stream\_headers](requests_transport_curl/stream_headers) — Collect the headers as they are received
* [test](requests_transport_curl/test) — Whether this transport is valid
File: `wp-includes/Requests/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/transport/curl.php/)
```
class Requests_Transport_cURL implements Requests_Transport {
const CURL_7_10_5 = 0x070A05;
const CURL_7_16_2 = 0x071002;
/**
* Raw HTTP data
*
* @var string
*/
public $headers = '';
/**
* Raw body data
*
* @var string
*/
public $response_data = '';
/**
* Information on the current request
*
* @var array cURL information array, see {@see https://secure.php.net/curl_getinfo}
*/
public $info;
/**
* cURL version number
*
* @var int
*/
public $version;
/**
* cURL handle
*
* @var resource
*/
protected $handle;
/**
* Hook dispatcher instance
*
* @var Requests_Hooks
*/
protected $hooks;
/**
* Have we finished the headers yet?
*
* @var boolean
*/
protected $done_headers = false;
/**
* If streaming to a file, keep the file pointer
*
* @var resource
*/
protected $stream_handle;
/**
* How many bytes are in the response body?
*
* @var int
*/
protected $response_bytes;
/**
* What's the maximum number of bytes we should keep?
*
* @var int|bool Byte count, or false if no limit.
*/
protected $response_byte_limit;
/**
* Constructor
*/
public function __construct() {
$curl = curl_version();
$this->version = $curl['version_number'];
$this->handle = curl_init();
curl_setopt($this->handle, CURLOPT_HEADER, false);
curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, 1);
if ($this->version >= self::CURL_7_10_5) {
curl_setopt($this->handle, CURLOPT_ENCODING, '');
}
if (defined('CURLOPT_PROTOCOLS')) {
// phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_protocolsFound
curl_setopt($this->handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
}
if (defined('CURLOPT_REDIR_PROTOCOLS')) {
// phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_redir_protocolsFound
curl_setopt($this->handle, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
}
}
/**
* Destructor
*/
public function __destruct() {
if (is_resource($this->handle)) {
curl_close($this->handle);
}
}
/**
* Perform a request
*
* @throws Requests_Exception On a cURL error (`curlerror`)
*
* @param string $url URL to request
* @param array $headers Associative array of request headers
* @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
* @param array $options Request options, see {@see Requests::response()} for documentation
* @return string Raw HTTP result
*/
public function request($url, $headers = array(), $data = array(), $options = array()) {
$this->hooks = $options['hooks'];
$this->setup_handle($url, $headers, $data, $options);
$options['hooks']->dispatch('curl.before_send', array(&$this->handle));
if ($options['filename'] !== false) {
$this->stream_handle = fopen($options['filename'], 'wb');
}
$this->response_data = '';
$this->response_bytes = 0;
$this->response_byte_limit = false;
if ($options['max_bytes'] !== false) {
$this->response_byte_limit = $options['max_bytes'];
}
if (isset($options['verify'])) {
if ($options['verify'] === false) {
curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($this->handle, CURLOPT_SSL_VERIFYPEER, 0);
}
elseif (is_string($options['verify'])) {
curl_setopt($this->handle, CURLOPT_CAINFO, $options['verify']);
}
}
if (isset($options['verifyname']) && $options['verifyname'] === false) {
curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0);
}
curl_exec($this->handle);
$response = $this->response_data;
$options['hooks']->dispatch('curl.after_send', array());
if (curl_errno($this->handle) === 23 || curl_errno($this->handle) === 61) {
// Reset encoding and try again
curl_setopt($this->handle, CURLOPT_ENCODING, 'none');
$this->response_data = '';
$this->response_bytes = 0;
curl_exec($this->handle);
$response = $this->response_data;
}
$this->process_response($response, $options);
// Need to remove the $this reference from the curl handle.
// Otherwise Requests_Transport_cURL wont be garbage collected and the curl_close() will never be called.
curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, null);
curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, null);
return $this->headers;
}
/**
* Send multiple requests simultaneously
*
* @param array $requests Request data
* @param array $options Global options
* @return array Array of Requests_Response objects (may contain Requests_Exception or string responses as well)
*/
public function request_multiple($requests, $options) {
// If you're not requesting, we can't get any responses ¯\_(ツ)_/¯
if (empty($requests)) {
return array();
}
$multihandle = curl_multi_init();
$subrequests = array();
$subhandles = array();
$class = get_class($this);
foreach ($requests as $id => $request) {
$subrequests[$id] = new $class();
$subhandles[$id] = $subrequests[$id]->get_subrequest_handle($request['url'], $request['headers'], $request['data'], $request['options']);
$request['options']['hooks']->dispatch('curl.before_multi_add', array(&$subhandles[$id]));
curl_multi_add_handle($multihandle, $subhandles[$id]);
}
$completed = 0;
$responses = array();
$subrequestcount = count($subrequests);
$request['options']['hooks']->dispatch('curl.before_multi_exec', array(&$multihandle));
do {
$active = 0;
do {
$status = curl_multi_exec($multihandle, $active);
}
while ($status === CURLM_CALL_MULTI_PERFORM);
$to_process = array();
// Read the information as needed
while ($done = curl_multi_info_read($multihandle)) {
$key = array_search($done['handle'], $subhandles, true);
if (!isset($to_process[$key])) {
$to_process[$key] = $done;
}
}
// Parse the finished requests before we start getting the new ones
foreach ($to_process as $key => $done) {
$options = $requests[$key]['options'];
if ($done['result'] !== CURLE_OK) {
//get error string for handle.
$reason = curl_error($done['handle']);
$exception = new Requests_Exception_Transport_cURL(
$reason,
Requests_Exception_Transport_cURL::EASY,
$done['handle'],
$done['result']
);
$responses[$key] = $exception;
$options['hooks']->dispatch('transport.internal.parse_error', array(&$responses[$key], $requests[$key]));
}
else {
$responses[$key] = $subrequests[$key]->process_response($subrequests[$key]->response_data, $options);
$options['hooks']->dispatch('transport.internal.parse_response', array(&$responses[$key], $requests[$key]));
}
curl_multi_remove_handle($multihandle, $done['handle']);
curl_close($done['handle']);
if (!is_string($responses[$key])) {
$options['hooks']->dispatch('multiple.request.complete', array(&$responses[$key], $key));
}
$completed++;
}
}
while ($active || $completed < $subrequestcount);
$request['options']['hooks']->dispatch('curl.after_multi_exec', array(&$multihandle));
curl_multi_close($multihandle);
return $responses;
}
/**
* Get the cURL handle for use in a multi-request
*
* @param string $url URL to request
* @param array $headers Associative array of request headers
* @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
* @param array $options Request options, see {@see Requests::response()} for documentation
* @return resource Subrequest's cURL handle
*/
public function &get_subrequest_handle($url, $headers, $data, $options) {
$this->setup_handle($url, $headers, $data, $options);
if ($options['filename'] !== false) {
$this->stream_handle = fopen($options['filename'], 'wb');
}
$this->response_data = '';
$this->response_bytes = 0;
$this->response_byte_limit = false;
if ($options['max_bytes'] !== false) {
$this->response_byte_limit = $options['max_bytes'];
}
$this->hooks = $options['hooks'];
return $this->handle;
}
/**
* Setup the cURL handle for the given data
*
* @param string $url URL to request
* @param array $headers Associative array of request headers
* @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
* @param array $options Request options, see {@see Requests::response()} for documentation
*/
protected function setup_handle($url, $headers, $data, $options) {
$options['hooks']->dispatch('curl.before_request', array(&$this->handle));
// Force closing the connection for old versions of cURL (<7.22).
if (!isset($headers['Connection'])) {
$headers['Connection'] = 'close';
}
/**
* Add "Expect" header.
*
* By default, cURL adds a "Expect: 100-Continue" to most requests. This header can
* add as much as a second to the time it takes for cURL to perform a request. To
* prevent this, we need to set an empty "Expect" header. To match the behaviour of
* Guzzle, we'll add the empty header to requests that are smaller than 1 MB and use
* HTTP/1.1.
*
* https://curl.se/mail/lib-2017-07/0013.html
*/
if (!isset($headers['Expect']) && $options['protocol_version'] === 1.1) {
$headers['Expect'] = $this->get_expect_header($data);
}
$headers = Requests::flatten($headers);
if (!empty($data)) {
$data_format = $options['data_format'];
if ($data_format === 'query') {
$url = self::format_get($url, $data);
$data = '';
}
elseif (!is_string($data)) {
$data = http_build_query($data, null, '&');
}
}
switch ($options['type']) {
case Requests::POST:
curl_setopt($this->handle, CURLOPT_POST, true);
curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data);
break;
case Requests::HEAD:
curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
curl_setopt($this->handle, CURLOPT_NOBODY, true);
break;
case Requests::TRACE:
curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
break;
case Requests::PATCH:
case Requests::PUT:
case Requests::DELETE:
case Requests::OPTIONS:
default:
curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
if (!empty($data)) {
curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data);
}
}
// cURL requires a minimum timeout of 1 second when using the system
// DNS resolver, as it uses `alarm()`, which is second resolution only.
// There's no way to detect which DNS resolver is being used from our
// end, so we need to round up regardless of the supplied timeout.
//
// https://github.com/curl/curl/blob/4f45240bc84a9aa648c8f7243be7b79e9f9323a5/lib/hostip.c#L606-L609
$timeout = max($options['timeout'], 1);
if (is_int($timeout) || $this->version < self::CURL_7_16_2) {
curl_setopt($this->handle, CURLOPT_TIMEOUT, ceil($timeout));
}
else {
// phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_timeout_msFound
curl_setopt($this->handle, CURLOPT_TIMEOUT_MS, round($timeout * 1000));
}
if (is_int($options['connect_timeout']) || $this->version < self::CURL_7_16_2) {
curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT, ceil($options['connect_timeout']));
}
else {
// phpcs:ignore PHPCompatibility.Constants.NewConstants.curlopt_connecttimeout_msFound
curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT_MS, round($options['connect_timeout'] * 1000));
}
curl_setopt($this->handle, CURLOPT_URL, $url);
curl_setopt($this->handle, CURLOPT_REFERER, $url);
curl_setopt($this->handle, CURLOPT_USERAGENT, $options['useragent']);
if (!empty($headers)) {
curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers);
}
if ($options['protocol_version'] === 1.1) {
curl_setopt($this->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
}
else {
curl_setopt($this->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
}
if ($options['blocking'] === true) {
curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, array($this, 'stream_headers'));
curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, array($this, 'stream_body'));
curl_setopt($this->handle, CURLOPT_BUFFERSIZE, Requests::BUFFER_SIZE);
}
}
/**
* Process a response
*
* @param string $response Response data from the body
* @param array $options Request options
* @return string|false HTTP response data including headers. False if non-blocking.
* @throws Requests_Exception
*/
public function process_response($response, $options) {
if ($options['blocking'] === false) {
$fake_headers = '';
$options['hooks']->dispatch('curl.after_request', array(&$fake_headers));
return false;
}
if ($options['filename'] !== false && $this->stream_handle) {
fclose($this->stream_handle);
$this->headers = trim($this->headers);
}
else {
$this->headers .= $response;
}
if (curl_errno($this->handle)) {
$error = sprintf(
'cURL error %s: %s',
curl_errno($this->handle),
curl_error($this->handle)
);
throw new Requests_Exception($error, 'curlerror', $this->handle);
}
$this->info = curl_getinfo($this->handle);
$options['hooks']->dispatch('curl.after_request', array(&$this->headers, &$this->info));
return $this->headers;
}
/**
* Collect the headers as they are received
*
* @param resource $handle cURL resource
* @param string $headers Header string
* @return integer Length of provided header
*/
public function stream_headers($handle, $headers) {
// Why do we do this? cURL will send both the final response and any
// interim responses, such as a 100 Continue. We don't need that.
// (We may want to keep this somewhere just in case)
if ($this->done_headers) {
$this->headers = '';
$this->done_headers = false;
}
$this->headers .= $headers;
if ($headers === "\r\n") {
$this->done_headers = true;
}
return strlen($headers);
}
/**
* Collect data as it's received
*
* @since 1.6.1
*
* @param resource $handle cURL resource
* @param string $data Body data
* @return integer Length of provided data
*/
public function stream_body($handle, $data) {
$this->hooks->dispatch('request.progress', array($data, $this->response_bytes, $this->response_byte_limit));
$data_length = strlen($data);
// Are we limiting the response size?
if ($this->response_byte_limit) {
if ($this->response_bytes === $this->response_byte_limit) {
// Already at maximum, move on
return $data_length;
}
if (($this->response_bytes + $data_length) > $this->response_byte_limit) {
// Limit the length
$limited_length = ($this->response_byte_limit - $this->response_bytes);
$data = substr($data, 0, $limited_length);
}
}
if ($this->stream_handle) {
fwrite($this->stream_handle, $data);
}
else {
$this->response_data .= $data;
}
$this->response_bytes += strlen($data);
return $data_length;
}
/**
* Format a URL given GET data
*
* @param string $url
* @param array|object $data Data to build query using, see {@see https://secure.php.net/http_build_query}
* @return string URL with data
*/
protected static function format_get($url, $data) {
if (!empty($data)) {
$query = '';
$url_parts = parse_url($url);
if (empty($url_parts['query'])) {
$url_parts['query'] = '';
}
else {
$query = $url_parts['query'];
}
$query .= '&' . http_build_query($data, null, '&');
$query = trim($query, '&');
if (empty($url_parts['query'])) {
$url .= '?' . $query;
}
else {
$url = str_replace($url_parts['query'], $query, $url);
}
}
return $url;
}
/**
* Whether this transport is valid
*
* @codeCoverageIgnore
* @return boolean True if the transport is valid, false otherwise.
*/
public static function test($capabilities = array()) {
if (!function_exists('curl_init') || !function_exists('curl_exec')) {
return false;
}
// If needed, check that our installed curl version supports SSL
if (isset($capabilities['ssl']) && $capabilities['ssl']) {
$curl_version = curl_version();
if (!(CURL_VERSION_SSL & $curl_version['features'])) {
return false;
}
}
return true;
}
/**
* Get the correct "Expect" header for the given request data.
*
* @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD.
* @return string The "Expect" header.
*/
protected function get_expect_header($data) {
if (!is_array($data)) {
return strlen((string) $data) >= 1048576 ? '100-Continue' : '';
}
$bytesize = 0;
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
foreach ($iterator as $datum) {
$bytesize += strlen((string) $datum);
if ($bytesize >= 1048576) {
return '100-Continue';
}
}
return '';
}
}
```
| programming_docs |
wordpress class WP_Text_Diff_Renderer_Table {} class WP\_Text\_Diff\_Renderer\_Table {}
========================================
Table renderer to display the diff lines.
* [\_\_construct](wp_text_diff_renderer_table/__construct) — Constructor - Call parent constructor with params array.
* [\_\_get](wp_text_diff_renderer_table/__get) — Make private properties readable for backward compatibility.
* [\_\_isset](wp_text_diff_renderer_table/__isset) — Make private properties checkable for backward compatibility.
* [\_\_set](wp_text_diff_renderer_table/__set) — Make private properties settable for backward compatibility.
* [\_\_unset](wp_text_diff_renderer_table/__unset) — Make private properties un-settable for backward compatibility.
* [\_changed](wp_text_diff_renderer_table/_changed) — Process changed lines to do word-by-word diffs for extra highlighting.
* [compute\_string\_distance](wp_text_diff_renderer_table/compute_string_distance) — Computes a number that is intended to reflect the "distance" between two strings.
* [interleave\_changed\_lines](wp_text_diff_renderer_table/interleave_changed_lines) — Takes changed blocks and matches which rows in orig turned into which rows in final.
File: `wp-includes/class-wp-text-diff-renderer-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-text-diff-renderer-table.php/)
```
class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer {
/**
* @see Text_Diff_Renderer::_leading_context_lines
* @var int
* @since 2.6.0
*/
public $_leading_context_lines = 10000;
/**
* @see Text_Diff_Renderer::_trailing_context_lines
* @var int
* @since 2.6.0
*/
public $_trailing_context_lines = 10000;
/**
* Threshold for when a diff should be saved or omitted.
*
* @var float
* @since 2.6.0
*/
protected $_diff_threshold = 0.6;
/**
* Inline display helper object name.
*
* @var string
* @since 2.6.0
*/
protected $inline_diff_renderer = 'WP_Text_Diff_Renderer_inline';
/**
* Should we show the split view or not
*
* @var string
* @since 3.6.0
*/
protected $_show_split_view = true;
protected $compat_fields = array( '_show_split_view', 'inline_diff_renderer', '_diff_threshold' );
/**
* Caches the output of count_chars() in compute_string_distance()
*
* @var array
* @since 5.0.0
*/
protected $count_cache = array();
/**
* Caches the difference calculation in compute_string_distance()
*
* @var array
* @since 5.0.0
*/
protected $difference_cache = array();
/**
* Constructor - Call parent constructor with params array.
*
* This will set class properties based on the key value pairs in the array.
*
* @since 2.6.0
*
* @param array $params
*/
public function __construct( $params = array() ) {
parent::__construct( $params );
if ( isset( $params['show_split_view'] ) ) {
$this->_show_split_view = $params['show_split_view'];
}
}
/**
* @ignore
*
* @param string $header
* @return string
*/
public function _startBlock( $header ) {
return '';
}
/**
* @ignore
*
* @param array $lines
* @param string $prefix
*/
public function _lines( $lines, $prefix = ' ' ) {
}
/**
* @ignore
*
* @param string $line HTML-escape the value.
* @return string
*/
public function addedLine( $line ) {
return "<td class='diff-addedline'><span aria-hidden='true' class='dashicons dashicons-plus'></span><span class='screen-reader-text'>" . __( 'Added:' ) . " </span>{$line}</td>";
}
/**
* @ignore
*
* @param string $line HTML-escape the value.
* @return string
*/
public function deletedLine( $line ) {
return "<td class='diff-deletedline'><span aria-hidden='true' class='dashicons dashicons-minus'></span><span class='screen-reader-text'>" . __( 'Deleted:' ) . " </span>{$line}</td>";
}
/**
* @ignore
*
* @param string $line HTML-escape the value.
* @return string
*/
public function contextLine( $line ) {
return "<td class='diff-context'><span class='screen-reader-text'>" . __( 'Unchanged:' ) . " </span>{$line}</td>";
}
/**
* @ignore
*
* @return string
*/
public function emptyLine() {
return '<td> </td>';
}
/**
* @ignore
*
* @param array $lines
* @param bool $encode
* @return string
*/
public function _added( $lines, $encode = true ) {
$r = '';
foreach ( $lines as $line ) {
if ( $encode ) {
$processed_line = htmlspecialchars( $line );
/**
* Contextually filters a diffed line.
*
* Filters TextDiff processing of diffed line. By default, diffs are processed with
* htmlspecialchars. Use this filter to remove or change the processing. Passes a context
* indicating if the line is added, deleted or unchanged.
*
* @since 4.1.0
*
* @param string $processed_line The processed diffed line.
* @param string $line The unprocessed diffed line.
* @param string $context The line context. Values are 'added', 'deleted' or 'unchanged'.
*/
$line = apply_filters( 'process_text_diff_html', $processed_line, $line, 'added' );
}
if ( $this->_show_split_view ) {
$r .= '<tr>' . $this->emptyLine() . $this->addedLine( $line ) . "</tr>\n";
} else {
$r .= '<tr>' . $this->addedLine( $line ) . "</tr>\n";
}
}
return $r;
}
/**
* @ignore
*
* @param array $lines
* @param bool $encode
* @return string
*/
public function _deleted( $lines, $encode = true ) {
$r = '';
foreach ( $lines as $line ) {
if ( $encode ) {
$processed_line = htmlspecialchars( $line );
/** This filter is documented in wp-includes/wp-diff.php */
$line = apply_filters( 'process_text_diff_html', $processed_line, $line, 'deleted' );
}
if ( $this->_show_split_view ) {
$r .= '<tr>' . $this->deletedLine( $line ) . $this->emptyLine() . "</tr>\n";
} else {
$r .= '<tr>' . $this->deletedLine( $line ) . "</tr>\n";
}
}
return $r;
}
/**
* @ignore
*
* @param array $lines
* @param bool $encode
* @return string
*/
public function _context( $lines, $encode = true ) {
$r = '';
foreach ( $lines as $line ) {
if ( $encode ) {
$processed_line = htmlspecialchars( $line );
/** This filter is documented in wp-includes/wp-diff.php */
$line = apply_filters( 'process_text_diff_html', $processed_line, $line, 'unchanged' );
}
if ( $this->_show_split_view ) {
$r .= '<tr>' . $this->contextLine( $line ) . $this->contextLine( $line ) . "</tr>\n";
} else {
$r .= '<tr>' . $this->contextLine( $line ) . "</tr>\n";
}
}
return $r;
}
/**
* Process changed lines to do word-by-word diffs for extra highlighting.
*
* (TRAC style) sometimes these lines can actually be deleted or added rows.
* We do additional processing to figure that out
*
* @since 2.6.0
*
* @param array $orig
* @param array $final
* @return string
*/
public function _changed( $orig, $final ) {
$r = '';
/*
* Does the aforementioned additional processing:
* *_matches tell what rows are "the same" in orig and final. Those pairs will be diffed to get word changes.
* - match is numeric: an index in other column.
* - match is 'X': no match. It is a new row.
* *_rows are column vectors for the orig column and the final column.
* - row >= 0: an index of the $orig or $final array.
* - row < 0: a blank row for that column.
*/
list($orig_matches, $final_matches, $orig_rows, $final_rows) = $this->interleave_changed_lines( $orig, $final );
// These will hold the word changes as determined by an inline diff.
$orig_diffs = array();
$final_diffs = array();
// Compute word diffs for each matched pair using the inline diff.
foreach ( $orig_matches as $o => $f ) {
if ( is_numeric( $o ) && is_numeric( $f ) ) {
$text_diff = new Text_Diff( 'auto', array( array( $orig[ $o ] ), array( $final[ $f ] ) ) );
$renderer = new $this->inline_diff_renderer;
$diff = $renderer->render( $text_diff );
// If they're too different, don't include any <ins> or <del>'s.
if ( preg_match_all( '!(<ins>.*?</ins>|<del>.*?</del>)!', $diff, $diff_matches ) ) {
// Length of all text between <ins> or <del>.
$stripped_matches = strlen( strip_tags( implode( ' ', $diff_matches[0] ) ) );
// Since we count length of text between <ins> or <del> (instead of picking just one),
// we double the length of chars not in those tags.
$stripped_diff = strlen( strip_tags( $diff ) ) * 2 - $stripped_matches;
$diff_ratio = $stripped_matches / $stripped_diff;
if ( $diff_ratio > $this->_diff_threshold ) {
continue; // Too different. Don't save diffs.
}
}
// Un-inline the diffs by removing <del> or <ins>.
$orig_diffs[ $o ] = preg_replace( '|<ins>.*?</ins>|', '', $diff );
$final_diffs[ $f ] = preg_replace( '|<del>.*?</del>|', '', $diff );
}
}
foreach ( array_keys( $orig_rows ) as $row ) {
// Both columns have blanks. Ignore them.
if ( $orig_rows[ $row ] < 0 && $final_rows[ $row ] < 0 ) {
continue;
}
// If we have a word based diff, use it. Otherwise, use the normal line.
if ( isset( $orig_diffs[ $orig_rows[ $row ] ] ) ) {
$orig_line = $orig_diffs[ $orig_rows[ $row ] ];
} elseif ( isset( $orig[ $orig_rows[ $row ] ] ) ) {
$orig_line = htmlspecialchars( $orig[ $orig_rows[ $row ] ] );
} else {
$orig_line = '';
}
if ( isset( $final_diffs[ $final_rows[ $row ] ] ) ) {
$final_line = $final_diffs[ $final_rows[ $row ] ];
} elseif ( isset( $final[ $final_rows[ $row ] ] ) ) {
$final_line = htmlspecialchars( $final[ $final_rows[ $row ] ] );
} else {
$final_line = '';
}
if ( $orig_rows[ $row ] < 0 ) { // Orig is blank. This is really an added row.
$r .= $this->_added( array( $final_line ), false );
} elseif ( $final_rows[ $row ] < 0 ) { // Final is blank. This is really a deleted row.
$r .= $this->_deleted( array( $orig_line ), false );
} else { // A true changed row.
if ( $this->_show_split_view ) {
$r .= '<tr>' . $this->deletedLine( $orig_line ) . $this->addedLine( $final_line ) . "</tr>\n";
} else {
$r .= '<tr>' . $this->deletedLine( $orig_line ) . '</tr><tr>' . $this->addedLine( $final_line ) . "</tr>\n";
}
}
}
return $r;
}
/**
* Takes changed blocks and matches which rows in orig turned into which rows in final.
*
* @since 2.6.0
*
* @param array $orig Lines of the original version of the text.
* @param array $final Lines of the final version of the text.
* @return array {
* Array containing results of comparing the original text to the final text.
*
* @type array $orig_matches Associative array of original matches. Index == row
* number of `$orig`, value == corresponding row number
* of that same line in `$final` or 'x' if there is no
* corresponding row (indicating it is a deleted line).
* @type array $final_matches Associative array of final matches. Index == row
* number of `$final`, value == corresponding row number
* of that same line in `$orig` or 'x' if there is no
* corresponding row (indicating it is a new line).
* @type array $orig_rows Associative array of interleaved rows of `$orig` with
* blanks to keep matches aligned with side-by-side diff
* of `$final`. A value >= 0 corresponds to index of `$orig`.
* Value < 0 indicates a blank row.
* @type array $final_rows Associative array of interleaved rows of `$final` with
* blanks to keep matches aligned with side-by-side diff
* of `$orig`. A value >= 0 corresponds to index of `$final`.
* Value < 0 indicates a blank row.
* }
*/
public function interleave_changed_lines( $orig, $final ) {
// Contains all pairwise string comparisons. Keys are such that this need only be a one dimensional array.
$matches = array();
foreach ( array_keys( $orig ) as $o ) {
foreach ( array_keys( $final ) as $f ) {
$matches[ "$o,$f" ] = $this->compute_string_distance( $orig[ $o ], $final[ $f ] );
}
}
asort( $matches ); // Order by string distance.
$orig_matches = array();
$final_matches = array();
foreach ( $matches as $keys => $difference ) {
list($o, $f) = explode( ',', $keys );
$o = (int) $o;
$f = (int) $f;
// Already have better matches for these guys.
if ( isset( $orig_matches[ $o ] ) && isset( $final_matches[ $f ] ) ) {
continue;
}
// First match for these guys. Must be best match.
if ( ! isset( $orig_matches[ $o ] ) && ! isset( $final_matches[ $f ] ) ) {
$orig_matches[ $o ] = $f;
$final_matches[ $f ] = $o;
continue;
}
// Best match of this final is already taken? Must mean this final is a new row.
if ( isset( $orig_matches[ $o ] ) ) {
$final_matches[ $f ] = 'x';
} elseif ( isset( $final_matches[ $f ] ) ) {
// Best match of this orig is already taken? Must mean this orig is a deleted row.
$orig_matches[ $o ] = 'x';
}
}
// We read the text in this order.
ksort( $orig_matches );
ksort( $final_matches );
// Stores rows and blanks for each column.
$orig_rows = array_keys( $orig_matches );
$orig_rows_copy = $orig_rows;
$final_rows = array_keys( $final_matches );
// Interleaves rows with blanks to keep matches aligned.
// We may end up with some extraneous blank rows, but we'll just ignore them later.
foreach ( $orig_rows_copy as $orig_row ) {
$final_pos = array_search( $orig_matches[ $orig_row ], $final_rows, true );
$orig_pos = (int) array_search( $orig_row, $orig_rows, true );
if ( false === $final_pos ) { // This orig is paired with a blank final.
array_splice( $final_rows, $orig_pos, 0, -1 );
} elseif ( $final_pos < $orig_pos ) { // This orig's match is up a ways. Pad final with blank rows.
$diff_array = range( -1, $final_pos - $orig_pos );
array_splice( $final_rows, $orig_pos, 0, $diff_array );
} elseif ( $final_pos > $orig_pos ) { // This orig's match is down a ways. Pad orig with blank rows.
$diff_array = range( -1, $orig_pos - $final_pos );
array_splice( $orig_rows, $orig_pos, 0, $diff_array );
}
}
// Pad the ends with blank rows if the columns aren't the same length.
$diff_count = count( $orig_rows ) - count( $final_rows );
if ( $diff_count < 0 ) {
while ( $diff_count < 0 ) {
array_push( $orig_rows, $diff_count++ );
}
} elseif ( $diff_count > 0 ) {
$diff_count = -1 * $diff_count;
while ( $diff_count < 0 ) {
array_push( $final_rows, $diff_count++ );
}
}
return array( $orig_matches, $final_matches, $orig_rows, $final_rows );
}
/**
* Computes a number that is intended to reflect the "distance" between two strings.
*
* @since 2.6.0
*
* @param string $string1
* @param string $string2
* @return int
*/
public function compute_string_distance( $string1, $string2 ) {
// Use an md5 hash of the strings for a count cache, as it's fast to generate, and collisions aren't a concern.
$count_key1 = md5( $string1 );
$count_key2 = md5( $string2 );
// Cache vectors containing character frequency for all chars in each string.
if ( ! isset( $this->count_cache[ $count_key1 ] ) ) {
$this->count_cache[ $count_key1 ] = count_chars( $string1 );
}
if ( ! isset( $this->count_cache[ $count_key2 ] ) ) {
$this->count_cache[ $count_key2 ] = count_chars( $string2 );
}
$chars1 = $this->count_cache[ $count_key1 ];
$chars2 = $this->count_cache[ $count_key2 ];
$difference_key = md5( implode( ',', $chars1 ) . ':' . implode( ',', $chars2 ) );
if ( ! isset( $this->difference_cache[ $difference_key ] ) ) {
// L1-norm of difference vector.
$this->difference_cache[ $difference_key ] = array_sum( array_map( array( $this, 'difference' ), $chars1, $chars2 ) );
}
$difference = $this->difference_cache[ $difference_key ];
// $string1 has zero length? Odd. Give huge penalty by not dividing.
if ( ! $string1 ) {
return $difference;
}
// Return distance per character (of string1).
return $difference / strlen( $string1 );
}
/**
* @ignore
* @since 2.6.0
*
* @param int $a
* @param int $b
* @return int
*/
public function difference( $a, $b ) {
return abs( $a - $b );
}
/**
* 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 set.
*/
public function __isset( $name ) {
if ( in_array( $name, $this->compat_fields, true ) ) {
return isset( $this->$name );
}
}
/**
* 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 );
}
}
}
```
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress class Requests_Response {} class Requests\_Response {}
===========================
HTTP response class
Contains a response from [Requests::request()](requests/request)
* [\_\_construct](requests_response/__construct) — Constructor
* [is\_redirect](requests_response/is_redirect) — Is the response a redirect?
* [throw\_for\_status](requests_response/throw_for_status) — Throws an exception if the request was not successful
File: `wp-includes/Requests/Response.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/response.php/)
```
class Requests_Response {
/**
* Constructor
*/
public function __construct() {
$this->headers = new Requests_Response_Headers();
$this->cookies = new Requests_Cookie_Jar();
}
/**
* Response body
*
* @var string
*/
public $body = '';
/**
* Raw HTTP data from the transport
*
* @var string
*/
public $raw = '';
/**
* Headers, as an associative array
*
* @var Requests_Response_Headers Array-like object representing headers
*/
public $headers = array();
/**
* Status code, false if non-blocking
*
* @var integer|boolean
*/
public $status_code = false;
/**
* Protocol version, false if non-blocking
*
* @var float|boolean
*/
public $protocol_version = false;
/**
* Whether the request succeeded or not
*
* @var boolean
*/
public $success = false;
/**
* Number of redirects the request used
*
* @var integer
*/
public $redirects = 0;
/**
* URL requested
*
* @var string
*/
public $url = '';
/**
* Previous requests (from redirects)
*
* @var array Array of Requests_Response objects
*/
public $history = array();
/**
* Cookies from the request
*
* @var Requests_Cookie_Jar Array-like object representing a cookie jar
*/
public $cookies = array();
/**
* Is the response a redirect?
*
* @return boolean True if redirect (3xx status), false if not.
*/
public function is_redirect() {
$code = $this->status_code;
return in_array($code, array(300, 301, 302, 303, 307), true) || $code > 307 && $code < 400;
}
/**
* Throws an exception if the request was not successful
*
* @throws Requests_Exception If `$allow_redirects` is false, and code is 3xx (`response.no_redirects`)
* @throws Requests_Exception_HTTP On non-successful status code. Exception class corresponds to code (e.g. {@see Requests_Exception_HTTP_404})
* @param boolean $allow_redirects Set to false to throw on a 3xx as well
*/
public function throw_for_status($allow_redirects = true) {
if ($this->is_redirect()) {
if (!$allow_redirects) {
throw new Requests_Exception('Redirection not allowed', 'response.no_redirects', $this);
}
}
elseif (!$this->success) {
$exception = Requests_Exception_HTTP::get_class($this->status_code);
throw new $exception(null, $this);
}
}
}
```
| programming_docs |
wordpress class WP_Internal_Pointers {} class WP\_Internal\_Pointers {}
===============================
Core class used to implement an internal admin pointers API.
* [dismiss\_pointers\_for\_new\_users](wp_internal_pointers/dismiss_pointers_for_new_users) — Prevents new users from seeing existing 'new feature' pointers.
* [enqueue\_scripts](wp_internal_pointers/enqueue_scripts) — Initializes the new feature pointers.
* [pointer\_wp330\_media\_uploader](wp_internal_pointers/pointer_wp330_media_uploader)
* [pointer\_wp330\_saving\_widgets](wp_internal_pointers/pointer_wp330_saving_widgets)
* [pointer\_wp330\_toolbar](wp_internal_pointers/pointer_wp330_toolbar)
* [pointer\_wp340\_choose\_image\_from\_library](wp_internal_pointers/pointer_wp340_choose_image_from_library)
* [pointer\_wp340\_customize\_current\_theme\_link](wp_internal_pointers/pointer_wp340_customize_current_theme_link)
* [pointer\_wp350\_media](wp_internal_pointers/pointer_wp350_media)
* [pointer\_wp360\_locks](wp_internal_pointers/pointer_wp360_locks)
* [pointer\_wp360\_revisions](wp_internal_pointers/pointer_wp360_revisions)
* [pointer\_wp390\_widgets](wp_internal_pointers/pointer_wp390_widgets)
* [pointer\_wp410\_dfw](wp_internal_pointers/pointer_wp410_dfw)
* [pointer\_wp496\_privacy](wp_internal_pointers/pointer_wp496_privacy)
* [print\_js](wp_internal_pointers/print_js) — Print the pointer JavaScript data.
File: `wp-admin/includes/class-wp-internal-pointers.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-internal-pointers.php/)
```
final class WP_Internal_Pointers {
/**
* Initializes the new feature pointers.
*
* @since 3.3.0
*
* All pointers can be disabled using the following:
* remove_action( 'admin_enqueue_scripts', array( 'WP_Internal_Pointers', 'enqueue_scripts' ) );
*
* Individual pointers (e.g. wp390_widgets) can be disabled using the following:
*
* function yourprefix_remove_pointers() {
* remove_action(
* 'admin_print_footer_scripts',
* array( 'WP_Internal_Pointers', 'pointer_wp390_widgets' )
* );
* }
* add_action( 'admin_enqueue_scripts', 'yourprefix_remove_pointers', 11 );
*
* @param string $hook_suffix The current admin page.
*/
public static function enqueue_scripts( $hook_suffix ) {
/*
* Register feature pointers
*
* Format:
* array(
* hook_suffix => pointer callback
* )
*
* Example:
* array(
* 'themes.php' => 'wp390_widgets'
* )
*/
$registered_pointers = array(
// None currently.
);
// Check if screen related pointer is registered.
if ( empty( $registered_pointers[ $hook_suffix ] ) ) {
return;
}
$pointers = (array) $registered_pointers[ $hook_suffix ];
/*
* Specify required capabilities for feature pointers
*
* Format:
* array(
* pointer callback => Array of required capabilities
* )
*
* Example:
* array(
* 'wp390_widgets' => array( 'edit_theme_options' )
* )
*/
$caps_required = array(
// None currently.
);
// Get dismissed pointers.
$dismissed = explode( ',', (string) get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) );
$got_pointers = false;
foreach ( array_diff( $pointers, $dismissed ) as $pointer ) {
if ( isset( $caps_required[ $pointer ] ) ) {
foreach ( $caps_required[ $pointer ] as $cap ) {
if ( ! current_user_can( $cap ) ) {
continue 2;
}
}
}
// Bind pointer print function.
add_action( 'admin_print_footer_scripts', array( 'WP_Internal_Pointers', 'pointer_' . $pointer ) );
$got_pointers = true;
}
if ( ! $got_pointers ) {
return;
}
// Add pointers script and style to queue.
wp_enqueue_style( 'wp-pointer' );
wp_enqueue_script( 'wp-pointer' );
}
/**
* Print the pointer JavaScript data.
*
* @since 3.3.0
*
* @param string $pointer_id The pointer ID.
* @param string $selector The HTML elements, on which the pointer should be attached.
* @param array $args Arguments to be passed to the pointer JS (see wp-pointer.js).
*/
private static function print_js( $pointer_id, $selector, $args ) {
if ( empty( $pointer_id ) || empty( $selector ) || empty( $args ) || empty( $args['content'] ) ) {
return;
}
?>
<script type="text/javascript">
(function($){
var options = <?php echo wp_json_encode( $args ); ?>, setup;
if ( ! options )
return;
options = $.extend( options, {
close: function() {
$.post( ajaxurl, {
pointer: '<?php echo $pointer_id; ?>',
action: 'dismiss-wp-pointer'
});
}
});
setup = function() {
$('<?php echo $selector; ?>').first().pointer( options ).pointer('open');
};
if ( options.position && options.position.defer_loading )
$(window).bind( 'load.wp-pointers', setup );
else
$( function() {
setup();
} );
})( jQuery );
</script>
<?php
}
public static function pointer_wp330_toolbar() {}
public static function pointer_wp330_media_uploader() {}
public static function pointer_wp330_saving_widgets() {}
public static function pointer_wp340_customize_current_theme_link() {}
public static function pointer_wp340_choose_image_from_library() {}
public static function pointer_wp350_media() {}
public static function pointer_wp360_revisions() {}
public static function pointer_wp360_locks() {}
public static function pointer_wp390_widgets() {}
public static function pointer_wp410_dfw() {}
public static function pointer_wp496_privacy() {}
/**
* Prevents new users from seeing existing 'new feature' pointers.
*
* @since 3.3.0
*
* @param int $user_id User ID.
*/
public static function dismiss_pointers_for_new_users( $user_id ) {
add_user_meta( $user_id, 'dismissed_wp_pointers', '' );
}
}
```
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress class WP_Comments_List_Table {} class WP\_Comments\_List\_Table {}
==================================
Core class used to implement displaying comments in a list table.
* [WP\_List\_Table](wp_list_table)
* [\_\_construct](wp_comments_list_table/__construct) — Constructor.
* [ajax\_user\_can](wp_comments_list_table/ajax_user_can)
* [column\_author](wp_comments_list_table/column_author)
* [column\_cb](wp_comments_list_table/column_cb)
* [column\_comment](wp_comments_list_table/column_comment)
* [column\_date](wp_comments_list_table/column_date)
* [column\_default](wp_comments_list_table/column_default)
* [column\_response](wp_comments_list_table/column_response)
* [comment\_status\_dropdown](wp_comments_list_table/comment_status_dropdown) — Displays a comment status drop-down for filtering on the Comments list table.
* [comment\_type\_dropdown](wp_comments_list_table/comment_type_dropdown) — Displays a comment type drop-down for filtering on the Comments list table.
* [current\_action](wp_comments_list_table/current_action)
* [display](wp_comments_list_table/display) — Displays the comments table.
* [extra\_tablenav](wp_comments_list_table/extra_tablenav)
* [floated\_admin\_avatar](wp_comments_list_table/floated_admin_avatar) — Adds avatars to comment author names.
* [get\_bulk\_actions](wp_comments_list_table/get_bulk_actions)
* [get\_columns](wp_comments_list_table/get_columns)
* [get\_default\_primary\_column\_name](wp_comments_list_table/get_default_primary_column_name) — Gets the name of the default primary column.
* [get\_per\_page](wp_comments_list_table/get_per_page)
* [get\_sortable\_columns](wp_comments_list_table/get_sortable_columns)
* [get\_views](wp_comments_list_table/get_views)
* [handle\_row\_actions](wp_comments_list_table/handle_row_actions) — Generates and displays row actions links.
* [no\_items](wp_comments_list_table/no_items)
* [prepare\_items](wp_comments_list_table/prepare_items)
* [single\_row](wp_comments_list_table/single_row)
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
class WP_Comments_List_Table extends WP_List_Table {
public $checkbox = true;
public $pending_count = array();
public $extra_items;
private $user_can;
/**
* Constructor.
*
* @since 3.1.0
*
* @see WP_List_Table::__construct() for more information on default arguments.
*
* @global int $post_id
*
* @param array $args An associative array of arguments.
*/
public function __construct( $args = array() ) {
global $post_id;
$post_id = isset( $_REQUEST['p'] ) ? absint( $_REQUEST['p'] ) : 0;
if ( get_option( 'show_avatars' ) ) {
add_filter( 'comment_author', array( $this, 'floated_admin_avatar' ), 10, 2 );
}
parent::__construct(
array(
'plural' => 'comments',
'singular' => 'comment',
'ajax' => true,
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
}
/**
* Adds avatars to comment author names.
*
* @since 3.1.0
*
* @param string $name Comment author name.
* @param int $comment_id Comment ID.
* @return string Avatar with the user name.
*/
public function floated_admin_avatar( $name, $comment_id ) {
$comment = get_comment( $comment_id );
$avatar = get_avatar( $comment, 32, 'mystery' );
return "$avatar $name";
}
/**
* @return bool
*/
public function ajax_user_can() {
return current_user_can( 'edit_posts' );
}
/**
* @global string $mode List table view mode.
* @global int $post_id
* @global string $comment_status
* @global string $comment_type
* @global string $search
*/
public function prepare_items() {
global $mode, $post_id, $comment_status, $comment_type, $search;
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' );
}
$comment_status = isset( $_REQUEST['comment_status'] ) ? $_REQUEST['comment_status'] : 'all';
if ( ! in_array( $comment_status, array( 'all', 'mine', 'moderated', 'approved', 'spam', 'trash' ), true ) ) {
$comment_status = 'all';
}
$comment_type = ! empty( $_REQUEST['comment_type'] ) ? $_REQUEST['comment_type'] : '';
$search = ( isset( $_REQUEST['s'] ) ) ? $_REQUEST['s'] : '';
$post_type = ( isset( $_REQUEST['post_type'] ) ) ? sanitize_key( $_REQUEST['post_type'] ) : '';
$user_id = ( isset( $_REQUEST['user_id'] ) ) ? $_REQUEST['user_id'] : '';
$orderby = ( isset( $_REQUEST['orderby'] ) ) ? $_REQUEST['orderby'] : '';
$order = ( isset( $_REQUEST['order'] ) ) ? $_REQUEST['order'] : '';
$comments_per_page = $this->get_per_page( $comment_status );
$doing_ajax = wp_doing_ajax();
if ( isset( $_REQUEST['number'] ) ) {
$number = (int) $_REQUEST['number'];
} else {
$number = $comments_per_page + min( 8, $comments_per_page ); // Grab a few extra.
}
$page = $this->get_pagenum();
if ( isset( $_REQUEST['start'] ) ) {
$start = $_REQUEST['start'];
} else {
$start = ( $page - 1 ) * $comments_per_page;
}
if ( $doing_ajax && isset( $_REQUEST['offset'] ) ) {
$start += $_REQUEST['offset'];
}
$status_map = array(
'mine' => '',
'moderated' => 'hold',
'approved' => 'approve',
'all' => '',
);
$args = array(
'status' => isset( $status_map[ $comment_status ] ) ? $status_map[ $comment_status ] : $comment_status,
'search' => $search,
'user_id' => $user_id,
'offset' => $start,
'number' => $number,
'post_id' => $post_id,
'type' => $comment_type,
'orderby' => $orderby,
'order' => $order,
'post_type' => $post_type,
);
/**
* Filters the arguments for the comment query in the comments list table.
*
* @since 5.1.0
*
* @param array $args An array of get_comments() arguments.
*/
$args = apply_filters( 'comments_list_table_query_args', $args );
$_comments = get_comments( $args );
if ( is_array( $_comments ) ) {
update_comment_cache( $_comments );
$this->items = array_slice( $_comments, 0, $comments_per_page );
$this->extra_items = array_slice( $_comments, $comments_per_page );
$_comment_post_ids = array_unique( wp_list_pluck( $_comments, 'comment_post_ID' ) );
$this->pending_count = get_pending_comments_num( $_comment_post_ids );
}
$total_comments = get_comments(
array_merge(
$args,
array(
'count' => true,
'offset' => 0,
'number' => 0,
)
)
);
$this->set_pagination_args(
array(
'total_items' => $total_comments,
'per_page' => $comments_per_page,
)
);
}
/**
* @param string $comment_status
* @return int
*/
public function get_per_page( $comment_status = 'all' ) {
$comments_per_page = $this->get_items_per_page( 'edit_comments_per_page' );
/**
* Filters the number of comments listed per page in the comments list table.
*
* @since 2.6.0
*
* @param int $comments_per_page The number of comments to list per page.
* @param string $comment_status The comment status name. Default 'All'.
*/
return apply_filters( 'comments_per_page', $comments_per_page, $comment_status );
}
/**
* @global string $comment_status
*/
public function no_items() {
global $comment_status;
if ( 'moderated' === $comment_status ) {
_e( 'No comments awaiting moderation.' );
} elseif ( 'trash' === $comment_status ) {
_e( 'No comments found in Trash.' );
} else {
_e( 'No comments found.' );
}
}
/**
* @global int $post_id
* @global string $comment_status
* @global string $comment_type
*/
protected function get_views() {
global $post_id, $comment_status, $comment_type;
$status_links = array();
$num_comments = ( $post_id ) ? wp_count_comments( $post_id ) : wp_count_comments();
$stati = array(
/* translators: %s: Number of comments. */
'all' => _nx_noop(
'All <span class="count">(%s)</span>',
'All <span class="count">(%s)</span>',
'comments'
), // Singular not used.
/* translators: %s: Number of comments. */
'mine' => _nx_noop(
'Mine <span class="count">(%s)</span>',
'Mine <span class="count">(%s)</span>',
'comments'
),
/* translators: %s: Number of comments. */
'moderated' => _nx_noop(
'Pending <span class="count">(%s)</span>',
'Pending <span class="count">(%s)</span>',
'comments'
),
/* translators: %s: Number of comments. */
'approved' => _nx_noop(
'Approved <span class="count">(%s)</span>',
'Approved <span class="count">(%s)</span>',
'comments'
),
/* translators: %s: Number of comments. */
'spam' => _nx_noop(
'Spam <span class="count">(%s)</span>',
'Spam <span class="count">(%s)</span>',
'comments'
),
/* translators: %s: Number of comments. */
'trash' => _nx_noop(
'Trash <span class="count">(%s)</span>',
'Trash <span class="count">(%s)</span>',
'comments'
),
);
if ( ! EMPTY_TRASH_DAYS ) {
unset( $stati['trash'] );
}
$link = admin_url( 'edit-comments.php' );
if ( ! empty( $comment_type ) && 'all' !== $comment_type ) {
$link = add_query_arg( 'comment_type', $comment_type, $link );
}
foreach ( $stati as $status => $label ) {
if ( 'mine' === $status ) {
$current_user_id = get_current_user_id();
$num_comments->mine = get_comments(
array(
'post_id' => $post_id ? $post_id : 0,
'user_id' => $current_user_id,
'count' => true,
)
);
$link = add_query_arg( 'user_id', $current_user_id, $link );
} else {
$link = remove_query_arg( 'user_id', $link );
}
if ( ! isset( $num_comments->$status ) ) {
$num_comments->$status = 10;
}
$link = add_query_arg( 'comment_status', $status, $link );
if ( $post_id ) {
$link = add_query_arg( 'p', absint( $post_id ), $link );
}
/*
// I toyed with this, but decided against it. Leaving it in here in case anyone thinks it is a good idea. ~ Mark
if ( !empty( $_REQUEST['s'] ) )
$link = add_query_arg( 's', esc_attr( wp_unslash( $_REQUEST['s'] ) ), $link );
*/
$status_links[ $status ] = array(
'url' => esc_url( $link ),
'label' => sprintf(
translate_nooped_plural( $label, $num_comments->$status ),
sprintf(
'<span class="%s-count">%s</span>',
( 'moderated' === $status ) ? 'pending' : $status,
number_format_i18n( $num_comments->$status )
)
),
'current' => $status === $comment_status,
);
}
/**
* Filters the comment status links.
*
* @since 2.5.0
* @since 5.1.0 The 'Mine' link was added.
*
* @param string[] $status_links An associative array of fully-formed comment status links. Includes 'All', 'Mine',
* 'Pending', 'Approved', 'Spam', and 'Trash'.
*/
return apply_filters( 'comment_status_links', $this->get_views_links( $status_links ) );
}
/**
* @global string $comment_status
*
* @return array
*/
protected function get_bulk_actions() {
global $comment_status;
$actions = array();
if ( in_array( $comment_status, array( 'all', 'approved' ), true ) ) {
$actions['unapprove'] = __( 'Unapprove' );
}
if ( in_array( $comment_status, array( 'all', 'moderated' ), true ) ) {
$actions['approve'] = __( 'Approve' );
}
if ( in_array( $comment_status, array( 'all', 'moderated', 'approved', 'trash' ), true ) ) {
$actions['spam'] = _x( 'Mark as spam', 'comment' );
}
if ( 'trash' === $comment_status ) {
$actions['untrash'] = __( 'Restore' );
} elseif ( 'spam' === $comment_status ) {
$actions['unspam'] = _x( 'Not spam', 'comment' );
}
if ( in_array( $comment_status, array( 'trash', 'spam' ), true ) || ! EMPTY_TRASH_DAYS ) {
$actions['delete'] = __( 'Delete permanently' );
} else {
$actions['trash'] = __( 'Move to Trash' );
}
return $actions;
}
/**
* @global string $comment_status
* @global string $comment_type
*
* @param string $which
*/
protected function extra_tablenav( $which ) {
global $comment_status, $comment_type;
static $has_items;
if ( ! isset( $has_items ) ) {
$has_items = $this->has_items();
}
echo '<div class="alignleft actions">';
if ( 'top' === $which ) {
ob_start();
$this->comment_type_dropdown( $comment_type );
/**
* Fires just before the Filter submit button for comment types.
*
* @since 3.5.0
*/
do_action( 'restrict_manage_comments' );
$output = ob_get_clean();
if ( ! empty( $output ) && $this->has_items() ) {
echo $output;
submit_button( __( 'Filter' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) );
}
}
if ( ( 'spam' === $comment_status || 'trash' === $comment_status ) && $has_items
&& current_user_can( 'moderate_comments' )
) {
wp_nonce_field( 'bulk-destroy', '_destroy_nonce' );
$title = ( 'spam' === $comment_status ) ? esc_attr__( 'Empty Spam' ) : esc_attr__( 'Empty Trash' );
submit_button( $title, 'apply', 'delete_all', false );
}
/**
* Fires after the Filter submit button for comment types.
*
* @since 2.5.0
* @since 5.6.0 The `$which` parameter was added.
*
* @param string $comment_status The comment status name. Default 'All'.
* @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
*/
do_action( 'manage_comments_nav', $comment_status, $which );
echo '</div>';
}
/**
* @return string|false
*/
public function current_action() {
if ( isset( $_REQUEST['delete_all'] ) || isset( $_REQUEST['delete_all2'] ) ) {
return 'delete_all';
}
return parent::current_action();
}
/**
* @global int $post_id
*
* @return array
*/
public function get_columns() {
global $post_id;
$columns = array();
if ( $this->checkbox ) {
$columns['cb'] = '<input type="checkbox" />';
}
$columns['author'] = __( 'Author' );
$columns['comment'] = _x( 'Comment', 'column name' );
if ( ! $post_id ) {
/* translators: Column name or table row header. */
$columns['response'] = __( 'In response to' );
}
$columns['date'] = _x( 'Submitted on', 'column name' );
return $columns;
}
/**
* Displays a comment type drop-down for filtering on the Comments list table.
*
* @since 5.5.0
* @since 5.6.0 Renamed from `comment_status_dropdown()` to `comment_type_dropdown()`.
*
* @param string $comment_type The current comment type slug.
*/
protected function comment_type_dropdown( $comment_type ) {
/**
* Filters the comment types shown in the drop-down menu on the Comments list table.
*
* @since 2.7.0
*
* @param string[] $comment_types Array of comment type labels keyed by their name.
*/
$comment_types = apply_filters(
'admin_comment_types_dropdown',
array(
'comment' => __( 'Comments' ),
'pings' => __( 'Pings' ),
)
);
if ( $comment_types && is_array( $comment_types ) ) {
printf( '<label class="screen-reader-text" for="filter-by-comment-type">%s</label>', __( 'Filter by comment type' ) );
echo '<select id="filter-by-comment-type" name="comment_type">';
printf( "\t<option value=''>%s</option>", __( 'All comment types' ) );
foreach ( $comment_types as $type => $label ) {
if ( get_comments(
array(
'number' => 1,
'type' => $type,
)
) ) {
printf(
"\t<option value='%s'%s>%s</option>\n",
esc_attr( $type ),
selected( $comment_type, $type, false ),
esc_html( $label )
);
}
}
echo '</select>';
}
}
/**
* @return array
*/
protected function get_sortable_columns() {
return array(
'author' => 'comment_author',
'response' => 'comment_post_ID',
'date' => 'comment_date',
);
}
/**
* Gets the name of the default primary column.
*
* @since 4.3.0
*
* @return string Name of the default primary column, in this case, 'comment'.
*/
protected function get_default_primary_column_name() {
return 'comment';
}
/**
* Displays the comments table.
*
* Overrides the parent display() method to render extra comments.
*
* @since 3.1.0
*/
public function display() {
wp_nonce_field( 'fetch-list-' . get_class( $this ), '_ajax_fetch_list_nonce' );
static $has_items;
if ( ! isset( $has_items ) ) {
$has_items = $this->has_items();
if ( $has_items ) {
$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-comment-list" data-wp-lists="list:comment">
<?php $this->display_rows_or_placeholder(); ?>
</tbody>
<tbody id="the-extra-comment-list" data-wp-lists="list:comment" style="display: none;">
<?php
/*
* Back up the items to restore after printing the extra items markup.
* The extra items may be empty, which will prevent the table nav from displaying later.
*/
$items = $this->items;
$this->items = $this->extra_items;
$this->display_rows_or_placeholder();
$this->items = $items;
?>
</tbody>
<tfoot>
<tr>
<?php $this->print_column_headers( false ); ?>
</tr>
</tfoot>
</table>
<?php
$this->display_tablenav( 'bottom' );
}
/**
* @global WP_Post $post Global post object.
* @global WP_Comment $comment Global comment object.
*
* @param WP_Comment $item
*/
public function single_row( $item ) {
global $post, $comment;
$comment = $item;
$the_comment_class = wp_get_comment_status( $comment );
if ( ! $the_comment_class ) {
$the_comment_class = '';
}
$the_comment_class = implode( ' ', get_comment_class( $the_comment_class, $comment, $comment->comment_post_ID ) );
if ( $comment->comment_post_ID > 0 ) {
$post = get_post( $comment->comment_post_ID );
}
$this->user_can = current_user_can( 'edit_comment', $comment->comment_ID );
echo "<tr id='comment-$comment->comment_ID' class='$the_comment_class'>";
$this->single_row_columns( $comment );
echo "</tr>\n";
unset( $GLOBALS['post'], $GLOBALS['comment'] );
}
/**
* Generates and displays row actions links.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$comment` to `$item` to match parent class for PHP 8 named parameter support.
*
* @global string $comment_status Status for the current listed comments.
*
* @param WP_Comment $item The comment object.
* @param string $column_name Current column name.
* @param string $primary Primary column name.
* @return string Row actions output for comments. An empty string
* if the current column is not the primary column,
* or if the current user cannot edit the comment.
*/
protected function handle_row_actions( $item, $column_name, $primary ) {
global $comment_status;
if ( $primary !== $column_name ) {
return '';
}
if ( ! $this->user_can ) {
return '';
}
// Restores the more descriptive, specific name for use within this method.
$comment = $item;
$the_comment_status = wp_get_comment_status( $comment );
$output = '';
$del_nonce = esc_html( '_wpnonce=' . wp_create_nonce( "delete-comment_$comment->comment_ID" ) );
$approve_nonce = esc_html( '_wpnonce=' . wp_create_nonce( "approve-comment_$comment->comment_ID" ) );
$url = "comment.php?c=$comment->comment_ID";
$approve_url = esc_url( $url . "&action=approvecomment&$approve_nonce" );
$unapprove_url = esc_url( $url . "&action=unapprovecomment&$approve_nonce" );
$spam_url = esc_url( $url . "&action=spamcomment&$del_nonce" );
$unspam_url = esc_url( $url . "&action=unspamcomment&$del_nonce" );
$trash_url = esc_url( $url . "&action=trashcomment&$del_nonce" );
$untrash_url = esc_url( $url . "&action=untrashcomment&$del_nonce" );
$delete_url = esc_url( $url . "&action=deletecomment&$del_nonce" );
// Preorder it: Approve | Reply | Quick Edit | Edit | Spam | Trash.
$actions = array(
'approve' => '',
'unapprove' => '',
'reply' => '',
'quickedit' => '',
'edit' => '',
'spam' => '',
'unspam' => '',
'trash' => '',
'untrash' => '',
'delete' => '',
);
// Not looking at all comments.
if ( $comment_status && 'all' !== $comment_status ) {
if ( 'approved' === $the_comment_status ) {
$actions['unapprove'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="vim-u vim-destructive aria-button-if-js" aria-label="%s">%s</a>',
$unapprove_url,
"delete:the-comment-list:comment-{$comment->comment_ID}:e7e7d3:action=dim-comment&new=unapproved",
esc_attr__( 'Unapprove this comment' ),
__( 'Unapprove' )
);
} elseif ( 'unapproved' === $the_comment_status ) {
$actions['approve'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="vim-a vim-destructive aria-button-if-js" aria-label="%s">%s</a>',
$approve_url,
"delete:the-comment-list:comment-{$comment->comment_ID}:e7e7d3:action=dim-comment&new=approved",
esc_attr__( 'Approve this comment' ),
__( 'Approve' )
);
}
} else {
$actions['approve'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="vim-a aria-button-if-js" aria-label="%s">%s</a>',
$approve_url,
"dim:the-comment-list:comment-{$comment->comment_ID}:unapproved:e7e7d3:e7e7d3:new=approved",
esc_attr__( 'Approve this comment' ),
__( 'Approve' )
);
$actions['unapprove'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="vim-u aria-button-if-js" aria-label="%s">%s</a>',
$unapprove_url,
"dim:the-comment-list:comment-{$comment->comment_ID}:unapproved:e7e7d3:e7e7d3:new=unapproved",
esc_attr__( 'Unapprove this comment' ),
__( 'Unapprove' )
);
}
if ( 'spam' !== $the_comment_status ) {
$actions['spam'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="vim-s vim-destructive aria-button-if-js" aria-label="%s">%s</a>',
$spam_url,
"delete:the-comment-list:comment-{$comment->comment_ID}::spam=1",
esc_attr__( 'Mark this comment as spam' ),
/* translators: "Mark as spam" link. */
_x( 'Spam', 'verb' )
);
} elseif ( 'spam' === $the_comment_status ) {
$actions['unspam'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="vim-z vim-destructive aria-button-if-js" aria-label="%s">%s</a>',
$unspam_url,
"delete:the-comment-list:comment-{$comment->comment_ID}:66cc66:unspam=1",
esc_attr__( 'Restore this comment from the spam' ),
_x( 'Not Spam', 'comment' )
);
}
if ( 'trash' === $the_comment_status ) {
$actions['untrash'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="vim-z vim-destructive aria-button-if-js" aria-label="%s">%s</a>',
$untrash_url,
"delete:the-comment-list:comment-{$comment->comment_ID}:66cc66:untrash=1",
esc_attr__( 'Restore this comment from the Trash' ),
__( 'Restore' )
);
}
if ( 'spam' === $the_comment_status || 'trash' === $the_comment_status || ! EMPTY_TRASH_DAYS ) {
$actions['delete'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="delete vim-d vim-destructive aria-button-if-js" aria-label="%s">%s</a>',
$delete_url,
"delete:the-comment-list:comment-{$comment->comment_ID}::delete=1",
esc_attr__( 'Delete this comment permanently' ),
__( 'Delete Permanently' )
);
} else {
$actions['trash'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="delete vim-d vim-destructive aria-button-if-js" aria-label="%s">%s</a>',
$trash_url,
"delete:the-comment-list:comment-{$comment->comment_ID}::trash=1",
esc_attr__( 'Move this comment to the Trash' ),
_x( 'Trash', 'verb' )
);
}
if ( 'spam' !== $the_comment_status && 'trash' !== $the_comment_status ) {
$actions['edit'] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
"comment.php?action=editcomment&c={$comment->comment_ID}",
esc_attr__( 'Edit this comment' ),
__( 'Edit' )
);
$format = '<button type="button" data-comment-id="%d" data-post-id="%d" data-action="%s" class="%s button-link" aria-expanded="false" aria-label="%s">%s</button>';
$actions['quickedit'] = sprintf(
$format,
$comment->comment_ID,
$comment->comment_post_ID,
'edit',
'vim-q comment-inline',
esc_attr__( 'Quick edit this comment inline' ),
__( 'Quick Edit' )
);
$actions['reply'] = sprintf(
$format,
$comment->comment_ID,
$comment->comment_post_ID,
'replyto',
'vim-r comment-inline',
esc_attr__( 'Reply to this comment' ),
__( 'Reply' )
);
}
/** This filter is documented in wp-admin/includes/dashboard.php */
$actions = apply_filters( 'comment_row_actions', array_filter( $actions ), $comment );
$always_visible = false;
$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;
if ( ( ( 'approve' === $action || 'unapprove' === $action ) && 2 === $i )
|| 1 === $i
) {
$separator = '';
} else {
$separator = ' | ';
}
// Reply and quickedit need a hide-if-no-js span when not added with Ajax.
if ( ( 'reply' === $action || 'quickedit' === $action ) && ! wp_doing_ajax() ) {
$action .= ' hide-if-no-js';
} elseif ( ( 'untrash' === $action && 'trash' === $the_comment_status )
|| ( 'unspam' === $action && 'spam' === $the_comment_status )
) {
if ( '1' === get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true ) ) {
$action .= ' approve';
} else {
$action .= ' unapprove';
}
}
$output .= "<span class='$action'>{$separator}{$link}</span>";
}
$output .= '</div>';
$output .= '<button type="button" class="toggle-row"><span class="screen-reader-text">' . __( 'Show more details' ) . '</span></button>';
return $output;
}
/**
* @since 5.9.0 Renamed `$comment` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Comment $item The comment object.
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$comment = $item;
if ( $this->user_can ) {
?>
<label class="screen-reader-text" for="cb-select-<?php echo $comment->comment_ID; ?>"><?php _e( 'Select comment' ); ?></label>
<input id="cb-select-<?php echo $comment->comment_ID; ?>" type="checkbox" name="delete_comments[]" value="<?php echo $comment->comment_ID; ?>" />
<?php
}
}
/**
* @param WP_Comment $comment The comment object.
*/
public function column_comment( $comment ) {
echo '<div class="comment-author">';
$this->column_author( $comment );
echo '</div>';
if ( $comment->comment_parent ) {
$parent = get_comment( $comment->comment_parent );
if ( $parent ) {
$parent_link = esc_url( get_comment_link( $parent ) );
$name = get_comment_author( $parent );
printf(
/* translators: %s: Comment link. */
__( 'In reply to %s.' ),
'<a href="' . $parent_link . '">' . $name . '</a>'
);
}
}
comment_text( $comment );
if ( $this->user_can ) {
/** This filter is documented in wp-admin/includes/comment.php */
$comment_content = apply_filters( 'comment_edit_pre', $comment->comment_content );
?>
<div id="inline-<?php echo $comment->comment_ID; ?>" class="hidden">
<textarea class="comment" rows="1" cols="1"><?php echo esc_textarea( $comment_content ); ?></textarea>
<div class="author-email"><?php echo esc_html( $comment->comment_author_email ); ?></div>
<div class="author"><?php echo esc_html( $comment->comment_author ); ?></div>
<div class="author-url"><?php echo esc_url( $comment->comment_author_url ); ?></div>
<div class="comment_status"><?php echo $comment->comment_approved; ?></div>
</div>
<?php
}
}
/**
* @global string $comment_status
*
* @param WP_Comment $comment The comment object.
*/
public function column_author( $comment ) {
global $comment_status;
$author_url = get_comment_author_url( $comment );
$author_url_display = untrailingslashit( preg_replace( '|^http(s)?://(www\.)?|i', '', $author_url ) );
if ( strlen( $author_url_display ) > 50 ) {
$author_url_display = wp_html_excerpt( $author_url_display, 49, '…' );
}
echo '<strong>';
comment_author( $comment );
echo '</strong><br />';
if ( ! empty( $author_url_display ) ) {
// Print link to author URL, and disallow referrer information (without using target="_blank").
printf(
'<a href="%s" rel="noopener noreferrer">%s</a><br />',
esc_url( $author_url ),
esc_html( $author_url_display )
);
}
if ( $this->user_can ) {
if ( ! empty( $comment->comment_author_email ) ) {
/** This filter is documented in wp-includes/comment-template.php */
$email = apply_filters( 'comment_email', $comment->comment_author_email, $comment );
if ( ! empty( $email ) && '@' !== $email ) {
printf( '<a href="%1$s">%2$s</a><br />', esc_url( 'mailto:' . $email ), esc_html( $email ) );
}
}
$author_ip = get_comment_author_IP( $comment );
if ( $author_ip ) {
$author_ip_url = add_query_arg(
array(
's' => $author_ip,
'mode' => 'detail',
),
admin_url( 'edit-comments.php' )
);
if ( 'spam' === $comment_status ) {
$author_ip_url = add_query_arg( 'comment_status', 'spam', $author_ip_url );
}
printf( '<a href="%1$s">%2$s</a>', esc_url( $author_ip_url ), esc_html( $author_ip ) );
}
}
}
/**
* @param WP_Comment $comment The comment object.
*/
public function column_date( $comment ) {
$submitted = sprintf(
/* translators: 1: Comment date, 2: Comment time. */
__( '%1$s at %2$s' ),
/* translators: Comment date format. See https://www.php.net/manual/datetime.format.php */
get_comment_date( __( 'Y/m/d' ), $comment ),
/* translators: Comment time format. See https://www.php.net/manual/datetime.format.php */
get_comment_date( __( 'g:i a' ), $comment )
);
echo '<div class="submitted-on">';
if ( 'approved' === wp_get_comment_status( $comment ) && ! empty( $comment->comment_post_ID ) ) {
printf(
'<a href="%s">%s</a>',
esc_url( get_comment_link( $comment ) ),
$submitted
);
} else {
echo $submitted;
}
echo '</div>';
}
/**
* @param WP_Comment $comment The comment object.
*/
public function column_response( $comment ) {
$post = get_post();
if ( ! $post ) {
return;
}
if ( isset( $this->pending_count[ $post->ID ] ) ) {
$pending_comments = $this->pending_count[ $post->ID ];
} else {
$_pending_count_temp = get_pending_comments_num( array( $post->ID ) );
$pending_comments = $_pending_count_temp[ $post->ID ];
$this->pending_count[ $post->ID ] = $pending_comments;
}
if ( current_user_can( 'edit_post', $post->ID ) ) {
$post_link = "<a href='" . get_edit_post_link( $post->ID ) . "' class='comments-edit-item-link'>";
$post_link .= esc_html( get_the_title( $post->ID ) ) . '</a>';
} else {
$post_link = esc_html( get_the_title( $post->ID ) );
}
echo '<div class="response-links">';
if ( 'attachment' === $post->post_type ) {
$thumb = wp_get_attachment_image( $post->ID, array( 80, 60 ), true );
if ( $thumb ) {
echo $thumb;
}
}
echo $post_link;
$post_type_object = get_post_type_object( $post->post_type );
echo "<a href='" . get_permalink( $post->ID ) . "' class='comments-view-item-link'>" . $post_type_object->labels->view_item . '</a>';
echo '<span class="post-com-count-wrapper post-com-count-', $post->ID, '">';
$this->comments_bubble( $post->ID, $pending_comments );
echo '</span> ';
echo '</div>';
}
/**
* @since 5.9.0 Renamed `$comment` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Comment $item The comment object.
* @param string $column_name The custom column's name.
*/
public function column_default( $item, $column_name ) {
/**
* Fires when the default column output is displayed for a single row.
*
* @since 2.8.0
*
* @param string $column_name The custom column's name.
* @param string $comment_id The comment ID as a numeric string.
*/
do_action( 'manage_comments_custom_column', $column_name, $item->comment_ID );
}
}
```
| 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\_Post\_Comments\_List\_Table](wp_post_comments_list_table) wp-admin/includes/class-wp-post-comments-list-table.php | Core class used to implement displaying post comments in a list table. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
| programming_docs |
wordpress class WP_Customize_New_Menu_Section {} class WP\_Customize\_New\_Menu\_Section {}
==========================================
This class has been deprecated. Use [WP\_Customize\_Section](wp_customize_section) instead.
Customize Menu Section Class
* [WP\_Customize\_Section](wp_customize_section)
* [\_\_construct](wp_customize_new_menu_section/__construct) — Constructor. — deprecated
* [render](wp_customize_new_menu_section/render) — Render the section, and the controls that have been added to it. — deprecated
File: `wp-includes/customize/class-wp-customize-new-menu-section.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-new-menu-section.php/)
```
class WP_Customize_New_Menu_Section extends WP_Customize_Section {
/**
* Control type.
*
* @since 4.3.0
* @var string
*/
public $type = 'new_menu';
/**
* Constructor.
*
* Any supplied $args override class property defaults.
*
* @since 4.9.0
* @deprecated 4.9.0
*
* @param WP_Customize_Manager $manager Customizer bootstrap instance.
* @param string $id A specific ID of the section.
* @param array $args Section arguments.
*/
public function __construct( WP_Customize_Manager $manager, $id, array $args = array() ) {
_deprecated_function( __METHOD__, '4.9.0' );
parent::__construct( $manager, $id, $args );
}
/**
* Render the section, and the controls that have been added to it.
*
* @since 4.3.0
* @deprecated 4.9.0
*/
protected function render() {
_deprecated_function( __METHOD__, '4.9.0' );
?>
<li id="accordion-section-<?php echo esc_attr( $this->id ); ?>" class="accordion-section-new-menu">
<button type="button" class="button add-new-menu-item add-menu-toggle" aria-expanded="false">
<?php echo esc_html( $this->title ); ?>
</button>
<ul class="new-menu-section-content"></ul>
</li>
<?php
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Section](wp_customize_section) wp-includes/class-wp-customize-section.php | Customize Section 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 Language_Pack_Upgrader {} class Language\_Pack\_Upgrader {}
=================================
Core class used for updating/installing language packs (translations) for plugins, themes, and core.
* [WP\_Upgrader](wp_upgrader)
* [async\_upgrade](language_pack_upgrader/async_upgrade) — Asynchronously upgrades language packs after other upgrades have been made.
* [bulk\_upgrade](language_pack_upgrader/bulk_upgrade) — Bulk upgrade language packs.
* [check\_package](language_pack_upgrader/check_package) — Checks that the package source contains .mo and .po files.
* [clear\_destination](language_pack_upgrader/clear_destination) — Clears existing translations where this item is going to be installed into.
* [get\_name\_for\_update](language_pack_upgrader/get_name_for_update) — Get the name of an item being updated.
* [upgrade](language_pack_upgrader/upgrade) — Upgrade a language pack.
* [upgrade\_strings](language_pack_upgrader/upgrade_strings) — Initialize the upgrade strings.
File: `wp-admin/includes/class-language-pack-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-language-pack-upgrader.php/)
```
class Language_Pack_Upgrader extends WP_Upgrader {
/**
* Result of the language pack upgrade.
*
* @since 3.7.0
* @var array|WP_Error $result
* @see WP_Upgrader::$result
*/
public $result;
/**
* Whether a bulk upgrade/installation is being performed.
*
* @since 3.7.0
* @var bool $bulk
*/
public $bulk = true;
/**
* Asynchronously upgrades language packs after other upgrades have been made.
*
* Hooked to the {@see 'upgrader_process_complete'} action by default.
*
* @since 3.7.0
*
* @param false|WP_Upgrader $upgrader Optional. WP_Upgrader instance or false. If `$upgrader` is
* a Language_Pack_Upgrader instance, the method will bail to
* avoid recursion. Otherwise unused. Default false.
*/
public static function async_upgrade( $upgrader = false ) {
// Avoid recursion.
if ( $upgrader && $upgrader instanceof Language_Pack_Upgrader ) {
return;
}
// Nothing to do?
$language_updates = wp_get_translation_updates();
if ( ! $language_updates ) {
return;
}
/*
* Avoid messing with VCS installations, at least for now.
* Noted: this is not the ideal way to accomplish this.
*/
$check_vcs = new WP_Automatic_Updater;
if ( $check_vcs->is_vcs_checkout( WP_CONTENT_DIR ) ) {
return;
}
foreach ( $language_updates as $key => $language_update ) {
$update = ! empty( $language_update->autoupdate );
/**
* Filters whether to asynchronously update translation for core, a plugin, or a theme.
*
* @since 4.0.0
*
* @param bool $update Whether to update.
* @param object $language_update The update offer.
*/
$update = apply_filters( 'async_update_translation', $update, $language_update );
if ( ! $update ) {
unset( $language_updates[ $key ] );
}
}
if ( empty( $language_updates ) ) {
return;
}
// Re-use the automatic upgrader skin if the parent upgrader is using it.
if ( $upgrader && $upgrader->skin instanceof Automatic_Upgrader_Skin ) {
$skin = $upgrader->skin;
} else {
$skin = new Language_Pack_Upgrader_Skin(
array(
'skip_header_footer' => true,
)
);
}
$lp_upgrader = new Language_Pack_Upgrader( $skin );
$lp_upgrader->bulk_upgrade( $language_updates );
}
/**
* Initialize the upgrade strings.
*
* @since 3.7.0
*/
public function upgrade_strings() {
$this->strings['starting_upgrade'] = __( 'Some of your translations need updating. Sit tight for a few more seconds while they are updated as well.' );
$this->strings['up_to_date'] = __( 'Your translations are all up to date.' );
$this->strings['no_package'] = __( 'Update package not available.' );
/* translators: %s: Package URL. */
$this->strings['downloading_package'] = sprintf( __( 'Downloading translation from %s…' ), '<span class="code">%s</span>' );
$this->strings['unpack_package'] = __( 'Unpacking the update…' );
$this->strings['process_failed'] = __( 'Translation update failed.' );
$this->strings['process_success'] = __( 'Translation updated successfully.' );
$this->strings['remove_old'] = __( 'Removing the old version of the translation…' );
$this->strings['remove_old_failed'] = __( 'Could not remove the old translation.' );
}
/**
* Upgrade a language pack.
*
* @since 3.7.0
*
* @param string|false $update Optional. Whether an update offer is available. Default false.
* @param array $args Optional. Other optional arguments, see
* Language_Pack_Upgrader::bulk_upgrade(). Default empty array.
* @return array|bool|WP_Error The result of the upgrade, or a WP_Error object instead.
*/
public function upgrade( $update = false, $args = array() ) {
if ( $update ) {
$update = array( $update );
}
$results = $this->bulk_upgrade( $update, $args );
if ( ! is_array( $results ) ) {
return $results;
}
return $results[0];
}
/**
* Bulk upgrade language packs.
*
* @since 3.7.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param object[] $language_updates Optional. Array of language packs to update. @see wp_get_translation_updates().
* Default empty array.
* @param array $args {
* Other arguments for upgrading multiple language packs. Default empty array.
*
* @type bool $clear_update_cache Whether to clear the update cache when done.
* Default true.
* }
* @return array|bool|WP_Error Will return an array of results, or true if there are no updates,
* false or WP_Error for initial errors.
*/
public function bulk_upgrade( $language_updates = array(), $args = array() ) {
global $wp_filesystem;
$defaults = array(
'clear_update_cache' => true,
);
$parsed_args = wp_parse_args( $args, $defaults );
$this->init();
$this->upgrade_strings();
if ( ! $language_updates ) {
$language_updates = wp_get_translation_updates();
}
if ( empty( $language_updates ) ) {
$this->skin->header();
$this->skin->set_result( true );
$this->skin->feedback( 'up_to_date' );
$this->skin->bulk_footer();
$this->skin->footer();
return true;
}
if ( 'upgrader_process_complete' === current_filter() ) {
$this->skin->feedback( 'starting_upgrade' );
}
// Remove any existing upgrade filters from the plugin/theme upgraders #WP29425 & #WP29230.
remove_all_filters( 'upgrader_pre_install' );
remove_all_filters( 'upgrader_clear_destination' );
remove_all_filters( 'upgrader_post_install' );
remove_all_filters( 'upgrader_source_selection' );
add_filter( 'upgrader_source_selection', array( $this, 'check_package' ), 10, 2 );
$this->skin->header();
// Connect to the filesystem first.
$res = $this->fs_connect( array( WP_CONTENT_DIR, WP_LANG_DIR ) );
if ( ! $res ) {
$this->skin->footer();
return false;
}
$results = array();
$this->update_count = count( $language_updates );
$this->update_current = 0;
/*
* The filesystem's mkdir() is not recursive. Make sure WP_LANG_DIR exists,
* as we then may need to create a /plugins or /themes directory inside of it.
*/
$remote_destination = $wp_filesystem->find_folder( WP_LANG_DIR );
if ( ! $wp_filesystem->exists( $remote_destination ) ) {
if ( ! $wp_filesystem->mkdir( $remote_destination, FS_CHMOD_DIR ) ) {
return new WP_Error( 'mkdir_failed_lang_dir', $this->strings['mkdir_failed'], $remote_destination );
}
}
$language_updates_results = array();
foreach ( $language_updates as $language_update ) {
$this->skin->language_update = $language_update;
$destination = WP_LANG_DIR;
if ( 'plugin' === $language_update->type ) {
$destination .= '/plugins';
} elseif ( 'theme' === $language_update->type ) {
$destination .= '/themes';
}
$this->update_current++;
$options = array(
'package' => $language_update->package,
'destination' => $destination,
'clear_destination' => true,
'abort_if_destination_exists' => false, // We expect the destination to exist.
'clear_working' => true,
'is_multi' => true,
'hook_extra' => array(
'language_update_type' => $language_update->type,
'language_update' => $language_update,
),
);
$result = $this->run( $options );
$results[] = $this->result;
// Prevent credentials auth screen from displaying multiple times.
if ( false === $result ) {
break;
}
$language_updates_results[] = array(
'language' => $language_update->language,
'type' => $language_update->type,
'slug' => isset( $language_update->slug ) ? $language_update->slug : 'default',
'version' => $language_update->version,
);
}
// Remove upgrade hooks which are not required for translation updates.
remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
remove_action( 'upgrader_process_complete', 'wp_version_check' );
remove_action( 'upgrader_process_complete', 'wp_update_plugins' );
remove_action( 'upgrader_process_complete', 'wp_update_themes' );
/** This action is documented in wp-admin/includes/class-wp-upgrader.php */
do_action(
'upgrader_process_complete',
$this,
array(
'action' => 'update',
'type' => 'translation',
'bulk' => true,
'translations' => $language_updates_results,
)
);
// Re-add upgrade hooks.
add_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
add_action( 'upgrader_process_complete', 'wp_version_check', 10, 0 );
add_action( 'upgrader_process_complete', 'wp_update_plugins', 10, 0 );
add_action( 'upgrader_process_complete', 'wp_update_themes', 10, 0 );
$this->skin->bulk_footer();
$this->skin->footer();
// Clean up our hooks, in case something else does an upgrade on this connection.
remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
if ( $parsed_args['clear_update_cache'] ) {
wp_clean_update_cache();
}
return $results;
}
/**
* Checks that the package source contains .mo and .po files.
*
* Hooked to the {@see 'upgrader_source_selection'} filter by
* Language_Pack_Upgrader::bulk_upgrade().
*
* @since 3.7.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string|WP_Error $source The path to the downloaded package source.
* @param string $remote_source Remote file source location.
* @return string|WP_Error The source as passed, or a WP_Error object on failure.
*/
public function check_package( $source, $remote_source ) {
global $wp_filesystem;
if ( is_wp_error( $source ) ) {
return $source;
}
// Check that the folder contains a valid language.
$files = $wp_filesystem->dirlist( $remote_source );
// Check to see if a .po and .mo exist in the folder.
$po = false;
$mo = false;
foreach ( (array) $files as $file => $filedata ) {
if ( '.po' === substr( $file, -3 ) ) {
$po = true;
} elseif ( '.mo' === substr( $file, -3 ) ) {
$mo = true;
}
}
if ( ! $mo || ! $po ) {
return new WP_Error(
'incompatible_archive_pomo',
$this->strings['incompatible_archive'],
sprintf(
/* translators: 1: .po, 2: .mo */
__( 'The language pack is missing either the %1$s or %2$s files.' ),
'<code>.po</code>',
'<code>.mo</code>'
)
);
}
return $source;
}
/**
* Get the name of an item being updated.
*
* @since 3.7.0
*
* @param object $update The data for an update.
* @return string The name of the item being updated.
*/
public function get_name_for_update( $update ) {
switch ( $update->type ) {
case 'core':
return 'WordPress'; // Not translated.
case 'theme':
$theme = wp_get_theme( $update->slug );
if ( $theme->exists() ) {
return $theme->Get( 'Name' );
}
break;
case 'plugin':
$plugin_data = get_plugins( '/' . $update->slug );
$plugin_data = reset( $plugin_data );
if ( $plugin_data ) {
return $plugin_data['Name'];
}
break;
}
return '';
}
/**
* Clears existing translations where this item is going to be installed into.
*
* @since 5.1.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string $remote_destination The location on the remote filesystem to be cleared.
* @return bool|WP_Error True upon success, WP_Error on failure.
*/
public function clear_destination( $remote_destination ) {
global $wp_filesystem;
$language_update = $this->skin->language_update;
$language_directory = WP_LANG_DIR . '/'; // Local path for use with glob().
if ( 'core' === $language_update->type ) {
$files = array(
$remote_destination . $language_update->language . '.po',
$remote_destination . $language_update->language . '.mo',
$remote_destination . 'admin-' . $language_update->language . '.po',
$remote_destination . 'admin-' . $language_update->language . '.mo',
$remote_destination . 'admin-network-' . $language_update->language . '.po',
$remote_destination . 'admin-network-' . $language_update->language . '.mo',
$remote_destination . 'continents-cities-' . $language_update->language . '.po',
$remote_destination . 'continents-cities-' . $language_update->language . '.mo',
);
$json_translation_files = glob( $language_directory . $language_update->language . '-*.json' );
if ( $json_translation_files ) {
foreach ( $json_translation_files as $json_translation_file ) {
$files[] = str_replace( $language_directory, $remote_destination, $json_translation_file );
}
}
} else {
$files = array(
$remote_destination . $language_update->slug . '-' . $language_update->language . '.po',
$remote_destination . $language_update->slug . '-' . $language_update->language . '.mo',
);
$language_directory = $language_directory . $language_update->type . 's/';
$json_translation_files = glob( $language_directory . $language_update->slug . '-' . $language_update->language . '-*.json' );
if ( $json_translation_files ) {
foreach ( $json_translation_files as $json_translation_file ) {
$files[] = str_replace( $language_directory, $remote_destination, $json_translation_file );
}
}
}
$files = array_filter( $files, array( $wp_filesystem, 'exists' ) );
// No files to delete.
if ( ! $files ) {
return true;
}
// Check all files are writable before attempting to clear the destination.
$unwritable_files = array();
// Check writability.
foreach ( $files as $file ) {
if ( ! $wp_filesystem->is_writable( $file ) ) {
// Attempt to alter permissions to allow writes and try again.
$wp_filesystem->chmod( $file, FS_CHMOD_FILE );
if ( ! $wp_filesystem->is_writable( $file ) ) {
$unwritable_files[] = $file;
}
}
}
if ( ! empty( $unwritable_files ) ) {
return new WP_Error( 'files_not_writable', $this->strings['files_not_writable'], implode( ', ', $unwritable_files ) );
}
foreach ( $files as $file ) {
if ( ! $wp_filesystem->delete( $file ) ) {
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. |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress class WP_Sitemaps_Stylesheet {} class WP\_Sitemaps\_Stylesheet {}
=================================
Stylesheet provider class.
* [get\_sitemap\_index\_stylesheet](wp_sitemaps_stylesheet/get_sitemap_index_stylesheet) — Returns the escaped XSL for the index sitemaps.
* [get\_sitemap\_stylesheet](wp_sitemaps_stylesheet/get_sitemap_stylesheet) — Returns the escaped XSL for all sitemaps, except index.
* [get\_stylesheet\_css](wp_sitemaps_stylesheet/get_stylesheet_css) — Gets the CSS to be included in sitemap XSL stylesheets.
* [render\_stylesheet](wp_sitemaps_stylesheet/render_stylesheet) — Renders the XSL stylesheet depending on whether it's the sitemap index or not.
File: `wp-includes/sitemaps/class-wp-sitemaps-stylesheet.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps-stylesheet.php/)
```
class WP_Sitemaps_Stylesheet {
/**
* Renders the XSL stylesheet depending on whether it's the sitemap index or not.
*
* @param string $type Stylesheet type. Either 'sitemap' or 'index'.
*/
public function render_stylesheet( $type ) {
header( 'Content-type: application/xml; charset=UTF-8' );
if ( 'sitemap' === $type ) {
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- All content escaped below.
echo $this->get_sitemap_stylesheet();
}
if ( 'index' === $type ) {
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- All content escaped below.
echo $this->get_sitemap_index_stylesheet();
}
exit;
}
/**
* Returns the escaped XSL for all sitemaps, except index.
*
* @since 5.5.0
*/
public function get_sitemap_stylesheet() {
$css = $this->get_stylesheet_css();
$title = esc_xml( __( 'XML Sitemap' ) );
$description = esc_xml( __( 'This XML Sitemap is generated by WordPress to make your content more visible for search engines.' ) );
$learn_more = sprintf(
'<a href="%s">%s</a>',
esc_url( __( 'https://www.sitemaps.org/' ) ),
esc_xml( __( 'Learn more about XML sitemaps.' ) )
);
$text = sprintf(
/* translators: %s: Number of URLs. */
esc_xml( __( 'Number of URLs in this XML Sitemap: %s.' ) ),
'<xsl:value-of select="count( sitemap:urlset/sitemap:url )" />'
);
$lang = get_language_attributes( 'html' );
$url = esc_xml( __( 'URL' ) );
$lastmod = esc_xml( __( 'Last Modified' ) );
$changefreq = esc_xml( __( 'Change Frequency' ) );
$priority = esc_xml( __( 'Priority' ) );
$xsl_content = <<<XSL
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:sitemap="http://www.sitemaps.org/schemas/sitemap/0.9"
exclude-result-prefixes="sitemap"
>
<xsl:output method="html" encoding="UTF-8" indent="yes" />
<!--
Set variables for whether lastmod, changefreq or priority occur for any url in the sitemap.
We do this up front because it can be expensive in a large sitemap.
-->
<xsl:variable name="has-lastmod" select="count( /sitemap:urlset/sitemap:url/sitemap:lastmod )" />
<xsl:variable name="has-changefreq" select="count( /sitemap:urlset/sitemap:url/sitemap:changefreq )" />
<xsl:variable name="has-priority" select="count( /sitemap:urlset/sitemap:url/sitemap:priority )" />
<xsl:template match="/">
<html {$lang}>
<head>
<title>{$title}</title>
<style>
{$css}
</style>
</head>
<body>
<div id="sitemap">
<div id="sitemap__header">
<h1>{$title}</h1>
<p>{$description}</p>
<p>{$learn_more}</p>
</div>
<div id="sitemap__content">
<p class="text">{$text}</p>
<table id="sitemap__table">
<thead>
<tr>
<th class="loc">{$url}</th>
<xsl:if test="\$has-lastmod">
<th class="lastmod">{$lastmod}</th>
</xsl:if>
<xsl:if test="\$has-changefreq">
<th class="changefreq">{$changefreq}</th>
</xsl:if>
<xsl:if test="\$has-priority">
<th class="priority">{$priority}</th>
</xsl:if>
</tr>
</thead>
<tbody>
<xsl:for-each select="sitemap:urlset/sitemap:url">
<tr>
<td class="loc"><a href="{sitemap:loc}"><xsl:value-of select="sitemap:loc" /></a></td>
<xsl:if test="\$has-lastmod">
<td class="lastmod"><xsl:value-of select="sitemap:lastmod" /></td>
</xsl:if>
<xsl:if test="\$has-changefreq">
<td class="changefreq"><xsl:value-of select="sitemap:changefreq" /></td>
</xsl:if>
<xsl:if test="\$has-priority">
<td class="priority"><xsl:value-of select="sitemap:priority" /></td>
</xsl:if>
</tr>
</xsl:for-each>
</tbody>
</table>
</div>
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
XSL;
/**
* Filters the content of the sitemap stylesheet.
*
* @since 5.5.0
*
* @param string $xsl_content Full content for the XML stylesheet.
*/
return apply_filters( 'wp_sitemaps_stylesheet_content', $xsl_content );
}
/**
* Returns the escaped XSL for the index sitemaps.
*
* @since 5.5.0
*/
public function get_sitemap_index_stylesheet() {
$css = $this->get_stylesheet_css();
$title = esc_xml( __( 'XML Sitemap' ) );
$description = esc_xml( __( 'This XML Sitemap is generated by WordPress to make your content more visible for search engines.' ) );
$learn_more = sprintf(
'<a href="%s">%s</a>',
esc_url( __( 'https://www.sitemaps.org/' ) ),
esc_xml( __( 'Learn more about XML sitemaps.' ) )
);
$text = sprintf(
/* translators: %s: Number of URLs. */
esc_xml( __( 'Number of URLs in this XML Sitemap: %s.' ) ),
'<xsl:value-of select="count( sitemap:sitemapindex/sitemap:sitemap )" />'
);
$lang = get_language_attributes( 'html' );
$url = esc_xml( __( 'URL' ) );
$lastmod = esc_xml( __( 'Last Modified' ) );
$xsl_content = <<<XSL
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:sitemap="http://www.sitemaps.org/schemas/sitemap/0.9"
exclude-result-prefixes="sitemap"
>
<xsl:output method="html" encoding="UTF-8" indent="yes" />
<!--
Set variables for whether lastmod occurs for any sitemap in the index.
We do this up front because it can be expensive in a large sitemap.
-->
<xsl:variable name="has-lastmod" select="count( /sitemap:sitemapindex/sitemap:sitemap/sitemap:lastmod )" />
<xsl:template match="/">
<html {$lang}>
<head>
<title>{$title}</title>
<style>
{$css}
</style>
</head>
<body>
<div id="sitemap">
<div id="sitemap__header">
<h1>{$title}</h1>
<p>{$description}</p>
<p>{$learn_more}</p>
</div>
<div id="sitemap__content">
<p class="text">{$text}</p>
<table id="sitemap__table">
<thead>
<tr>
<th class="loc">{$url}</th>
<xsl:if test="\$has-lastmod">
<th class="lastmod">{$lastmod}</th>
</xsl:if>
</tr>
</thead>
<tbody>
<xsl:for-each select="sitemap:sitemapindex/sitemap:sitemap">
<tr>
<td class="loc"><a href="{sitemap:loc}"><xsl:value-of select="sitemap:loc" /></a></td>
<xsl:if test="\$has-lastmod">
<td class="lastmod"><xsl:value-of select="sitemap:lastmod" /></td>
</xsl:if>
</tr>
</xsl:for-each>
</tbody>
</table>
</div>
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
XSL;
/**
* Filters the content of the sitemap index stylesheet.
*
* @since 5.5.0
*
* @param string $xsl_content Full content for the XML stylesheet.
*/
return apply_filters( 'wp_sitemaps_stylesheet_index_content', $xsl_content );
}
/**
* Gets the CSS to be included in sitemap XSL stylesheets.
*
* @since 5.5.0
*
* @return string The CSS.
*/
public function get_stylesheet_css() {
$text_align = is_rtl() ? 'right' : 'left';
$css = <<<EOF
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
color: #444;
}
#sitemap {
max-width: 980px;
margin: 0 auto;
}
#sitemap__table {
width: 100%;
border: solid 1px #ccc;
border-collapse: collapse;
}
#sitemap__table tr td.loc {
/*
* URLs should always be LTR.
* See https://core.trac.wordpress.org/ticket/16834
* and https://core.trac.wordpress.org/ticket/49949
*/
direction: ltr;
}
#sitemap__table tr th {
text-align: {$text_align};
}
#sitemap__table tr td,
#sitemap__table tr th {
padding: 10px;
}
#sitemap__table tr:nth-child(odd) td {
background-color: #eee;
}
a:hover {
text-decoration: none;
}
EOF;
/**
* Filters the CSS only for the sitemap stylesheet.
*
* @since 5.5.0
*
* @param string $css CSS to be applied to default XSL file.
*/
return apply_filters( 'wp_sitemaps_stylesheet_css', $css );
}
}
```
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
| programming_docs |
wordpress class POMO_StringReader {} class POMO\_StringReader {}
===========================
Provides file-like methods for manipulating a string instead of a physical file.
* [\_\_construct](pomo_stringreader/__construct) — PHP5 constructor.
* [length](pomo_stringreader/length)
* [POMO\_StringReader](pomo_stringreader/pomo_stringreader) — PHP4 constructor. — deprecated
* [read](pomo_stringreader/read)
* [read\_all](pomo_stringreader/read_all)
* [seekto](pomo_stringreader/seekto)
File: `wp-includes/pomo/streams.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/pomo/streams.php/)
```
class POMO_StringReader extends POMO_Reader {
public $_str = '';
/**
* PHP5 constructor.
*/
public function __construct( $str = '' ) {
parent::__construct();
$this->_str = $str;
$this->_pos = 0;
}
/**
* PHP4 constructor.
*
* @deprecated 5.4.0 Use __construct() instead.
*
* @see POMO_StringReader::__construct()
*/
public function POMO_StringReader( $str = '' ) {
_deprecated_constructor( self::class, '5.4.0', static::class );
self::__construct( $str );
}
/**
* @param string $bytes
* @return string
*/
public function read( $bytes ) {
$data = $this->substr( $this->_str, $this->_pos, $bytes );
$this->_pos += $bytes;
if ( $this->strlen( $this->_str ) < $this->_pos ) {
$this->_pos = $this->strlen( $this->_str );
}
return $data;
}
/**
* @param int $pos
* @return int
*/
public function seekto( $pos ) {
$this->_pos = $pos;
if ( $this->strlen( $this->_str ) < $this->_pos ) {
$this->_pos = $this->strlen( $this->_str );
}
return $this->_pos;
}
/**
* @return int
*/
public function length() {
return $this->strlen( $this->_str );
}
/**
* @return string
*/
public function read_all() {
return $this->substr( $this->_str, $this->_pos, $this->strlen( $this->_str ) );
}
}
```
| Uses | Description |
| --- | --- |
| [POMO\_Reader](pomo_reader) wp-includes/pomo/streams.php | |
| Used By | Description |
| --- | --- |
| [POMO\_CachedFileReader](pomo_cachedfilereader) wp-includes/pomo/streams.php | Reads the contents of the file in the beginning. |
wordpress class WP_MS_Sites_List_Table {} class WP\_MS\_Sites\_List\_Table {}
===================================
Core class used to implement displaying sites in a list table for the network admin.
* [WP\_List\_Table](wp_list_table)
* [\_\_construct](wp_ms_sites_list_table/__construct) — Constructor.
* [ajax\_user\_can](wp_ms_sites_list_table/ajax_user_can)
* [column\_blogname](wp_ms_sites_list_table/column_blogname) — Handles the site name column output.
* [column\_cb](wp_ms_sites_list_table/column_cb) — Handles the checkbox column output.
* [column\_default](wp_ms_sites_list_table/column_default) — Handles output for the default column.
* [column\_id](wp_ms_sites_list_table/column_id) — Handles the ID column output.
* [column\_lastupdated](wp_ms_sites_list_table/column_lastupdated) — Handles the lastupdated column output.
* [column\_plugins](wp_ms_sites_list_table/column_plugins) — Handles the plugins column output.
* [column\_registered](wp_ms_sites_list_table/column_registered) — Handles the registered column output.
* [column\_users](wp_ms_sites_list_table/column_users) — Handles the users column output.
* [display\_rows](wp_ms_sites_list_table/display_rows)
* [extra\_tablenav](wp_ms_sites_list_table/extra_tablenav) — Extra controls to be displayed between bulk actions and pagination.
* [get\_bulk\_actions](wp_ms_sites_list_table/get_bulk_actions)
* [get\_columns](wp_ms_sites_list_table/get_columns)
* [get\_default\_primary\_column\_name](wp_ms_sites_list_table/get_default_primary_column_name) — Gets the name of the default primary column.
* [get\_sortable\_columns](wp_ms_sites_list_table/get_sortable_columns)
* [get\_views](wp_ms_sites_list_table/get_views) — Gets links to filter sites by status.
* [handle\_row\_actions](wp_ms_sites_list_table/handle_row_actions) — Generates and displays row action links.
* [no\_items](wp_ms_sites_list_table/no_items)
* [pagination](wp_ms_sites_list_table/pagination)
* [prepare\_items](wp_ms_sites_list_table/prepare_items) — Prepares the list of sites for display.
* [site\_states](wp_ms_sites_list_table/site_states) — Maybe output comma-separated site states.
File: `wp-admin/includes/class-wp-ms-sites-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-ms-sites-list-table.php/)
```
class WP_MS_Sites_List_Table extends WP_List_Table {
/**
* Site status list.
*
* @since 4.3.0
* @var array
*/
public $status_list;
/**
* 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->status_list = array(
'archived' => array( 'site-archived', __( 'Archived' ) ),
'spam' => array( 'site-spammed', _x( 'Spam', 'site' ) ),
'deleted' => array( 'site-deleted', __( 'Deleted' ) ),
'mature' => array( 'site-mature', __( 'Mature' ) ),
);
parent::__construct(
array(
'plural' => 'sites',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
}
/**
* @return bool
*/
public function ajax_user_can() {
return current_user_can( 'manage_sites' );
}
/**
* Prepares the list of sites for display.
*
* @since 3.1.0
*
* @global string $mode List table view mode.
* @global string $s
* @global wpdb $wpdb WordPress database abstraction object.
*/
public function prepare_items() {
global $mode, $s, $wpdb;
if ( ! empty( $_REQUEST['mode'] ) ) {
$mode = 'excerpt' === $_REQUEST['mode'] ? 'excerpt' : 'list';
set_user_setting( 'sites_list_mode', $mode );
} else {
$mode = get_user_setting( 'sites_list_mode', 'list' );
}
$per_page = $this->get_items_per_page( 'sites_network_per_page' );
$pagenum = $this->get_pagenum();
$s = isset( $_REQUEST['s'] ) ? wp_unslash( trim( $_REQUEST['s'] ) ) : '';
$wild = '';
if ( false !== strpos( $s, '*' ) ) {
$wild = '*';
$s = trim( $s, '*' );
}
/*
* If the network is large and a search is not being performed, show only
* the latest sites with no paging in order to avoid expensive count queries.
*/
if ( ! $s && wp_is_large_network() ) {
if ( ! isset( $_REQUEST['orderby'] ) ) {
$_GET['orderby'] = '';
$_REQUEST['orderby'] = '';
}
if ( ! isset( $_REQUEST['order'] ) ) {
$_GET['order'] = 'DESC';
$_REQUEST['order'] = 'DESC';
}
}
$args = array(
'number' => (int) $per_page,
'offset' => (int) ( ( $pagenum - 1 ) * $per_page ),
'network_id' => get_current_network_id(),
);
if ( empty( $s ) ) {
// Nothing to do.
} elseif ( preg_match( '/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $s ) ||
preg_match( '/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.?$/', $s ) ||
preg_match( '/^[0-9]{1,3}\.[0-9]{1,3}\.?$/', $s ) ||
preg_match( '/^[0-9]{1,3}\.$/', $s ) ) {
// IPv4 address.
$sql = $wpdb->prepare( "SELECT blog_id FROM {$wpdb->registration_log} WHERE {$wpdb->registration_log}.IP LIKE %s", $wpdb->esc_like( $s ) . ( ! empty( $wild ) ? '%' : '' ) );
$reg_blog_ids = $wpdb->get_col( $sql );
if ( $reg_blog_ids ) {
$args['site__in'] = $reg_blog_ids;
}
} elseif ( is_numeric( $s ) && empty( $wild ) ) {
$args['ID'] = $s;
} else {
$args['search'] = $s;
if ( ! is_subdomain_install() ) {
$args['search_columns'] = array( 'path' );
}
}
$order_by = isset( $_REQUEST['orderby'] ) ? $_REQUEST['orderby'] : '';
if ( 'registered' === $order_by ) {
// 'registered' is a valid field name.
} elseif ( 'lastupdated' === $order_by ) {
$order_by = 'last_updated';
} elseif ( 'blogname' === $order_by ) {
if ( is_subdomain_install() ) {
$order_by = 'domain';
} else {
$order_by = 'path';
}
} elseif ( 'blog_id' === $order_by ) {
$order_by = 'id';
} elseif ( ! $order_by ) {
$order_by = false;
}
$args['orderby'] = $order_by;
if ( $order_by ) {
$args['order'] = ( isset( $_REQUEST['order'] ) && 'DESC' === strtoupper( $_REQUEST['order'] ) ) ? 'DESC' : 'ASC';
}
if ( wp_is_large_network() ) {
$args['no_found_rows'] = true;
} else {
$args['no_found_rows'] = false;
}
// Take into account the role the user has selected.
$status = isset( $_REQUEST['status'] ) ? wp_unslash( trim( $_REQUEST['status'] ) ) : '';
if ( in_array( $status, array( 'public', 'archived', 'mature', 'spam', 'deleted' ), true ) ) {
$args[ $status ] = 1;
}
/**
* Filters the arguments for the site query in the sites list table.
*
* @since 4.6.0
*
* @param array $args An array of get_sites() arguments.
*/
$args = apply_filters( 'ms_sites_list_table_query_args', $args );
$_sites = get_sites( $args );
if ( is_array( $_sites ) ) {
update_site_cache( $_sites );
$this->items = array_slice( $_sites, 0, $per_page );
}
$total_sites = get_sites(
array_merge(
$args,
array(
'count' => true,
'offset' => 0,
'number' => 0,
)
)
);
$this->set_pagination_args(
array(
'total_items' => $total_sites,
'per_page' => $per_page,
)
);
}
/**
*/
public function no_items() {
_e( 'No sites found.' );
}
/**
* Gets links to filter sites by status.
*
* @since 5.3.0
*
* @return array
*/
protected function get_views() {
$counts = wp_count_sites();
$statuses = array(
/* translators: %s: Number of sites. */
'all' => _nx_noop(
'All <span class="count">(%s)</span>',
'All <span class="count">(%s)</span>',
'sites'
),
/* translators: %s: Number of sites. */
'public' => _n_noop(
'Public <span class="count">(%s)</span>',
'Public <span class="count">(%s)</span>'
),
/* translators: %s: Number of sites. */
'archived' => _n_noop(
'Archived <span class="count">(%s)</span>',
'Archived <span class="count">(%s)</span>'
),
/* translators: %s: Number of sites. */
'mature' => _n_noop(
'Mature <span class="count">(%s)</span>',
'Mature <span class="count">(%s)</span>'
),
/* translators: %s: Number of sites. */
'spam' => _nx_noop(
'Spam <span class="count">(%s)</span>',
'Spam <span class="count">(%s)</span>',
'sites'
),
/* translators: %s: Number of sites. */
'deleted' => _n_noop(
'Deleted <span class="count">(%s)</span>',
'Deleted <span class="count">(%s)</span>'
),
);
$view_links = array();
$requested_status = isset( $_REQUEST['status'] ) ? wp_unslash( trim( $_REQUEST['status'] ) ) : '';
$url = 'sites.php';
foreach ( $statuses as $status => $label_count ) {
if ( (int) $counts[ $status ] > 0 ) {
$label = sprintf( translate_nooped_plural( $label_count, $counts[ $status ] ), number_format_i18n( $counts[ $status ] ) );
$full_url = 'all' === $status ? $url : add_query_arg( 'status', $status, $url );
$view_links[ $status ] = array(
'url' => esc_url( $full_url ),
'label' => $label,
'current' => $requested_status === $status || ( '' === $requested_status && 'all' === $status ),
);
}
}
return $this->get_views_links( $view_links );
}
/**
* @return array
*/
protected function get_bulk_actions() {
$actions = array();
if ( current_user_can( 'delete_sites' ) ) {
$actions['delete'] = __( 'Delete' );
}
$actions['spam'] = _x( 'Mark as spam', 'site' );
$actions['notspam'] = _x( 'Not spam', 'site' );
return $actions;
}
/**
* @global string $mode List table view mode.
*
* @param string $which The location of the pagination nav markup: 'top' or 'bottom'.
*/
protected function pagination( $which ) {
global $mode;
parent::pagination( $which );
if ( 'top' === $which ) {
$this->view_switcher( $mode );
}
}
/**
* Extra controls to be displayed between bulk actions and pagination.
*
* @since 5.3.0
*
* @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
*/
protected function extra_tablenav( $which ) {
?>
<div class="alignleft actions">
<?php
if ( 'top' === $which ) {
ob_start();
/**
* Fires before the Filter button on the MS sites list table.
*
* @since 5.3.0
*
* @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
*/
do_action( 'restrict_manage_sites', $which );
$output = ob_get_clean();
if ( ! empty( $output ) ) {
echo $output;
submit_button( __( 'Filter' ), '', 'filter_action', false, array( 'id' => 'site-query-submit' ) );
}
}
?>
</div>
<?php
/**
* Fires immediately following the closing "actions" div in the tablenav for the
* MS sites list table.
*
* @since 5.3.0
*
* @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
*/
do_action( 'manage_sites_extra_tablenav', $which );
}
/**
* @return array
*/
public function get_columns() {
$sites_columns = array(
'cb' => '<input type="checkbox" />',
'blogname' => __( 'URL' ),
'lastupdated' => __( 'Last Updated' ),
'registered' => _x( 'Registered', 'site' ),
'users' => __( 'Users' ),
);
if ( has_filter( 'wpmublogsaction' ) ) {
$sites_columns['plugins'] = __( 'Actions' );
}
/**
* Filters the displayed site columns in Sites list table.
*
* @since MU (3.0.0)
*
* @param string[] $sites_columns An array of displayed site columns. Default 'cb',
* 'blogname', 'lastupdated', 'registered', 'users'.
*/
return apply_filters( 'wpmu_blogs_columns', $sites_columns );
}
/**
* @return array
*/
protected function get_sortable_columns() {
return array(
'blogname' => 'blogname',
'lastupdated' => 'lastupdated',
'registered' => 'blog_id',
);
}
/**
* Handles the checkbox column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$blog` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param array $item Current site.
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$blog = $item;
if ( ! is_main_site( $blog['blog_id'] ) ) :
$blogname = untrailingslashit( $blog['domain'] . $blog['path'] );
?>
<label class="screen-reader-text" for="blog_<?php echo $blog['blog_id']; ?>">
<?php
/* translators: %s: Site URL. */
printf( __( 'Select %s' ), $blogname );
?>
</label>
<input type="checkbox" id="blog_<?php echo $blog['blog_id']; ?>" name="allblogs[]" value="<?php echo esc_attr( $blog['blog_id'] ); ?>" />
<?php
endif;
}
/**
* Handles the ID column output.
*
* @since 4.4.0
*
* @param array $blog Current site.
*/
public function column_id( $blog ) {
echo $blog['blog_id'];
}
/**
* Handles the site name column output.
*
* @since 4.3.0
*
* @global string $mode List table view mode.
*
* @param array $blog Current site.
*/
public function column_blogname( $blog ) {
global $mode;
$blogname = untrailingslashit( $blog['domain'] . $blog['path'] );
?>
<strong>
<a href="<?php echo esc_url( network_admin_url( 'site-info.php?id=' . $blog['blog_id'] ) ); ?>" class="edit"><?php echo $blogname; ?></a>
<?php $this->site_states( $blog ); ?>
</strong>
<?php
if ( 'list' !== $mode ) {
switch_to_blog( $blog['blog_id'] );
echo '<p>';
printf(
/* translators: 1: Site title, 2: Site tagline. */
__( '%1$s – %2$s' ),
get_option( 'blogname' ),
'<em>' . get_option( 'blogdescription' ) . '</em>'
);
echo '</p>';
restore_current_blog();
}
}
/**
* Handles the lastupdated column output.
*
* @since 4.3.0
*
* @global string $mode List table view mode.
*
* @param array $blog Current site.
*/
public function column_lastupdated( $blog ) {
global $mode;
if ( 'list' === $mode ) {
$date = __( 'Y/m/d' );
} else {
$date = __( 'Y/m/d g:i:s a' );
}
echo ( '0000-00-00 00:00:00' === $blog['last_updated'] ) ? __( 'Never' ) : mysql2date( $date, $blog['last_updated'] );
}
/**
* Handles the registered column output.
*
* @since 4.3.0
*
* @global string $mode List table view mode.
*
* @param array $blog Current site.
*/
public function column_registered( $blog ) {
global $mode;
if ( 'list' === $mode ) {
$date = __( 'Y/m/d' );
} else {
$date = __( 'Y/m/d g:i:s a' );
}
if ( '0000-00-00 00:00:00' === $blog['registered'] ) {
echo '—';
} else {
echo mysql2date( $date, $blog['registered'] );
}
}
/**
* Handles the users column output.
*
* @since 4.3.0
*
* @param array $blog Current site.
*/
public function column_users( $blog ) {
$user_count = wp_cache_get( $blog['blog_id'] . '_user_count', 'blog-details' );
if ( ! $user_count ) {
$blog_users = new WP_User_Query(
array(
'blog_id' => $blog['blog_id'],
'fields' => 'ID',
'number' => 1,
'count_total' => true,
)
);
$user_count = $blog_users->get_total();
wp_cache_set( $blog['blog_id'] . '_user_count', $user_count, 'blog-details', 12 * HOUR_IN_SECONDS );
}
printf(
'<a href="%s">%s</a>',
esc_url( network_admin_url( 'site-users.php?id=' . $blog['blog_id'] ) ),
number_format_i18n( $user_count )
);
}
/**
* Handles the plugins column output.
*
* @since 4.3.0
*
* @param array $blog Current site.
*/
public function column_plugins( $blog ) {
if ( has_filter( 'wpmublogsaction' ) ) {
/**
* Fires inside the auxiliary 'Actions' column of the Sites list table.
*
* By default this column is hidden unless something is hooked to the action.
*
* @since MU (3.0.0)
*
* @param int $blog_id The site ID.
*/
do_action( 'wpmublogsaction', $blog['blog_id'] );
}
}
/**
* Handles output for the default column.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$blog` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param array $item Current site.
* @param string $column_name Current column name.
*/
public function column_default( $item, $column_name ) {
/**
* Fires for each registered custom column in the Sites list table.
*
* @since 3.1.0
*
* @param string $column_name The name of the column to display.
* @param int $blog_id The site ID.
*/
do_action( 'manage_sites_custom_column', $column_name, $item['blog_id'] );
}
/**
* @global string $mode List table view mode.
*/
public function display_rows() {
foreach ( $this->items as $blog ) {
$blog = $blog->to_array();
$class = '';
reset( $this->status_list );
foreach ( $this->status_list as $status => $col ) {
if ( 1 == $blog[ $status ] ) {
$class = " class='{$col[0]}'";
}
}
echo "<tr{$class}>";
$this->single_row_columns( $blog );
echo '</tr>';
}
}
/**
* Maybe output comma-separated site states.
*
* @since 5.3.0
*
* @param array $site
*/
protected function site_states( $site ) {
$site_states = array();
// $site is still an array, so get the object.
$_site = WP_Site::get_instance( $site['blog_id'] );
if ( is_main_site( $_site->id ) ) {
$site_states['main'] = __( 'Main' );
}
reset( $this->status_list );
$site_status = isset( $_REQUEST['status'] ) ? wp_unslash( trim( $_REQUEST['status'] ) ) : '';
foreach ( $this->status_list as $status => $col ) {
if ( ( 1 === (int) $_site->{$status} ) && ( $site_status !== $status ) ) {
$site_states[ $col[0] ] = $col[1];
}
}
/**
* Filters the default site display states for items in the Sites list table.
*
* @since 5.3.0
*
* @param string[] $site_states An array of site states. Default 'Main',
* 'Archived', 'Mature', 'Spam', 'Deleted'.
* @param WP_Site $site The current site object.
*/
$site_states = apply_filters( 'display_site_states', $site_states, $_site );
if ( ! empty( $site_states ) ) {
$state_count = count( $site_states );
$i = 0;
echo ' — ';
foreach ( $site_states as $state ) {
++$i;
$separator = ( $i < $state_count ) ? ', ' : '';
echo "<span class='post-state'>{$state}{$separator}</span>";
}
}
}
/**
* Gets the name of the default primary column.
*
* @since 4.3.0
*
* @return string Name of the default primary column, in this case, 'blogname'.
*/
protected function get_default_primary_column_name() {
return 'blogname';
}
/**
* Generates and displays row action links.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$blog` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param array $item Site being acted upon.
* @param string $column_name Current column name.
* @param string $primary Primary column name.
* @return string Row actions output for sites 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.
$blog = $item;
$blogname = untrailingslashit( $blog['domain'] . $blog['path'] );
// Preordered.
$actions = array(
'edit' => '',
'backend' => '',
'activate' => '',
'deactivate' => '',
'archive' => '',
'unarchive' => '',
'spam' => '',
'unspam' => '',
'delete' => '',
'visit' => '',
);
$actions['edit'] = '<a href="' . esc_url( network_admin_url( 'site-info.php?id=' . $blog['blog_id'] ) ) . '">' . __( 'Edit' ) . '</a>';
$actions['backend'] = "<a href='" . esc_url( get_admin_url( $blog['blog_id'] ) ) . "' class='edit'>" . __( 'Dashboard' ) . '</a>';
if ( get_network()->site_id != $blog['blog_id'] ) {
if ( '1' == $blog['deleted'] ) {
$actions['activate'] = '<a href="' . esc_url( wp_nonce_url( network_admin_url( 'sites.php?action=confirm&action2=activateblog&id=' . $blog['blog_id'] ), 'activateblog_' . $blog['blog_id'] ) ) . '">' . __( 'Activate' ) . '</a>';
} else {
$actions['deactivate'] = '<a href="' . esc_url( wp_nonce_url( network_admin_url( 'sites.php?action=confirm&action2=deactivateblog&id=' . $blog['blog_id'] ), 'deactivateblog_' . $blog['blog_id'] ) ) . '">' . __( 'Deactivate' ) . '</a>';
}
if ( '1' == $blog['archived'] ) {
$actions['unarchive'] = '<a href="' . esc_url( wp_nonce_url( network_admin_url( 'sites.php?action=confirm&action2=unarchiveblog&id=' . $blog['blog_id'] ), 'unarchiveblog_' . $blog['blog_id'] ) ) . '">' . __( 'Unarchive' ) . '</a>';
} else {
$actions['archive'] = '<a href="' . esc_url( wp_nonce_url( network_admin_url( 'sites.php?action=confirm&action2=archiveblog&id=' . $blog['blog_id'] ), 'archiveblog_' . $blog['blog_id'] ) ) . '">' . _x( 'Archive', 'verb; site' ) . '</a>';
}
if ( '1' == $blog['spam'] ) {
$actions['unspam'] = '<a href="' . esc_url( wp_nonce_url( network_admin_url( 'sites.php?action=confirm&action2=unspamblog&id=' . $blog['blog_id'] ), 'unspamblog_' . $blog['blog_id'] ) ) . '">' . _x( 'Not Spam', 'site' ) . '</a>';
} else {
$actions['spam'] = '<a href="' . esc_url( wp_nonce_url( network_admin_url( 'sites.php?action=confirm&action2=spamblog&id=' . $blog['blog_id'] ), 'spamblog_' . $blog['blog_id'] ) ) . '">' . _x( 'Spam', 'site' ) . '</a>';
}
if ( current_user_can( 'delete_site', $blog['blog_id'] ) ) {
$actions['delete'] = '<a href="' . esc_url( wp_nonce_url( network_admin_url( 'sites.php?action=confirm&action2=deleteblog&id=' . $blog['blog_id'] ), 'deleteblog_' . $blog['blog_id'] ) ) . '">' . __( 'Delete' ) . '</a>';
}
}
$actions['visit'] = "<a href='" . esc_url( get_home_url( $blog['blog_id'], '/' ) ) . "' rel='bookmark'>" . __( 'Visit' ) . '</a>';
/**
* Filters the action links displayed for each site in the Sites list table.
*
* The 'Edit', 'Dashboard', 'Delete', and 'Visit' links are displayed by
* default for each site. The site's status determines whether to show the
* 'Activate' or 'Deactivate' link, 'Unarchive' or 'Archive' links, and
* 'Not Spam' or 'Spam' link for each site.
*
* @since 3.1.0
*
* @param string[] $actions An array of action links to be displayed.
* @param int $blog_id The site ID.
* @param string $blogname Site path, formatted depending on whether it is a sub-domain
* or subdirectory multisite installation.
*/
$actions = apply_filters( 'manage_sites_action_links', array_filter( $actions ), $blog['blog_id'], $blogname );
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_Dependency {} class \_WP\_Dependency {}
=========================
Class [\_WP\_Dependency](_wp_dependency)
Helper class to register a handle and associated data.
* [\_\_construct](_wp_dependency/__construct) — Setup dependencies.
* [add\_data](_wp_dependency/add_data) — Add handle data.
* [set\_translations](_wp_dependency/set_translations) — Sets the translation domain for this dependency.
File: `wp-includes/class-wp-dependency.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-dependency.php/)
```
class _WP_Dependency {
/**
* The handle name.
*
* @since 2.6.0
* @var string
*/
public $handle;
/**
* The handle source.
*
* @since 2.6.0
* @var string
*/
public $src;
/**
* An array of handle dependencies.
*
* @since 2.6.0
* @var string[]
*/
public $deps = array();
/**
* The handle version.
*
* Used for cache-busting.
*
* @since 2.6.0
* @var bool|string
*/
public $ver = false;
/**
* Additional arguments for the handle.
*
* @since 2.6.0
* @var array
*/
public $args = null; // Custom property, such as $in_footer or $media.
/**
* Extra data to supply to the handle.
*
* @since 2.6.0
* @var array
*/
public $extra = array();
/**
* Translation textdomain set for this dependency.
*
* @since 5.0.0
* @var string
*/
public $textdomain;
/**
* Translation path set for this dependency.
*
* @since 5.0.0
* @var string
*/
public $translations_path;
/**
* Setup dependencies.
*
* @since 2.6.0
* @since 5.3.0 Formalized the existing `...$args` parameter by adding it
* to the function signature.
*
* @param mixed ...$args Dependency information.
*/
public function __construct( ...$args ) {
list( $this->handle, $this->src, $this->deps, $this->ver, $this->args ) = $args;
if ( ! is_array( $this->deps ) ) {
$this->deps = array();
}
}
/**
* Add handle data.
*
* @since 2.6.0
*
* @param string $name The data key to add.
* @param mixed $data The data value to add.
* @return bool False if not scalar, true otherwise.
*/
public function add_data( $name, $data ) {
if ( ! is_scalar( $name ) ) {
return false;
}
$this->extra[ $name ] = $data;
return true;
}
/**
* Sets the translation domain for this dependency.
*
* @since 5.0.0
*
* @param string $domain The translation textdomain.
* @param string $path Optional. The full file path to the directory containing translation files.
* @return bool False if $domain is not a string, true otherwise.
*/
public function set_translations( $domain, $path = '' ) {
if ( ! is_string( $domain ) ) {
return false;
}
$this->textdomain = $domain;
$this->translations_path = $path;
return true;
}
}
```
| Version | Description |
| --- | --- |
| [2.6.0](https://developer.wordpress.org/reference/since/2.6.0/) | Introduced. |
wordpress class POP3 {} class POP3 {}
=============
mail\_fetch/setup.php
Copyright (c) 1999-2011 CDI ([email protected]) All Rights Reserved Modified by Philippe Mingo 2001-2009 [email protected] An RFC 1939 compliant wrapper class for the POP3 protocol.
Licensed under the GNU GPL. For full terms see the file COPYING.
POP3 class
* [\_\_construct](pop3/__construct) — PHP5 constructor.
* [apop](pop3/apop)
* [connect](pop3/connect)
* [delete](pop3/delete)
* [get](pop3/get)
* [is\_ok](pop3/is_ok)
* [last](pop3/last)
* [login](pop3/login)
* [parse\_banner](pop3/parse_banner)
* [pass](pop3/pass)
* [POP3](pop3/pop3) — PHP4 constructor.
* [pop\_list](pop3/pop_list)
* [popstat](pop3/popstat)
* [quit](pop3/quit)
* [reset](pop3/reset)
* [send\_cmd](pop3/send_cmd)
* [strip\_clf](pop3/strip_clf)
* [top](pop3/top)
* [uidl](pop3/uidl)
* [update\_timer](pop3/update_timer)
* [user](pop3/user)
File: `wp-includes/class-pop3.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-pop3.php/)
```
class POP3 {
var $ERROR = ''; // Error string.
var $TIMEOUT = 60; // Default timeout before giving up on a
// network operation.
var $COUNT = -1; // Mailbox msg count
var $BUFFER = 512; // Socket buffer for socket fgets() calls.
// Per RFC 1939 the returned line a POP3
// server can send is 512 bytes.
var $FP = ''; // The connection to the server's
// file descriptor
var $MAILSERVER = ''; // Set this to hard code the server name
var $DEBUG = FALSE; // set to true to echo pop3
// commands and responses to error_log
// this WILL log passwords!
var $BANNER = ''; // Holds the banner returned by the
// pop server - used for apop()
var $ALLOWAPOP = FALSE; // Allow or disallow apop()
// This must be set to true
// manually
/**
* PHP5 constructor.
*/
function __construct ( $server = '', $timeout = '' ) {
settype($this->BUFFER,"integer");
if( !empty($server) ) {
// Do not allow programs to alter MAILSERVER
// if it is already specified. They can get around
// this if they -really- want to, so don't count on it.
if(empty($this->MAILSERVER))
$this->MAILSERVER = $server;
}
if(!empty($timeout)) {
settype($timeout,"integer");
$this->TIMEOUT = $timeout;
set_time_limit($timeout);
}
return true;
}
/**
* PHP4 constructor.
*/
public function POP3( $server = '', $timeout = '' ) {
self::__construct( $server, $timeout );
}
function update_timer () {
set_time_limit($this->TIMEOUT);
return true;
}
function connect ($server, $port = 110) {
// Opens a socket to the specified server. Unless overridden,
// port defaults to 110. Returns true on success, false on fail
// If MAILSERVER is set, override $server with its value.
if (!isset($port) || !$port) {$port = 110;}
if(!empty($this->MAILSERVER))
$server = $this->MAILSERVER;
if(empty($server)){
$this->ERROR = "POP3 connect: " . _("No server specified");
unset($this->FP);
return false;
}
$fp = @fsockopen("$server", $port, $errno, $errstr);
if(!$fp) {
$this->ERROR = "POP3 connect: " . _("Error ") . "[$errno] [$errstr]";
unset($this->FP);
return false;
}
socket_set_blocking($fp,-1);
$this->update_timer();
$reply = fgets($fp,$this->BUFFER);
$reply = $this->strip_clf($reply);
if($this->DEBUG)
error_log("POP3 SEND [connect: $server] GOT [$reply]",0);
if(!$this->is_ok($reply)) {
$this->ERROR = "POP3 connect: " . _("Error ") . "[$reply]";
unset($this->FP);
return false;
}
$this->FP = $fp;
$this->BANNER = $this->parse_banner($reply);
return true;
}
function user ($user = "") {
// Sends the USER command, returns true or false
if( empty($user) ) {
$this->ERROR = "POP3 user: " . _("no login ID submitted");
return false;
} elseif(!isset($this->FP)) {
$this->ERROR = "POP3 user: " . _("connection not established");
return false;
} else {
$reply = $this->send_cmd("USER $user");
if(!$this->is_ok($reply)) {
$this->ERROR = "POP3 user: " . _("Error ") . "[$reply]";
return false;
} else
return true;
}
}
function pass ($pass = "") {
// Sends the PASS command, returns # of msgs in mailbox,
// returns false (undef) on Auth failure
if(empty($pass)) {
$this->ERROR = "POP3 pass: " . _("No password submitted");
return false;
} elseif(!isset($this->FP)) {
$this->ERROR = "POP3 pass: " . _("connection not established");
return false;
} else {
$reply = $this->send_cmd("PASS $pass");
if(!$this->is_ok($reply)) {
$this->ERROR = "POP3 pass: " . _("Authentication failed") . " [$reply]";
$this->quit();
return false;
} else {
// Auth successful.
$count = $this->last("count");
$this->COUNT = $count;
return $count;
}
}
}
function apop ($login,$pass) {
// Attempts an APOP login. If this fails, it'll
// try a standard login. YOUR SERVER MUST SUPPORT
// THE USE OF THE APOP COMMAND!
// (apop is optional per rfc1939)
if(!isset($this->FP)) {
$this->ERROR = "POP3 apop: " . _("No connection to server");
return false;
} elseif(!$this->ALLOWAPOP) {
$retVal = $this->login($login,$pass);
return $retVal;
} elseif(empty($login)) {
$this->ERROR = "POP3 apop: " . _("No login ID submitted");
return false;
} elseif(empty($pass)) {
$this->ERROR = "POP3 apop: " . _("No password submitted");
return false;
} else {
$banner = $this->BANNER;
if( (!$banner) or (empty($banner)) ) {
$this->ERROR = "POP3 apop: " . _("No server banner") . ' - ' . _("abort");
$retVal = $this->login($login,$pass);
return $retVal;
} else {
$AuthString = $banner;
$AuthString .= $pass;
$APOPString = md5($AuthString);
$cmd = "APOP $login $APOPString";
$reply = $this->send_cmd($cmd);
if(!$this->is_ok($reply)) {
$this->ERROR = "POP3 apop: " . _("apop authentication failed") . ' - ' . _("abort");
$retVal = $this->login($login,$pass);
return $retVal;
} else {
// Auth successful.
$count = $this->last("count");
$this->COUNT = $count;
return $count;
}
}
}
}
function login ($login = "", $pass = "") {
// Sends both user and pass. Returns # of msgs in mailbox or
// false on failure (or -1, if the error occurs while getting
// the number of messages.)
if( !isset($this->FP) ) {
$this->ERROR = "POP3 login: " . _("No connection to server");
return false;
} else {
$fp = $this->FP;
if( !$this->user( $login ) ) {
// Preserve the error generated by user()
return false;
} else {
$count = $this->pass($pass);
if( (!$count) || ($count == -1) ) {
// Preserve the error generated by last() and pass()
return false;
} else
return $count;
}
}
}
function top ($msgNum, $numLines = "0") {
// Gets the header and first $numLines of the msg body
// returns data in an array with each returned line being
// an array element. If $numLines is empty, returns
// only the header information, and none of the body.
if(!isset($this->FP)) {
$this->ERROR = "POP3 top: " . _("No connection to server");
return false;
}
$this->update_timer();
$fp = $this->FP;
$buffer = $this->BUFFER;
$cmd = "TOP $msgNum $numLines";
fwrite($fp, "TOP $msgNum $numLines\r\n");
$reply = fgets($fp, $buffer);
$reply = $this->strip_clf($reply);
if($this->DEBUG) {
@error_log("POP3 SEND [$cmd] GOT [$reply]",0);
}
if(!$this->is_ok($reply))
{
$this->ERROR = "POP3 top: " . _("Error ") . "[$reply]";
return false;
}
$count = 0;
$MsgArray = array();
$line = fgets($fp,$buffer);
while ( !preg_match('/^\.\r\n/',$line))
{
$MsgArray[$count] = $line;
$count++;
$line = fgets($fp,$buffer);
if(empty($line)) { break; }
}
return $MsgArray;
}
function pop_list ($msgNum = "") {
// If called with an argument, returns that msgs' size in octets
// No argument returns an associative array of undeleted
// msg numbers and their sizes in octets
if(!isset($this->FP))
{
$this->ERROR = "POP3 pop_list: " . _("No connection to server");
return false;
}
$fp = $this->FP;
$Total = $this->COUNT;
if( (!$Total) or ($Total == -1) )
{
return false;
}
if($Total == 0)
{
return array("0","0");
// return -1; // mailbox empty
}
$this->update_timer();
if(!empty($msgNum))
{
$cmd = "LIST $msgNum";
fwrite($fp,"$cmd\r\n");
$reply = fgets($fp,$this->BUFFER);
$reply = $this->strip_clf($reply);
if($this->DEBUG) {
@error_log("POP3 SEND [$cmd] GOT [$reply]",0);
}
if(!$this->is_ok($reply))
{
$this->ERROR = "POP3 pop_list: " . _("Error ") . "[$reply]";
return false;
}
list($junk,$num,$size) = preg_split('/\s+/',$reply);
return $size;
}
$cmd = "LIST";
$reply = $this->send_cmd($cmd);
if(!$this->is_ok($reply))
{
$reply = $this->strip_clf($reply);
$this->ERROR = "POP3 pop_list: " . _("Error ") . "[$reply]";
return false;
}
$MsgArray = array();
$MsgArray[0] = $Total;
for($msgC=1;$msgC <= $Total; $msgC++)
{
if($msgC > $Total) { break; }
$line = fgets($fp,$this->BUFFER);
$line = $this->strip_clf($line);
if(strpos($line, '.') === 0)
{
$this->ERROR = "POP3 pop_list: " . _("Premature end of list");
return false;
}
list($thisMsg,$msgSize) = preg_split('/\s+/',$line);
settype($thisMsg,"integer");
if($thisMsg != $msgC)
{
$MsgArray[$msgC] = "deleted";
}
else
{
$MsgArray[$msgC] = $msgSize;
}
}
return $MsgArray;
}
function get ($msgNum) {
// Retrieve the specified msg number. Returns an array
// where each line of the msg is an array element.
if(!isset($this->FP))
{
$this->ERROR = "POP3 get: " . _("No connection to server");
return false;
}
$this->update_timer();
$fp = $this->FP;
$buffer = $this->BUFFER;
$cmd = "RETR $msgNum";
$reply = $this->send_cmd($cmd);
if(!$this->is_ok($reply))
{
$this->ERROR = "POP3 get: " . _("Error ") . "[$reply]";
return false;
}
$count = 0;
$MsgArray = array();
$line = fgets($fp,$buffer);
while ( !preg_match('/^\.\r\n/',$line))
{
if ( $line[0] == '.' ) { $line = substr($line,1); }
$MsgArray[$count] = $line;
$count++;
$line = fgets($fp,$buffer);
if(empty($line)) { break; }
}
return $MsgArray;
}
function last ( $type = "count" ) {
// Returns the highest msg number in the mailbox.
// returns -1 on error, 0+ on success, if type != count
// results in a popstat() call (2 element array returned)
$last = -1;
if(!isset($this->FP))
{
$this->ERROR = "POP3 last: " . _("No connection to server");
return $last;
}
$reply = $this->send_cmd("STAT");
if(!$this->is_ok($reply))
{
$this->ERROR = "POP3 last: " . _("Error ") . "[$reply]";
return $last;
}
$Vars = preg_split('/\s+/',$reply);
$count = $Vars[1];
$size = $Vars[2];
settype($count,"integer");
settype($size,"integer");
if($type != "count")
{
return array($count,$size);
}
return $count;
}
function reset () {
// Resets the status of the remote server. This includes
// resetting the status of ALL msgs to not be deleted.
// This method automatically closes the connection to the server.
if(!isset($this->FP))
{
$this->ERROR = "POP3 reset: " . _("No connection to server");
return false;
}
$reply = $this->send_cmd("RSET");
if(!$this->is_ok($reply))
{
// The POP3 RSET command -never- gives a -ERR
// response - if it ever does, something truly
// wild is going on.
$this->ERROR = "POP3 reset: " . _("Error ") . "[$reply]";
@error_log("POP3 reset: ERROR [$reply]",0);
}
$this->quit();
return true;
}
function send_cmd ( $cmd = "" )
{
// Sends a user defined command string to the
// POP server and returns the results. Useful for
// non-compliant or custom POP servers.
// Do NOT includ the \r\n as part of your command
// string - it will be appended automatically.
// The return value is a standard fgets() call, which
// will read up to $this->BUFFER bytes of data, until it
// encounters a new line, or EOF, whichever happens first.
// This method works best if $cmd responds with only
// one line of data.
if(!isset($this->FP))
{
$this->ERROR = "POP3 send_cmd: " . _("No connection to server");
return false;
}
if(empty($cmd))
{
$this->ERROR = "POP3 send_cmd: " . _("Empty command string");
return "";
}
$fp = $this->FP;
$buffer = $this->BUFFER;
$this->update_timer();
fwrite($fp,"$cmd\r\n");
$reply = fgets($fp,$buffer);
$reply = $this->strip_clf($reply);
if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); }
return $reply;
}
function quit() {
// Closes the connection to the POP3 server, deleting
// any msgs marked as deleted.
if(!isset($this->FP))
{
$this->ERROR = "POP3 quit: " . _("connection does not exist");
return false;
}
$fp = $this->FP;
$cmd = "QUIT";
fwrite($fp,"$cmd\r\n");
$reply = fgets($fp,$this->BUFFER);
$reply = $this->strip_clf($reply);
if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); }
fclose($fp);
unset($this->FP);
return true;
}
function popstat () {
// Returns an array of 2 elements. The number of undeleted
// msgs in the mailbox, and the size of the mbox in octets.
$PopArray = $this->last("array");
if($PopArray == -1) { return false; }
if( (!$PopArray) or (empty($PopArray)) )
{
return false;
}
return $PopArray;
}
function uidl ($msgNum = "")
{
// Returns the UIDL of the msg specified. If called with
// no arguments, returns an associative array where each
// undeleted msg num is a key, and the msg's uidl is the element
// Array element 0 will contain the total number of msgs
if(!isset($this->FP)) {
$this->ERROR = "POP3 uidl: " . _("No connection to server");
return false;
}
$fp = $this->FP;
$buffer = $this->BUFFER;
if(!empty($msgNum)) {
$cmd = "UIDL $msgNum";
$reply = $this->send_cmd($cmd);
if(!$this->is_ok($reply))
{
$this->ERROR = "POP3 uidl: " . _("Error ") . "[$reply]";
return false;
}
list ($ok,$num,$myUidl) = preg_split('/\s+/',$reply);
return $myUidl;
} else {
$this->update_timer();
$UIDLArray = array();
$Total = $this->COUNT;
$UIDLArray[0] = $Total;
if ($Total < 1)
{
return $UIDLArray;
}
$cmd = "UIDL";
fwrite($fp, "UIDL\r\n");
$reply = fgets($fp, $buffer);
$reply = $this->strip_clf($reply);
if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); }
if(!$this->is_ok($reply))
{
$this->ERROR = "POP3 uidl: " . _("Error ") . "[$reply]";
return false;
}
$line = "";
$count = 1;
$line = fgets($fp,$buffer);
while ( !preg_match('/^\.\r\n/',$line)) {
list ($msg,$msgUidl) = preg_split('/\s+/',$line);
$msgUidl = $this->strip_clf($msgUidl);
if($count == $msg) {
$UIDLArray[$msg] = $msgUidl;
}
else
{
$UIDLArray[$count] = 'deleted';
}
$count++;
$line = fgets($fp,$buffer);
}
}
return $UIDLArray;
}
function delete ($msgNum = "") {
// Flags a specified msg as deleted. The msg will not
// be deleted until a quit() method is called.
if(!isset($this->FP))
{
$this->ERROR = "POP3 delete: " . _("No connection to server");
return false;
}
if(empty($msgNum))
{
$this->ERROR = "POP3 delete: " . _("No msg number submitted");
return false;
}
$reply = $this->send_cmd("DELE $msgNum");
if(!$this->is_ok($reply))
{
$this->ERROR = "POP3 delete: " . _("Command failed ") . "[$reply]";
return false;
}
return true;
}
// *********************************************************
// The following methods are internal to the class.
function is_ok ($cmd = "") {
// Return true or false on +OK or -ERR
if( empty($cmd) )
return false;
else
return( stripos($cmd, '+OK') !== false );
}
function strip_clf ($text = "") {
// Strips \r\n from server responses
if(empty($text))
return $text;
else {
$stripped = str_replace(array("\r","\n"),'',$text);
return $stripped;
}
}
function parse_banner ( $server_text ) {
$outside = true;
$banner = "";
$length = strlen($server_text);
for($count =0; $count < $length; $count++)
{
$digit = substr($server_text,$count,1);
if(!empty($digit)) {
if( (!$outside) && ($digit != '<') && ($digit != '>') )
{
$banner .= $digit;
}
if ($digit == '<')
{
$outside = false;
}
if($digit == '>')
{
$outside = true;
}
}
}
$banner = $this->strip_clf($banner); // Just in case
return "<$banner>";
}
} // End class
```
| programming_docs |
wordpress class Walker_Nav_Menu {} class Walker\_Nav\_Menu {}
==========================
Core class used to implement an HTML list of nav menu items.
* [Walker](walker)
* [end\_el](walker_nav_menu/end_el) — Ends the element output, if needed.
* [end\_lvl](walker_nav_menu/end_lvl) — Ends the list of after the elements are added.
* [start\_el](walker_nav_menu/start_el) — Starts the element output.
* [start\_lvl](walker_nav_menu/start_lvl) — Starts the list before the elements are added.
File: `wp-includes/class-walker-nav-menu.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-nav-menu.php/)
```
class Walker_Nav_Menu extends Walker {
/**
* What the class handles.
*
* @since 3.0.0
* @var string
*
* @see Walker::$tree_type
*/
public $tree_type = array( 'post_type', 'taxonomy', 'custom' );
/**
* Database fields to use.
*
* @since 3.0.0
* @todo Decouple this.
* @var string[]
*
* @see Walker::$db_fields
*/
public $db_fields = array(
'parent' => 'menu_item_parent',
'id' => 'db_id',
);
/**
* Starts the list before the elements are added.
*
* @since 3.0.0
*
* @see Walker::start_lvl()
*
* @param string $output Used to append additional content (passed by reference).
* @param int $depth Depth of menu item. Used for padding.
* @param stdClass $args An object of wp_nav_menu() arguments.
*/
public function start_lvl( &$output, $depth = 0, $args = null ) {
if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
$t = '';
$n = '';
} else {
$t = "\t";
$n = "\n";
}
$indent = str_repeat( $t, $depth );
// Default class.
$classes = array( 'sub-menu' );
/**
* Filters the CSS class(es) applied to a menu list element.
*
* @since 4.8.0
*
* @param string[] $classes Array of the CSS classes that are applied to the menu `<ul>` element.
* @param stdClass $args An object of `wp_nav_menu()` arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$class_names = implode( ' ', apply_filters( 'nav_menu_submenu_css_class', $classes, $args, $depth ) );
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
$output .= "{$n}{$indent}<ul$class_names>{$n}";
}
/**
* Ends the list of after the elements are added.
*
* @since 3.0.0
*
* @see Walker::end_lvl()
*
* @param string $output Used to append additional content (passed by reference).
* @param int $depth Depth of menu item. Used for padding.
* @param stdClass $args An object of wp_nav_menu() arguments.
*/
public function end_lvl( &$output, $depth = 0, $args = null ) {
if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
$t = '';
$n = '';
} else {
$t = "\t";
$n = "\n";
}
$indent = str_repeat( $t, $depth );
$output .= "$indent</ul>{$n}";
}
/**
* Starts the element output.
*
* @since 3.0.0
* @since 4.4.0 The {@see 'nav_menu_item_args'} filter was added.
* @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.
*
* @see Walker::start_el()
*
* @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 An object of wp_nav_menu() arguments.
* @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 ) {
// Restores the more descriptive, specific name for use within this method.
$menu_item = $data_object;
if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
$t = '';
$n = '';
} else {
$t = "\t";
$n = "\n";
}
$indent = ( $depth ) ? str_repeat( $t, $depth ) : '';
$classes = empty( $menu_item->classes ) ? array() : (array) $menu_item->classes;
$classes[] = 'menu-item-' . $menu_item->ID;
/**
* Filters the arguments for a single nav menu item.
*
* @since 4.4.0
*
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param WP_Post $menu_item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
*/
$args = apply_filters( 'nav_menu_item_args', $args, $menu_item, $depth );
/**
* Filters the CSS classes applied to a menu item's list item element.
*
* @since 3.0.0
* @since 4.1.0 The `$depth` parameter was added.
*
* @param string[] $classes Array of the CSS classes that are applied to the menu item's `<li>` element.
* @param WP_Post $menu_item The current menu item object.
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$class_names = implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $menu_item, $args, $depth ) );
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
/**
* Filters the ID attribute applied to a menu item's list item element.
*
* @since 3.0.1
* @since 4.1.0 The `$depth` parameter was added.
*
* @param string $menu_item_id The ID attribute applied to the menu item's `<li>` element.
* @param WP_Post $menu_item The current menu item.
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$id = apply_filters( 'nav_menu_item_id', 'menu-item-' . $menu_item->ID, $menu_item, $args, $depth );
$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';
$output .= $indent . '<li' . $id . $class_names . '>';
$atts = array();
$atts['title'] = ! empty( $menu_item->attr_title ) ? $menu_item->attr_title : '';
$atts['target'] = ! empty( $menu_item->target ) ? $menu_item->target : '';
if ( '_blank' === $menu_item->target && empty( $menu_item->xfn ) ) {
$atts['rel'] = 'noopener';
} else {
$atts['rel'] = $menu_item->xfn;
}
$atts['href'] = ! empty( $menu_item->url ) ? $menu_item->url : '';
$atts['aria-current'] = $menu_item->current ? 'page' : '';
/**
* Filters the HTML attributes applied to a menu item's anchor element.
*
* @since 3.6.0
* @since 4.1.0 The `$depth` parameter was added.
*
* @param array $atts {
* The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.
*
* @type string $title Title attribute.
* @type string $target Target attribute.
* @type string $rel The rel attribute.
* @type string $href The href attribute.
* @type string $aria-current The aria-current attribute.
* }
* @param WP_Post $menu_item The current menu item object.
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$atts = apply_filters( 'nav_menu_link_attributes', $atts, $menu_item, $args, $depth );
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( is_scalar( $value ) && '' !== $value && false !== $value ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
/** This filter is documented in wp-includes/post-template.php */
$title = apply_filters( 'the_title', $menu_item->title, $menu_item->ID );
/**
* Filters a menu item's title.
*
* @since 4.4.0
*
* @param string $title The menu item's title.
* @param WP_Post $menu_item The current menu item object.
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$title = apply_filters( 'nav_menu_item_title', $title, $menu_item, $args, $depth );
$item_output = $args->before;
$item_output .= '<a' . $attributes . '>';
$item_output .= $args->link_before . $title . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
/**
* Filters a menu item's starting output.
*
* The menu item's starting output only includes `$args->before`, the opening `<a>`,
* the menu item's title, the closing `</a>`, and `$args->after`. Currently, there is
* no filter for modifying the opening and closing `<li>` for a menu item.
*
* @since 3.0.0
*
* @param string $item_output The menu item's starting HTML output.
* @param WP_Post $menu_item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param stdClass $args An object of wp_nav_menu() arguments.
*/
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $menu_item, $depth, $args );
}
/**
* Ends the element output, if needed.
*
* @since 3.0.0
* @since 5.9.0 Renamed `$item` 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 WP_Post $data_object Menu item data object. Not used.
* @param int $depth Depth of page. Not Used.
* @param stdClass $args An object of wp_nav_menu() arguments.
*/
public function end_el( &$output, $data_object, $depth = 0, $args = null ) {
if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
$t = '';
$n = '';
} else {
$t = "\t";
$n = "\n";
}
$output .= "</li>{$n}";
}
}
```
| Uses | Description |
| --- | --- |
| [Walker](walker) wp-includes/class-wp-walker.php | A class for displaying various tree-like structures. |
| Used By | Description |
| --- | --- |
| [Walker\_Nav\_Menu\_Edit](walker_nav_menu_edit) wp-admin/includes/class-walker-nav-menu-edit.php | Create HTML list of nav menu input items. |
| [Walker\_Nav\_Menu\_Checklist](walker_nav_menu_checklist) wp-admin/includes/class-walker-nav-menu-checklist.php | Create HTML list of nav menu input items. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress class WP_Links_List_Table {} class WP\_Links\_List\_Table {}
===============================
Core class used to implement displaying links in a list table.
* [WP\_List\_Table](wp_list_table)
* [\_\_construct](wp_links_list_table/__construct) — Constructor.
* [ajax\_user\_can](wp_links_list_table/ajax_user_can)
* [column\_categories](wp_links_list_table/column_categories) — Handles the link categories column output.
* [column\_cb](wp_links_list_table/column_cb) — Handles the checkbox column output.
* [column\_default](wp_links_list_table/column_default) — Handles the default column output.
* [column\_name](wp_links_list_table/column_name) — Handles the link name column output.
* [column\_rating](wp_links_list_table/column_rating) — Handles the link rating column output.
* [column\_rel](wp_links_list_table/column_rel) — Handles the link relation column output.
* [column\_url](wp_links_list_table/column_url) — Handles the link URL column output.
* [column\_visible](wp_links_list_table/column_visible) — Handles the link visibility column output.
* [display\_rows](wp_links_list_table/display_rows)
* [extra\_tablenav](wp_links_list_table/extra_tablenav)
* [get\_bulk\_actions](wp_links_list_table/get_bulk_actions)
* [get\_columns](wp_links_list_table/get_columns)
* [get\_default\_primary\_column\_name](wp_links_list_table/get_default_primary_column_name) — Get the name of the default primary column.
* [get\_sortable\_columns](wp_links_list_table/get_sortable_columns)
* [handle\_row\_actions](wp_links_list_table/handle_row_actions) — Generates and displays row action links.
* [no\_items](wp_links_list_table/no_items)
* [prepare\_items](wp_links_list_table/prepare_items)
File: `wp-admin/includes/class-wp-links-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-links-list-table.php/)
```
class WP_Links_List_Table extends WP_List_Table {
/**
* 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(
'plural' => 'bookmarks',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
}
/**
* @return bool
*/
public function ajax_user_can() {
return current_user_can( 'manage_links' );
}
/**
* @global int $cat_id
* @global string $s
* @global string $orderby
* @global string $order
*/
public function prepare_items() {
global $cat_id, $s, $orderby, $order;
wp_reset_vars( array( 'action', 'cat_id', 'link_id', 'orderby', 'order', 's' ) );
$args = array(
'hide_invisible' => 0,
'hide_empty' => 0,
);
if ( 'all' !== $cat_id ) {
$args['category'] = $cat_id;
}
if ( ! empty( $s ) ) {
$args['search'] = $s;
}
if ( ! empty( $orderby ) ) {
$args['orderby'] = $orderby;
}
if ( ! empty( $order ) ) {
$args['order'] = $order;
}
$this->items = get_bookmarks( $args );
}
/**
*/
public function no_items() {
_e( 'No links found.' );
}
/**
* @return array
*/
protected function get_bulk_actions() {
$actions = array();
$actions['delete'] = __( 'Delete' );
return $actions;
}
/**
* @global int $cat_id
* @param string $which
*/
protected function extra_tablenav( $which ) {
global $cat_id;
if ( 'top' !== $which ) {
return;
}
?>
<div class="alignleft actions">
<?php
$dropdown_options = array(
'selected' => $cat_id,
'name' => 'cat_id',
'taxonomy' => 'link_category',
'show_option_all' => get_taxonomy( 'link_category' )->labels->all_items,
'hide_empty' => true,
'hierarchical' => 1,
'show_count' => 0,
'orderby' => 'name',
);
echo '<label class="screen-reader-text" for="cat_id">' . get_taxonomy( 'link_category' )->labels->filter_by_item . '</label>';
wp_dropdown_categories( $dropdown_options );
submit_button( __( 'Filter' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) );
?>
</div>
<?php
}
/**
* @return array
*/
public function get_columns() {
return array(
'cb' => '<input type="checkbox" />',
'name' => _x( 'Name', 'link name' ),
'url' => __( 'URL' ),
'categories' => __( 'Categories' ),
'rel' => __( 'Relationship' ),
'visible' => __( 'Visible' ),
'rating' => __( 'Rating' ),
);
}
/**
* @return array
*/
protected function get_sortable_columns() {
return array(
'name' => 'name',
'url' => 'url',
'visible' => 'visible',
'rating' => 'rating',
);
}
/**
* Get 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';
}
/**
* Handles the checkbox column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$link` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param object $item The current link object.
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$link = $item;
?>
<label class="screen-reader-text" for="cb-select-<?php echo $link->link_id; ?>">
<?php
/* translators: %s: Link name. */
printf( __( 'Select %s' ), $link->link_name );
?>
</label>
<input type="checkbox" name="linkcheck[]" id="cb-select-<?php echo $link->link_id; ?>" value="<?php echo esc_attr( $link->link_id ); ?>" />
<?php
}
/**
* Handles the link name column output.
*
* @since 4.3.0
*
* @param object $link The current link object.
*/
public function column_name( $link ) {
$edit_link = get_edit_bookmark_link( $link );
printf(
'<strong><a class="row-title" href="%s" aria-label="%s">%s</a></strong>',
$edit_link,
/* translators: %s: Link name. */
esc_attr( sprintf( __( 'Edit “%s”' ), $link->link_name ) ),
$link->link_name
);
}
/**
* Handles the link URL column output.
*
* @since 4.3.0
*
* @param object $link The current link object.
*/
public function column_url( $link ) {
$short_url = url_shorten( $link->link_url );
echo "<a href='$link->link_url'>$short_url</a>";
}
/**
* Handles the link categories column output.
*
* @since 4.3.0
*
* @global int $cat_id
*
* @param object $link The current link object.
*/
public function column_categories( $link ) {
global $cat_id;
$cat_names = array();
foreach ( $link->link_category as $category ) {
$cat = get_term( $category, 'link_category', OBJECT, 'display' );
if ( is_wp_error( $cat ) ) {
echo $cat->get_error_message();
}
$cat_name = $cat->name;
if ( (int) $cat_id !== $category ) {
$cat_name = "<a href='link-manager.php?cat_id=$category'>$cat_name</a>";
}
$cat_names[] = $cat_name;
}
echo implode( ', ', $cat_names );
}
/**
* Handles the link relation column output.
*
* @since 4.3.0
*
* @param object $link The current link object.
*/
public function column_rel( $link ) {
echo empty( $link->link_rel ) ? '<br />' : $link->link_rel;
}
/**
* Handles the link visibility column output.
*
* @since 4.3.0
*
* @param object $link The current link object.
*/
public function column_visible( $link ) {
if ( 'Y' === $link->link_visible ) {
_e( 'Yes' );
} else {
_e( 'No' );
}
}
/**
* Handles the link rating column output.
*
* @since 4.3.0
*
* @param object $link The current link object.
*/
public function column_rating( $link ) {
echo $link->link_rating;
}
/**
* Handles the default column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$link` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param object $item Link object.
* @param string $column_name Current column name.
*/
public function column_default( $item, $column_name ) {
/**
* Fires for each registered custom link column.
*
* @since 2.1.0
*
* @param string $column_name Name of the custom column.
* @param int $link_id Link ID.
*/
do_action( 'manage_link_custom_column', $column_name, $item->link_id );
}
public function display_rows() {
foreach ( $this->items as $link ) {
$link = sanitize_bookmark( $link );
$link->link_name = esc_attr( $link->link_name );
$link->link_category = wp_get_link_cats( $link->link_id );
?>
<tr id="link-<?php echo $link->link_id; ?>">
<?php $this->single_row_columns( $link ); ?>
</tr>
<?php
}
}
/**
* Generates and displays row action links.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$link` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param object $item Link being acted upon.
* @param string $column_name Current column name.
* @param string $primary Primary column name.
* @return string Row actions output for links, 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.
$link = $item;
$edit_link = get_edit_bookmark_link( $link );
$actions = array();
$actions['edit'] = '<a href="' . $edit_link . '">' . __( 'Edit' ) . '</a>';
$actions['delete'] = sprintf(
'<a class="submitdelete" href="%s" onclick="return confirm( \'%s\' );">%s</a>',
wp_nonce_url( "link.php?action=delete&link_id=$link->link_id", 'delete-bookmark_' . $link->link_id ),
/* translators: %s: Link name. */
esc_js( sprintf( __( "You are about to delete this link '%s'\n 'Cancel' to stop, 'OK' to delete." ), $link->link_name ) ),
__( 'Delete' )
);
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_Textdomain_Registry {} class WP\_Textdomain\_Registry {}
=================================
Core class used for registering text domains.
* [get](wp_textdomain_registry/get) — Returns the languages directory path for a specific domain and locale.
* [get\_path\_from\_lang\_dir](wp_textdomain_registry/get_path_from_lang_dir) — Gets the path to the language directory for the current locale.
* [has](wp_textdomain_registry/has) — Determines whether any MO file paths are available for the domain.
* [set](wp_textdomain_registry/set) — Sets the language directory path for a specific domain and locale.
* [set\_cached\_mo\_files](wp_textdomain_registry/set_cached_mo_files) — Reads and caches all available MO files from a given directory.
* [set\_custom\_path](wp_textdomain_registry/set_custom_path) — Sets the custom path to the plugin's/theme's languages directory.
File: `wp-includes/class-wp-textdomain-registry.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-textdomain-registry.php/)
```
class WP_Textdomain_Registry {
/**
* List of domains and all their language directory paths for each locale.
*
* @since 6.1.0
*
* @var array
*/
protected $all = array();
/**
* List of domains and their language directory path for the current (most recent) locale.
*
* @since 6.1.0
*
* @var array
*/
protected $current = array();
/**
* List of domains and their custom language directory paths.
*
* @see load_plugin_textdomain()
* @see load_theme_textdomain()
*
* @since 6.1.0
*
* @var array
*/
protected $custom_paths = array();
/**
* Holds a cached list of available .mo files to improve performance.
*
* @since 6.1.0
*
* @var array
*/
protected $cached_mo_files;
/**
* Returns the languages directory path for a specific domain and locale.
*
* @since 6.1.0
*
* @param string $domain Text domain.
* @param string $locale Locale.
*
* @return string|false MO file path or false if there is none available.
*/
public function get( $domain, $locale ) {
if ( isset( $this->all[ $domain ][ $locale ] ) ) {
return $this->all[ $domain ][ $locale ];
}
return $this->get_path_from_lang_dir( $domain, $locale );
}
/**
* Determines whether any MO file paths are available for the domain.
*
* This is the case if a path has been set for the current locale,
* or if there is no information stored yet, in which case
* {@see _load_textdomain_just_in_time()} will fetch the information first.
*
* @since 6.1.0
*
* @param string $domain Text domain.
* @return bool Whether any MO file paths are available for the domain.
*/
public function has( $domain ) {
return ! empty( $this->current[ $domain ] ) || empty( $this->all[ $domain ] );
}
/**
* Sets the language directory path for a specific domain and locale.
*
* Also sets the 'current' property for direct access
* to the path for the current (most recent) locale.
*
* @since 6.1.0
*
* @param string $domain Text domain.
* @param string $locale Locale.
* @param string|false $path Language directory path or false if there is none available.
*/
public function set( $domain, $locale, $path ) {
$this->all[ $domain ][ $locale ] = $path ? trailingslashit( $path ) : false;
$this->current[ $domain ] = $this->all[ $domain ][ $locale ];
}
/**
* Sets the custom path to the plugin's/theme's languages directory.
*
* Used by {@see load_plugin_textdomain()} and {@see load_theme_textdomain()}.
*
* @param string $domain Text domain.
* @param string $path Language directory path.
*/
public function set_custom_path( $domain, $path ) {
$this->custom_paths[ $domain ] = untrailingslashit( $path );
}
/**
* Gets the path to the language directory for the current locale.
*
* Checks the plugins and themes language directories as well as any
* custom directory set via {@see load_plugin_textdomain()} or {@see load_theme_textdomain()}.
*
* @since 6.1.0
*
* @see _get_path_to_translation_from_lang_dir()
*
* @param string $domain Text domain.
* @param string $locale Locale.
* @return string|false Language directory path or false if there is none available.
*/
private function get_path_from_lang_dir( $domain, $locale ) {
$locations = array(
WP_LANG_DIR . '/plugins',
WP_LANG_DIR . '/themes',
);
if ( isset( $this->custom_paths[ $domain ] ) ) {
$locations[] = $this->custom_paths[ $domain ];
}
$mofile = "$domain-$locale.mo";
foreach ( $locations as $location ) {
if ( ! isset( $this->cached_mo_files[ $location ] ) ) {
$this->set_cached_mo_files( $location );
}
$path = $location . '/' . $mofile;
if ( in_array( $path, $this->cached_mo_files[ $location ], true ) ) {
$this->set( $domain, $locale, $location );
return trailingslashit( $location );
}
}
// If no path is found for the given locale and a custom path has been set
// using load_plugin_textdomain/load_theme_textdomain, use that one.
if ( 'en_US' !== $locale && isset( $this->custom_paths[ $domain ] ) ) {
$path = trailingslashit( $this->custom_paths[ $domain ] );
$this->set( $domain, $locale, $path );
return $path;
}
$this->set( $domain, $locale, false );
return false;
}
/**
* Reads and caches all available MO files from a given directory.
*
* @since 6.1.0
*
* @param string $path Language directory path.
*/
private function set_cached_mo_files( $path ) {
$this->cached_mo_files[ $path ] = array();
$mo_files = glob( $path . '/*.mo' );
if ( $mo_files ) {
$this->cached_mo_files[ $path ] = $mo_files;
}
}
}
```
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress class WP_Sitemaps {} class WP\_Sitemaps {}
=====================
Class [WP\_Sitemaps](wp_sitemaps).
* [\_\_construct](wp_sitemaps/__construct) — WP\_Sitemaps constructor.
* [add\_robots](wp_sitemaps/add_robots) — Adds the sitemap index to robots.txt.
* [init](wp_sitemaps/init) — Initiates all sitemap functionality.
* [redirect\_sitemapxml](wp_sitemaps/redirect_sitemapxml) — Redirects a URL to the wp-sitemap.xml
* [register\_rewrites](wp_sitemaps/register_rewrites) — Registers sitemap rewrite tags and routing rules.
* [register\_sitemaps](wp_sitemaps/register_sitemaps) — Registers and sets up the functionality for all supported sitemaps.
* [render\_sitemaps](wp_sitemaps/render_sitemaps) — Renders sitemap templates based on rewrite rules.
* [sitemaps\_enabled](wp_sitemaps/sitemaps_enabled) — Determines whether sitemaps are enabled or not.
File: `wp-includes/sitemaps/class-wp-sitemaps.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/sitemaps/class-wp-sitemaps.php/)
```
class WP_Sitemaps {
/**
* The main index of supported sitemaps.
*
* @since 5.5.0
*
* @var WP_Sitemaps_Index
*/
public $index;
/**
* The main registry of supported sitemaps.
*
* @since 5.5.0
*
* @var WP_Sitemaps_Registry
*/
public $registry;
/**
* An instance of the renderer class.
*
* @since 5.5.0
*
* @var WP_Sitemaps_Renderer
*/
public $renderer;
/**
* WP_Sitemaps constructor.
*
* @since 5.5.0
*/
public function __construct() {
$this->registry = new WP_Sitemaps_Registry();
$this->renderer = new WP_Sitemaps_Renderer();
$this->index = new WP_Sitemaps_Index( $this->registry );
}
/**
* Initiates all sitemap functionality.
*
* If sitemaps are disabled, only the rewrite rules will be registered
* by this method, in order to properly send 404s.
*
* @since 5.5.0
*/
public function init() {
// These will all fire on the init hook.
$this->register_rewrites();
add_action( 'template_redirect', array( $this, 'render_sitemaps' ) );
if ( ! $this->sitemaps_enabled() ) {
return;
}
$this->register_sitemaps();
// Add additional action callbacks.
add_filter( 'pre_handle_404', array( $this, 'redirect_sitemapxml' ), 10, 2 );
add_filter( 'robots_txt', array( $this, 'add_robots' ), 0, 2 );
}
/**
* Determines whether sitemaps are enabled or not.
*
* @since 5.5.0
*
* @return bool Whether sitemaps are enabled.
*/
public function sitemaps_enabled() {
$is_enabled = (bool) get_option( 'blog_public' );
/**
* Filters whether XML Sitemaps are enabled or not.
*
* When XML Sitemaps are disabled via this filter, rewrite rules are still
* in place to ensure a 404 is returned.
*
* @see WP_Sitemaps::register_rewrites()
*
* @since 5.5.0
*
* @param bool $is_enabled Whether XML Sitemaps are enabled or not. Defaults
* to true for public sites.
*/
return (bool) apply_filters( 'wp_sitemaps_enabled', $is_enabled );
}
/**
* Registers and sets up the functionality for all supported sitemaps.
*
* @since 5.5.0
*/
public function register_sitemaps() {
$providers = array(
'posts' => new WP_Sitemaps_Posts(),
'taxonomies' => new WP_Sitemaps_Taxonomies(),
'users' => new WP_Sitemaps_Users(),
);
/* @var WP_Sitemaps_Provider $provider */
foreach ( $providers as $name => $provider ) {
$this->registry->add_provider( $name, $provider );
}
}
/**
* Registers sitemap rewrite tags and routing rules.
*
* @since 5.5.0
*/
public function register_rewrites() {
// Add rewrite tags.
add_rewrite_tag( '%sitemap%', '([^?]+)' );
add_rewrite_tag( '%sitemap-subtype%', '([^?]+)' );
// Register index route.
add_rewrite_rule( '^wp-sitemap\.xml$', 'index.php?sitemap=index', 'top' );
// Register rewrites for the XSL stylesheet.
add_rewrite_tag( '%sitemap-stylesheet%', '([^?]+)' );
add_rewrite_rule( '^wp-sitemap\.xsl$', 'index.php?sitemap-stylesheet=sitemap', 'top' );
add_rewrite_rule( '^wp-sitemap-index\.xsl$', 'index.php?sitemap-stylesheet=index', 'top' );
// Register routes for providers.
add_rewrite_rule(
'^wp-sitemap-([a-z]+?)-([a-z\d_-]+?)-(\d+?)\.xml$',
'index.php?sitemap=$matches[1]&sitemap-subtype=$matches[2]&paged=$matches[3]',
'top'
);
add_rewrite_rule(
'^wp-sitemap-([a-z]+?)-(\d+?)\.xml$',
'index.php?sitemap=$matches[1]&paged=$matches[2]',
'top'
);
}
/**
* Renders sitemap templates based on rewrite rules.
*
* @since 5.5.0
*
* @global WP_Query $wp_query WordPress Query object.
*/
public function render_sitemaps() {
global $wp_query;
$sitemap = sanitize_text_field( get_query_var( 'sitemap' ) );
$object_subtype = sanitize_text_field( get_query_var( 'sitemap-subtype' ) );
$stylesheet_type = sanitize_text_field( get_query_var( 'sitemap-stylesheet' ) );
$paged = absint( get_query_var( 'paged' ) );
// Bail early if this isn't a sitemap or stylesheet route.
if ( ! ( $sitemap || $stylesheet_type ) ) {
return;
}
if ( ! $this->sitemaps_enabled() ) {
$wp_query->set_404();
status_header( 404 );
return;
}
// Render stylesheet if this is stylesheet route.
if ( $stylesheet_type ) {
$stylesheet = new WP_Sitemaps_Stylesheet();
$stylesheet->render_stylesheet( $stylesheet_type );
exit;
}
// Render the index.
if ( 'index' === $sitemap ) {
$sitemap_list = $this->index->get_sitemap_list();
$this->renderer->render_index( $sitemap_list );
exit;
}
$provider = $this->registry->get_provider( $sitemap );
if ( ! $provider ) {
return;
}
if ( empty( $paged ) ) {
$paged = 1;
}
$url_list = $provider->get_url_list( $paged, $object_subtype );
// Force a 404 and bail early if no URLs are present.
if ( empty( $url_list ) ) {
$wp_query->set_404();
status_header( 404 );
return;
}
$this->renderer->render_sitemap( $url_list );
exit;
}
/**
* Redirects a URL to the wp-sitemap.xml
*
* @since 5.5.0
*
* @param bool $bypass Pass-through of the pre_handle_404 filter value.
* @param WP_Query $query The WP_Query object.
* @return bool Bypass value.
*/
public function redirect_sitemapxml( $bypass, $query ) {
// If a plugin has already utilized the pre_handle_404 function, return without action to avoid conflicts.
if ( $bypass ) {
return $bypass;
}
// 'pagename' is for most permalink types, name is for when the %postname% is used as a top-level field.
if ( 'sitemap-xml' === $query->get( 'pagename' )
|| 'sitemap-xml' === $query->get( 'name' )
) {
wp_safe_redirect( $this->index->get_index_url() );
exit();
}
return $bypass;
}
/**
* Adds the sitemap index to robots.txt.
*
* @since 5.5.0
*
* @param string $output robots.txt output.
* @param bool $public Whether the site is public.
* @return string The robots.txt output.
*/
public function add_robots( $output, $public ) {
if ( $public ) {
$output .= "\nSitemap: " . esc_url( $this->index->get_index_url() ) . "\n";
}
return $output;
}
}
```
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress class WP_REST_Global_Styles_Controller {} class WP\_REST\_Global\_Styles\_Controller {}
=============================================
Base Global Styles REST API Controller.
* [\_\_construct](wp_rest_global_styles_controller/__construct) — Constructor.
* [\_sanitize\_global\_styles\_callback](wp_rest_global_styles_controller/_sanitize_global_styles_callback) — Sanitize the global styles ID or stylesheet to decode endpoint.
* [check\_read\_permission](wp_rest_global_styles_controller/check_read_permission) — Checks if a global style can be read.
* [check\_update\_permission](wp_rest_global_styles_controller/check_update_permission) — Checks if a global style can be edited.
* [get\_available\_actions](wp_rest_global_styles_controller/get_available_actions) — Get the link relations available for the post and current user.
* [get\_collection\_params](wp_rest_global_styles_controller/get_collection_params) — Retrieves the query params for the global styles collection.
* [get\_item](wp_rest_global_styles_controller/get_item) — Returns the given global styles config.
* [get\_item\_permissions\_check](wp_rest_global_styles_controller/get_item_permissions_check) — Checks if a given request has access to read a single global style.
* [get\_item\_schema](wp_rest_global_styles_controller/get_item_schema) — Retrieves the global styles type' schema, conforming to JSON Schema.
* [get\_post](wp_rest_global_styles_controller/get_post) — Get the post, if the ID is valid.
* [get\_theme\_item](wp_rest_global_styles_controller/get_theme_item) — Returns the given theme global styles config.
* [get\_theme\_item\_permissions\_check](wp_rest_global_styles_controller/get_theme_item_permissions_check) — Checks if a given request has access to read a single theme global styles config.
* [get\_theme\_items](wp_rest_global_styles_controller/get_theme_items) — Returns the given theme global styles variations.
* [get\_theme\_items\_permissions\_check](wp_rest_global_styles_controller/get_theme_items_permissions_check) — Checks if a given request has access to read a single theme global styles config.
* [prepare\_item\_for\_database](wp_rest_global_styles_controller/prepare_item_for_database) — Prepares a single global styles config for update.
* [prepare\_item\_for\_response](wp_rest_global_styles_controller/prepare_item_for_response) — Prepare a global styles config output for response.
* [prepare\_links](wp_rest_global_styles_controller/prepare_links) — Prepares links for the request.
* [protected\_title\_format](wp_rest_global_styles_controller/protected_title_format) — Overwrites the default protected title format.
* [register\_routes](wp_rest_global_styles_controller/register_routes) — Registers the controllers routes.
* [update\_item](wp_rest_global_styles_controller/update_item) — Updates a single global style config.
* [update\_item\_permissions\_check](wp_rest_global_styles_controller/update_item_permissions_check) — Checks if a given request has access to write a single global styles config.
File: `wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php/)
```
class WP_REST_Global_Styles_Controller extends WP_REST_Controller {
/**
* Post type.
*
* @since 5.9.0
* @var string
*/
protected $post_type;
/**
* Constructor.
* @since 5.9.0
*/
public function __construct() {
$this->namespace = 'wp/v2';
$this->rest_base = 'global-styles';
$this->post_type = 'wp_global_styles';
}
/**
* Registers the controllers routes.
*
* @since 5.9.0
*
* @return void
*/
public function register_routes() {
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/themes/(?P<stylesheet>[\/\s%\w\.\(\)\[\]\@_\-]+)/variations',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_theme_items' ),
'permission_callback' => array( $this, 'get_theme_items_permissions_check' ),
'args' => array(
'stylesheet' => array(
'description' => __( 'The theme identifier' ),
'type' => 'string',
),
),
),
)
);
// List themes global styles.
register_rest_route(
$this->namespace,
// The route.
sprintf(
'/%s/themes/(?P<stylesheet>%s)',
$this->rest_base,
// Matches theme's directory: `/themes/<subdirectory>/<theme>/` or `/themes/<theme>/`.
// Excludes invalid directory name characters: `/:<>*?"|`.
'[^\/:<>\*\?"\|]+(?:\/[^\/:<>\*\?"\|]+)?'
),
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_theme_item' ),
'permission_callback' => array( $this, 'get_theme_item_permissions_check' ),
'args' => array(
'stylesheet' => array(
'description' => __( 'The theme identifier' ),
'type' => 'string',
'sanitize_callback' => array( $this, '_sanitize_global_styles_callback' ),
),
),
),
)
);
// Lists/updates a single global style variation based on the given id.
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/(?P<id>[\/\w-]+)',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => array( $this, 'get_item_permissions_check' ),
'args' => array(
'id' => array(
'description' => __( 'The id of a template' ),
'type' => 'string',
'sanitize_callback' => array( $this, '_sanitize_global_styles_callback' ),
),
),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'update_item' ),
'permission_callback' => array( $this, 'update_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
),
'schema' => array( $this, 'get_public_item_schema' ),
)
);
}
/**
* Sanitize the global styles ID or stylesheet to decode endpoint.
* For example, `wp/v2/global-styles/twentytwentytwo%200.4.0`
* would be decoded to `twentytwentytwo 0.4.0`.
*
* @since 5.9.0
*
* @param string $id_or_stylesheet Global styles ID or stylesheet.
* @return string Sanitized global styles ID or stylesheet.
*/
public function _sanitize_global_styles_callback( $id_or_stylesheet ) {
return urldecode( $id_or_stylesheet );
}
/**
* Get the post, if the ID is valid.
*
* @since 5.9.0
*
* @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_global_styles_not_found',
__( 'No global styles config exist with that id.' ),
array( 'status' => 404 )
);
$id = (int) $id;
if ( $id <= 0 ) {
return $error;
}
$post = get_post( $id );
if ( empty( $post ) || empty( $post->ID ) || $this->post_type !== $post->post_type ) {
return $error;
}
return $post;
}
/**
* Checks if a given request has access to read a single global style.
*
* @since 5.9.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 ) {
$post = $this->get_post( $request['id'] );
if ( is_wp_error( $post ) ) {
return $post;
}
if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) {
return new WP_Error(
'rest_forbidden_context',
__( 'Sorry, you are not allowed to edit this global style.' ),
array( 'status' => rest_authorization_required_code() )
);
}
if ( ! $this->check_read_permission( $post ) ) {
return new WP_Error(
'rest_cannot_view',
__( 'Sorry, you are not allowed to view this global style.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
/**
* Checks if a global style can be read.
*
* @since 5.9.0
*
* @param WP_Post $post Post object.
* @return bool Whether the post can be read.
*/
protected function check_read_permission( $post ) {
return current_user_can( 'read_post', $post->ID );
}
/**
* Returns the given global styles config.
*
* @since 5.9.0
*
* @param WP_REST_Request $request The request instance.
*
* @return WP_REST_Response|WP_Error
*/
public function get_item( $request ) {
$post = $this->get_post( $request['id'] );
if ( is_wp_error( $post ) ) {
return $post;
}
return $this->prepare_item_for_response( $post, $request );
}
/**
* Checks if a given request has access to write a single global styles config.
*
* @since 5.9.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 ) {
$post = $this->get_post( $request['id'] );
if ( is_wp_error( $post ) ) {
return $post;
}
if ( $post && ! $this->check_update_permission( $post ) ) {
return new WP_Error(
'rest_cannot_edit',
__( 'Sorry, you are not allowed to edit this global style.' ),
array( 'status' => rest_authorization_required_code() )
);
}
return true;
}
/**
* Checks if a global style can be edited.
*
* @since 5.9.0
*
* @param WP_Post $post Post object.
* @return bool Whether the post can be edited.
*/
protected function check_update_permission( $post ) {
return current_user_can( 'edit_post', $post->ID );
}
/**
* Updates a single global style config.
*
* @since 5.9.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 ) {
$post_before = $this->get_post( $request['id'] );
if ( is_wp_error( $post_before ) ) {
return $post_before;
}
$changes = $this->prepare_item_for_database( $request );
$result = wp_update_post( wp_slash( (array) $changes ), true, false );
if ( is_wp_error( $result ) ) {
return $result;
}
$post = get_post( $request['id'] );
$fields_update = $this->update_additional_fields_for_object( $post, $request );
if ( is_wp_error( $fields_update ) ) {
return $fields_update;
}
wp_after_insert_post( $post, true, $post_before );
$response = $this->prepare_item_for_response( $post, $request );
return rest_ensure_response( $response );
}
/**
* Prepares a single global styles config for update.
*
* @since 5.9.0
*
* @param WP_REST_Request $request Request object.
* @return stdClass Changes to pass to wp_update_post.
*/
protected function prepare_item_for_database( $request ) {
$changes = new stdClass();
$changes->ID = $request['id'];
$post = get_post( $request['id'] );
$existing_config = array();
if ( $post ) {
$existing_config = json_decode( $post->post_content, true );
$json_decoding_error = json_last_error();
if ( JSON_ERROR_NONE !== $json_decoding_error || ! isset( $existing_config['isGlobalStylesUserThemeJSON'] ) ||
! $existing_config['isGlobalStylesUserThemeJSON'] ) {
$existing_config = array();
}
}
if ( isset( $request['styles'] ) || isset( $request['settings'] ) ) {
$config = array();
if ( isset( $request['styles'] ) ) {
$config['styles'] = $request['styles'];
} elseif ( isset( $existing_config['styles'] ) ) {
$config['styles'] = $existing_config['styles'];
}
if ( isset( $request['settings'] ) ) {
$config['settings'] = $request['settings'];
} elseif ( isset( $existing_config['settings'] ) ) {
$config['settings'] = $existing_config['settings'];
}
$config['isGlobalStylesUserThemeJSON'] = true;
$config['version'] = WP_Theme_JSON::LATEST_SCHEMA;
$changes->post_content = wp_json_encode( $config );
}
// Post title.
if ( isset( $request['title'] ) ) {
if ( is_string( $request['title'] ) ) {
$changes->post_title = $request['title'];
} elseif ( ! empty( $request['title']['raw'] ) ) {
$changes->post_title = $request['title']['raw'];
}
}
return $changes;
}
/**
* Prepare a global styles config output for response.
*
* @since 5.9.0
*
* @param WP_Post $post Global Styles post object.
* @param WP_REST_Request $request Request object.
* @return WP_REST_Response Response object.
*/
public function prepare_item_for_response( $post, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
$raw_config = json_decode( $post->post_content, true );
$is_global_styles_user_theme_json = isset( $raw_config['isGlobalStylesUserThemeJSON'] ) && true === $raw_config['isGlobalStylesUserThemeJSON'];
$config = array();
if ( $is_global_styles_user_theme_json ) {
$config = ( new WP_Theme_JSON( $raw_config, 'custom' ) )->get_raw_data();
}
// Base fields for every post.
$data = array();
$fields = $this->get_fields_for_response( $request );
if ( rest_is_field_included( 'id', $fields ) ) {
$data['id'] = $post->ID;
}
if ( rest_is_field_included( 'title', $fields ) ) {
$data['title'] = array();
}
if ( rest_is_field_included( 'title.raw', $fields ) ) {
$data['title']['raw'] = $post->post_title;
}
if ( rest_is_field_included( 'title.rendered', $fields ) ) {
add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
$data['title']['rendered'] = get_the_title( $post->ID );
remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) );
}
if ( rest_is_field_included( 'settings', $fields ) ) {
$data['settings'] = ! empty( $config['settings'] ) && $is_global_styles_user_theme_json ? $config['settings'] : new stdClass();
}
if ( rest_is_field_included( 'styles', $fields ) ) {
$data['styles'] = ! empty( $config['styles'] ) && $is_global_styles_user_theme_json ? $config['styles'] : new stdClass();
}
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
// Wrap the data in a response object.
$response = rest_ensure_response( $data );
if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
$links = $this->prepare_links( $post->ID );
$response->add_links( $links );
if ( ! empty( $links['self']['href'] ) ) {
$actions = $this->get_available_actions();
$self = $links['self']['href'];
foreach ( $actions as $rel ) {
$response->add_link( $rel, $self );
}
}
}
return $response;
}
/**
* Prepares links for the request.
*
* @since 5.9.0
*
* @param integer $id ID.
* @return array Links for the given post.
*/
protected function prepare_links( $id ) {
$base = sprintf( '%s/%s', $this->namespace, $this->rest_base );
$links = array(
'self' => array(
'href' => rest_url( trailingslashit( $base ) . $id ),
),
);
return $links;
}
/**
* Get the link relations available for the post and current user.
*
* @since 5.9.0
*
* @return array 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';
}
return $rels;
}
/**
* 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.9.0
*
* @return string Protected title format.
*/
public function protected_title_format() {
return '%s';
}
/**
* Retrieves the query params for the global styles collection.
*
* @since 5.9.0
*
* @return array Collection parameters.
*/
public function get_collection_params() {
return array();
}
/**
* Retrieves the global styles type' 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 );
}
$schema = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => $this->post_type,
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'ID of global styles config.' ),
'type' => 'string',
'context' => array( 'embed', 'view', 'edit' ),
'readonly' => true,
),
'styles' => array(
'description' => __( 'Global styles.' ),
'type' => array( 'object' ),
'context' => array( 'view', 'edit' ),
),
'settings' => array(
'description' => __( 'Global settings.' ),
'type' => array( 'object' ),
'context' => array( 'view', 'edit' ),
),
'title' => array(
'description' => __( 'Title of the global styles variation.' ),
'type' => array( 'object', 'string' ),
'default' => '',
'context' => array( 'embed', 'view', 'edit' ),
'properties' => array(
'raw' => array(
'description' => __( 'Title for the global styles variation, as it exists in the database.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
),
'rendered' => array(
'description' => __( 'HTML title for the post, transformed for display.' ),
'type' => 'string',
'context' => array( 'view', 'edit', 'embed' ),
'readonly' => true,
),
),
),
),
);
$this->schema = $schema;
return $this->add_additional_fields_schema( $this->schema );
}
/**
* Checks if a given request has access to read a single theme global styles config.
*
* @since 5.9.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_theme_item_permissions_check( $request ) {
// Verify if the current user has edit_theme_options capability.
// This capability is required to edit/view/delete templates.
if ( ! current_user_can( 'edit_theme_options' ) ) {
return new WP_Error(
'rest_cannot_manage_global_styles',
__( 'Sorry, you are not allowed to access the global styles on this site.' ),
array(
'status' => rest_authorization_required_code(),
)
);
}
return true;
}
/**
* Returns the given theme global styles config.
*
* @since 5.9.0
*
* @param WP_REST_Request $request The request instance.
* @return WP_REST_Response|WP_Error
*/
public function get_theme_item( $request ) {
if ( wp_get_theme()->get_stylesheet() !== $request['stylesheet'] ) {
// This endpoint only supports the active theme for now.
return new WP_Error(
'rest_theme_not_found',
__( 'Theme not found.' ),
array( 'status' => 404 )
);
}
$theme = WP_Theme_JSON_Resolver::get_merged_data( 'theme' );
$data = array();
$fields = $this->get_fields_for_response( $request );
if ( rest_is_field_included( 'settings', $fields ) ) {
$data['settings'] = $theme->get_settings();
}
if ( rest_is_field_included( 'styles', $fields ) ) {
$raw_data = $theme->get_raw_data();
$data['styles'] = isset( $raw_data['styles'] ) ? $raw_data['styles'] : array();
}
$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
$data = $this->add_additional_fields_to_object( $data, $request );
$data = $this->filter_response_by_context( $data, $context );
$response = rest_ensure_response( $data );
if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
$links = array(
'self' => array(
'href' => rest_url( sprintf( '%s/%s/themes/%s', $this->namespace, $this->rest_base, $request['stylesheet'] ) ),
),
);
$response->add_links( $links );
}
return $response;
}
/**
* Checks if a given request has access to read a single theme global styles config.
*
* @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 for the item, WP_Error object otherwise.
*/
public function get_theme_items_permissions_check( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
// Verify if the current user has edit_theme_options capability.
// This capability is required to edit/view/delete templates.
if ( ! current_user_can( 'edit_theme_options' ) ) {
return new WP_Error(
'rest_cannot_manage_global_styles',
__( 'Sorry, you are not allowed to access the global styles on this site.' ),
array(
'status' => rest_authorization_required_code(),
)
);
}
return true;
}
/**
* Returns the given theme global styles variations.
*
* @since 6.0.0
*
* @param WP_REST_Request $request The request instance.
*
* @return WP_REST_Response|WP_Error
*/
public function get_theme_items( $request ) {
if ( wp_get_theme()->get_stylesheet() !== $request['stylesheet'] ) {
// This endpoint only supports the active theme for now.
return new WP_Error(
'rest_theme_not_found',
__( 'Theme not found.' ),
array( 'status' => 404 )
);
}
$variations = WP_Theme_JSON_Resolver::get_style_variations();
$response = rest_ensure_response( $variations );
return $response;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_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. |
| programming_docs |
wordpress class Walker_PageDropdown {} class Walker\_PageDropdown {}
=============================
Core class used to create an HTML drop-down list of pages.
* [Walker](walker)
* [start\_el](walker_pagedropdown/start_el) — Starts the element output.
File: `wp-includes/class-walker-page-dropdown.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-walker-page-dropdown.php/)
```
class Walker_PageDropdown extends Walker {
/**
* What the class handles.
*
* @since 2.1.0
* @var string
*
* @see Walker::$tree_type
*/
public $tree_type = 'page';
/**
* Database fields to use.
*
* @since 2.1.0
* @var string[]
*
* @see Walker::$db_fields
* @todo Decouple this
*/
public $db_fields = array(
'parent' => 'post_parent',
'id' => 'ID',
);
/**
* Starts the element output.
*
* @since 2.1.0
* @since 5.9.0 Renamed `$page` to `$data_object` and `$id` to `$current_object_id`
* to match parent class for PHP 8 named parameter support.
*
* @see Walker::start_el()
*
* @param string $output Used to append additional content. Passed by reference.
* @param WP_Post $data_object Page data object.
* @param int $depth Optional. Depth of page in reference to parent pages.
* Used for padding. Default 0.
* @param array $args Optional. Uses 'selected' argument for selected page to
* set selected HTML attribute for option element. Uses
* 'value_field' argument to fill "value" attribute.
* See wp_dropdown_pages(). Default empty array.
* @param int $current_object_id Optional. ID of the current page. 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.
$page = $data_object;
$pad = str_repeat( ' ', $depth * 3 );
if ( ! isset( $args['value_field'] ) || ! isset( $page->{$args['value_field']} ) ) {
$args['value_field'] = 'ID';
}
$output .= "\t<option class=\"level-$depth\" value=\"" . esc_attr( $page->{$args['value_field']} ) . '"';
if ( $page->ID == $args['selected'] ) {
$output .= ' selected="selected"';
}
$output .= '>';
$title = $page->post_title;
if ( '' === $title ) {
/* translators: %d: ID of a post. */
$title = sprintf( __( '#%d (no title)' ), $page->ID );
}
/**
* Filters the page title when creating an HTML drop-down list of pages.
*
* @since 3.1.0
*
* @param string $title Page title.
* @param WP_Post $page Page data object.
*/
$title = apply_filters( 'list_pages', $title, $page );
$output .= $pad . esc_html( $title );
$output .= "</option>\n";
}
}
```
| 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_Widget_Text {} class WP\_Widget\_Text {}
=========================
Core class used to implement a Text widget.
* [WP\_Widget](wp_widget)
* [\_\_construct](wp_widget_text/__construct) — Sets up a new Text widget instance.
* [\_filter\_gallery\_shortcode\_attrs](wp_widget_text/_filter_gallery_shortcode_attrs) — Filters gallery shortcode attributes.
* [\_register\_one](wp_widget_text/_register_one) — Add hooks for enqueueing assets when registering all widget instances of this widget class.
* [enqueue\_admin\_scripts](wp_widget_text/enqueue_admin_scripts) — Loads the required scripts and styles for the widget control.
* [enqueue\_preview\_scripts](wp_widget_text/enqueue_preview_scripts) — Enqueue preview scripts.
* [form](wp_widget_text/form) — Outputs the Text widget settings form.
* [inject\_video\_max\_width\_style](wp_widget_text/inject_video_max_width_style) — Inject max-width and remove height for videos too constrained to fit inside sidebars on frontend.
* [is\_legacy\_instance](wp_widget_text/is_legacy_instance) — Determines whether a given instance is legacy and should bypass using TinyMCE.
* [render\_control\_template\_scripts](wp_widget_text/render_control_template_scripts) — Render form template scripts.
* [update](wp_widget_text/update) — Handles updating settings for the current Text widget instance.
* [widget](wp_widget_text/widget) — Outputs the content for the current Text widget instance.
File: `wp-includes/widgets/class-wp-widget-text.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-text.php/)
```
class WP_Widget_Text extends WP_Widget {
/**
* Whether or not the widget has been registered yet.
*
* @since 4.8.1
* @var bool
*/
protected $registered = false;
/**
* Sets up a new Text widget instance.
*
* @since 2.8.0
*/
public function __construct() {
$widget_ops = array(
'classname' => 'widget_text',
'description' => __( 'Arbitrary text.' ),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
);
$control_ops = array(
'width' => 400,
'height' => 350,
);
parent::__construct( 'text', __( 'Text' ), $widget_ops, $control_ops );
}
/**
* Add hooks for enqueueing assets when registering all widget instances of this widget class.
*
* @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( 'text-widgets', sprintf( 'wp.textWidgets.idBases.push( %s );', wp_json_encode( $this->id_base ) ) );
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_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_Text', 'render_control_template_scripts' ) );
}
/**
* Determines whether a given instance is legacy and should bypass using TinyMCE.
*
* @since 4.8.1
*
* @param array $instance {
* Instance data.
*
* @type string $text Content.
* @type bool|string $filter Whether autop or content filters should apply.
* @type bool $legacy Whether widget is in legacy mode.
* }
* @return bool Whether Text widget instance contains legacy data.
*/
public function is_legacy_instance( $instance ) {
// Legacy mode when not in visual mode.
if ( isset( $instance['visual'] ) ) {
return ! $instance['visual'];
}
// Or, the widget has been added/updated in 4.8.0 then filter prop is 'content' and it is no longer legacy.
if ( isset( $instance['filter'] ) && 'content' === $instance['filter'] ) {
return false;
}
// If the text is empty, then nothing is preventing migration to TinyMCE.
if ( empty( $instance['text'] ) ) {
return false;
}
$wpautop = ! empty( $instance['filter'] );
$has_line_breaks = ( false !== strpos( trim( $instance['text'] ), "\n" ) );
// If auto-paragraphs are not enabled and there are line breaks, then ensure legacy mode.
if ( ! $wpautop && $has_line_breaks ) {
return true;
}
// If an HTML comment is present, assume legacy mode.
if ( false !== strpos( $instance['text'], '<!--' ) ) {
return true;
}
// In the rare case that DOMDocument is not available we cannot reliably sniff content and so we assume legacy.
if ( ! class_exists( 'DOMDocument' ) ) {
// @codeCoverageIgnoreStart
return true;
// @codeCoverageIgnoreEnd
}
$doc = new DOMDocument();
// Suppress warnings generated by loadHTML.
$errors = libxml_use_internal_errors( true );
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
@$doc->loadHTML(
sprintf(
'<!DOCTYPE html><html><head><meta charset="%s"></head><body>%s</body></html>',
esc_attr( get_bloginfo( 'charset' ) ),
$instance['text']
)
);
libxml_use_internal_errors( $errors );
$body = $doc->getElementsByTagName( 'body' )->item( 0 );
// See $allowedposttags.
$safe_elements_attributes = array(
'strong' => array(),
'em' => array(),
'b' => array(),
'i' => array(),
'u' => array(),
's' => array(),
'ul' => array(),
'ol' => array(),
'li' => array(),
'hr' => array(),
'abbr' => array(),
'acronym' => array(),
'code' => array(),
'dfn' => array(),
'a' => array(
'href' => true,
),
'img' => array(
'src' => true,
'alt' => true,
),
);
$safe_empty_elements = array( 'img', 'hr', 'iframe' );
foreach ( $body->getElementsByTagName( '*' ) as $element ) {
/** @var DOMElement $element */
$tag_name = strtolower( $element->nodeName );
// If the element is not safe, then the instance is legacy.
if ( ! isset( $safe_elements_attributes[ $tag_name ] ) ) {
return true;
}
// If the element is not safely empty and it has empty contents, then legacy mode.
if ( ! in_array( $tag_name, $safe_empty_elements, true ) && '' === trim( $element->textContent ) ) {
return true;
}
// If an attribute is not recognized as safe, then the instance is legacy.
foreach ( $element->attributes as $attribute ) {
/** @var DOMAttr $attribute */
$attribute_name = strtolower( $attribute->nodeName );
if ( ! isset( $safe_elements_attributes[ $tag_name ][ $attribute_name ] ) ) {
return true;
}
}
}
// Otherwise, the text contains no elements/attributes that TinyMCE could drop, and therefore the widget does not need legacy mode.
return false;
}
/**
* 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 Text widget instance.
*
* @since 2.8.0
*
* @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 Text widget instance.
*/
public function widget( $args, $instance ) {
global $post;
$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 );
$text = ! empty( $instance['text'] ) ? $instance['text'] : '';
$is_visual_text_widget = ( ! empty( $instance['visual'] ) && ! empty( $instance['filter'] ) );
// In 4.8.0 only, visual Text widgets get filter=content, without visual prop; upgrade instance props just-in-time.
if ( ! $is_visual_text_widget ) {
$is_visual_text_widget = ( isset( $instance['filter'] ) && 'content' === $instance['filter'] );
}
if ( $is_visual_text_widget ) {
$instance['filter'] = true;
$instance['visual'] = true;
}
/*
* Suspend legacy plugin-supplied do_shortcode() for 'widget_text' filter for the visual Text widget to prevent
* shortcodes being processed twice. Now do_shortcode() is added to the 'widget_text_content' filter in core itself
* and it applies after wpautop() to prevent corrupting HTML output added by the shortcode. When do_shortcode() is
* added to 'widget_text_content' then do_shortcode() will be manually called when in legacy mode as well.
*/
$widget_text_do_shortcode_priority = has_filter( 'widget_text', 'do_shortcode' );
$should_suspend_legacy_shortcode_support = ( $is_visual_text_widget && false !== $widget_text_do_shortcode_priority );
if ( $should_suspend_legacy_shortcode_support ) {
remove_filter( 'widget_text', 'do_shortcode', $widget_text_do_shortcode_priority );
}
// 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' ) );
/**
* Filters the content of the Text widget.
*
* @since 2.3.0
* @since 4.4.0 Added the `$widget` parameter.
* @since 4.8.1 The `$widget` param may now be a `WP_Widget_Custom_HTML` object in addition to a `WP_Widget_Text` object.
*
* @param string $text The widget content.
* @param array $instance Array of settings for the current widget.
* @param WP_Widget_Text|WP_Widget_Custom_HTML $widget Current text or HTML widget instance.
*/
$text = apply_filters( 'widget_text', $text, $instance, $this );
if ( $is_visual_text_widget ) {
/**
* Filters the content of the Text widget to apply changes expected from the visual (TinyMCE) editor.
*
* By default a subset of the_content filters are applied, including wpautop and wptexturize.
*
* @since 4.8.0
*
* @param string $text The widget content.
* @param array $instance Array of settings for the current widget.
* @param WP_Widget_Text $widget Current Text widget instance.
*/
$text = apply_filters( 'widget_text_content', $text, $instance, $this );
} else {
// Now in legacy mode, add paragraphs and line breaks when checkbox is checked.
if ( ! empty( $instance['filter'] ) ) {
$text = wpautop( $text );
}
/*
* Manually do shortcodes on the content when the core-added filter is present. It is added by default
* in core by adding do_shortcode() to the 'widget_text_content' filter to apply after wpautop().
* Since the legacy Text widget runs wpautop() after 'widget_text' filters are applied, the widget in
* legacy mode here manually applies do_shortcode() on the content unless the default
* core filter for 'widget_text_content' has been removed, or if do_shortcode() has already
* been applied via a plugin adding do_shortcode() to 'widget_text' filters.
*/
if ( has_filter( 'widget_text_content', 'do_shortcode' ) && ! $widget_text_do_shortcode_priority ) {
if ( ! empty( $instance['filter'] ) ) {
$text = shortcode_unautop( $text );
}
$text = do_shortcode( $text );
}
}
// Restore post global.
$post = $original_post;
remove_filter( 'shortcode_atts_gallery', array( $this, '_filter_gallery_shortcode_attrs' ) );
// Undo suspension of legacy plugin-supplied shortcode handling.
if ( $should_suspend_legacy_shortcode_support ) {
add_filter( 'widget_text', 'do_shortcode', $widget_text_do_shortcode_priority );
}
echo $args['before_widget'];
if ( ! empty( $title ) ) {
echo $args['before_title'] . $title . $args['after_title'];
}
$text = preg_replace_callback( '#<(video|iframe|object|embed)\s[^>]*>#i', array( $this, 'inject_video_max_width_style' ), $text );
// Adds 'noopener' relationship, without duplicating values, to all HTML A elements that have a target.
$text = wp_targeted_link_rel( $text );
?>
<div class="textwidget"><?php echo $text; ?></div>
<?php
echo $args['after_widget'];
}
/**
* Inject max-width and remove height for videos too constrained to fit inside sidebars on frontend.
*
* @since 4.9.0
*
* @see WP_Widget_Media_Video::inject_video_max_width_style()
*
* @param array $matches Pattern matches from preg_replace_callback.
* @return string HTML Output.
*/
public function inject_video_max_width_style( $matches ) {
$html = $matches[0];
$html = preg_replace( '/\sheight="\d+"/', '', $html );
$html = preg_replace( '/\swidth="\d+"/', '', $html );
$html = preg_replace( '/(?<=width:)\s*\d+px(?=;?)/', '100%', $html );
return $html;
}
/**
* Handles updating settings for the current Text 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 Settings to save or bool false to cancel saving.
*/
public function update( $new_instance, $old_instance ) {
$new_instance = wp_parse_args(
$new_instance,
array(
'title' => '',
'text' => '',
'filter' => false, // For back-compat.
'visual' => null, // Must be explicitly defined.
)
);
$instance = $old_instance;
$instance['title'] = sanitize_text_field( $new_instance['title'] );
if ( current_user_can( 'unfiltered_html' ) ) {
$instance['text'] = $new_instance['text'];
} else {
$instance['text'] = wp_kses_post( $new_instance['text'] );
}
$instance['filter'] = ! empty( $new_instance['filter'] );
// Upgrade 4.8.0 format.
if ( isset( $old_instance['filter'] ) && 'content' === $old_instance['filter'] ) {
$instance['visual'] = true;
}
if ( 'content' === $new_instance['filter'] ) {
$instance['visual'] = true;
}
if ( isset( $new_instance['visual'] ) ) {
$instance['visual'] = ! empty( $new_instance['visual'] );
}
// Filter is always true in visual mode.
if ( ! empty( $instance['visual'] ) ) {
$instance['filter'] = true;
}
return $instance;
}
/**
* Enqueue preview scripts.
*
* These scripts normally are enqueued just-in-time when a playlist shortcode is used.
* However, in the customizer, a playlist shortcode may be used in a text widget and
* dynamically added via selective refresh, so it is important to unconditionally enqueue them.
*
* @since 4.9.3
*/
public function enqueue_preview_scripts() {
require_once dirname( __DIR__ ) . '/media.php';
wp_playlist_scripts( 'audio' );
wp_playlist_scripts( 'video' );
}
/**
* Loads the required scripts and styles for the widget control.
*
* @since 4.8.0
*/
public function enqueue_admin_scripts() {
wp_enqueue_editor();
wp_enqueue_media();
wp_enqueue_script( 'text-widgets' );
wp_add_inline_script( 'text-widgets', 'wp.textWidgets.init();', 'after' );
}
/**
* Outputs the Text widget settings form.
*
* @since 2.8.0
* @since 4.8.0 Form only contains hidden inputs which are synced with JS template.
* @since 4.8.1 Restored original form to be displayed when in legacy mode.
*
* @see WP_Widget_Text::render_control_template_scripts()
* @see _WP_Editors::editor()
*
* @param array $instance Current settings.
*/
public function form( $instance ) {
$instance = wp_parse_args(
(array) $instance,
array(
'title' => '',
'text' => '',
)
);
?>
<?php if ( ! $this->is_legacy_instance( $instance ) ) : ?>
<?php
if ( user_can_richedit() ) {
add_filter( 'the_editor_content', 'format_for_editor', 10, 2 );
$default_editor = 'tinymce';
} else {
$default_editor = 'html';
}
/** This filter is documented in wp-includes/class-wp-editor.php */
$text = apply_filters( 'the_editor_content', $instance['text'], $default_editor );
// Reset filter addition.
if ( user_can_richedit() ) {
remove_filter( 'the_editor_content', 'format_for_editor' );
}
// Prevent premature closing of textarea in case format_for_editor() didn't apply or the_editor_content filter did a wrong thing.
$escaped_text = preg_replace( '#</textarea#i', '</textarea', $text );
?>
<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( 'text' ); ?>" name="<?php echo $this->get_field_name( 'text' ); ?>" class="text sync-input" hidden><?php echo $escaped_text; ?></textarea>
<input id="<?php echo $this->get_field_id( 'filter' ); ?>" name="<?php echo $this->get_field_name( 'filter' ); ?>" class="filter sync-input" type="hidden" value="on">
<input id="<?php echo $this->get_field_id( 'visual' ); ?>" name="<?php echo $this->get_field_name( 'visual' ); ?>" class="visual sync-input" type="hidden" value="on">
<?php else : ?>
<input id="<?php echo $this->get_field_id( 'visual' ); ?>" name="<?php echo $this->get_field_name( 'visual' ); ?>" class="visual" type="hidden" value="">
<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>
<div class="notice inline notice-info notice-alt">
<?php if ( ! isset( $instance['visual'] ) ) : ?>
<p><?php _e( 'This widget may contain code that may work better in the “Custom HTML” widget. How about trying that widget instead?' ); ?></p>
<?php else : ?>
<p><?php _e( 'This widget may have contained code that may work better in the “Custom HTML” widget. If you have not yet, how about trying that widget instead?' ); ?></p>
<?php endif; ?>
</div>
<p>
<label for="<?php echo $this->get_field_id( 'text' ); ?>"><?php _e( 'Content:' ); ?></label>
<textarea class="widefat" rows="16" cols="20" id="<?php echo $this->get_field_id( 'text' ); ?>" name="<?php echo $this->get_field_name( 'text' ); ?>"><?php echo esc_textarea( $instance['text'] ); ?></textarea>
</p>
<p>
<input id="<?php echo $this->get_field_id( 'filter' ); ?>" name="<?php echo $this->get_field_name( 'filter' ); ?>" type="checkbox"<?php checked( ! empty( $instance['filter'] ) ); ?> /> <label for="<?php echo $this->get_field_id( 'filter' ); ?>"><?php _e( 'Automatically add paragraphs' ); ?></label>
</p>
<?php
endif;
}
/**
* Render form template scripts.
*
* @since 4.8.0
* @since 4.9.0 The method is now static.
*/
public static function render_control_template_scripts() {
$dismissed_pointers = explode( ',', (string) get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) );
?>
<script type="text/html" id="tmpl-widget-text-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>
<?php if ( ! in_array( 'text_widget_custom_html', $dismissed_pointers, true ) ) : ?>
<div hidden class="wp-pointer custom-html-widget-pointer wp-pointer-top">
<div class="wp-pointer-content">
<h3><?php _e( 'New Custom HTML Widget' ); ?></h3>
<?php if ( is_customize_preview() ) : ?>
<p><?php _e( 'Did you know there is a “Custom HTML” widget now? You can find it by pressing the “<a class="add-widget" href="#">Add a Widget</a>” button and searching for “HTML”. Check it out to add some custom code to your site!' ); ?></p>
<?php else : ?>
<p><?php _e( 'Did you know there is a “Custom HTML” widget now? You can find it by scanning the list of available widgets on this screen. Check it out to add some custom code to your site!' ); ?></p>
<?php endif; ?>
<div class="wp-pointer-buttons">
<a class="close" href="#"><?php _e( 'Dismiss' ); ?></a>
</div>
</div>
<div class="wp-pointer-arrow">
<div class="wp-pointer-arrow-inner"></div>
</div>
</div>
<?php endif; ?>
<?php if ( ! in_array( 'text_widget_paste_html', $dismissed_pointers, true ) ) : ?>
<div hidden class="wp-pointer paste-html-pointer wp-pointer-top">
<div class="wp-pointer-content">
<h3><?php _e( 'Did you just paste HTML?' ); ?></h3>
<p><?php _e( 'Hey there, looks like you just pasted HTML into the “Visual” tab of the Text widget. You may want to paste your code into the “Text” tab instead. Alternately, try out the new “Custom HTML” widget!' ); ?></p>
<div class="wp-pointer-buttons">
<a class="close" href="#"><?php _e( 'Dismiss' ); ?></a>
</div>
</div>
<div class="wp-pointer-arrow">
<div class="wp-pointer-arrow-inner"></div>
</div>
</div>
<?php endif; ?>
<p>
<label for="{{ elementIdPrefix }}text" class="screen-reader-text"><?php esc_html_e( 'Content:' ); ?></label>
<textarea id="{{ elementIdPrefix }}text" class="widefat text wp-editor-area" style="height: 200px" rows="16" cols="20"></textarea>
</p>
</script>
<?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 WP_Filesystem_Base {} class WP\_Filesystem\_Base {}
=============================
Base WordPress Filesystem class which Filesystem implementations extend.
* [abspath](wp_filesystem_base/abspath) — Returns the path on the remote filesystem of ABSPATH.
* [atime](wp_filesystem_base/atime) — Gets the file's last access time.
* [chdir](wp_filesystem_base/chdir) — Changes current directory.
* [chgrp](wp_filesystem_base/chgrp) — Changes the file group.
* [chmod](wp_filesystem_base/chmod) — Changes filesystem permissions.
* [chown](wp_filesystem_base/chown) — Changes the owner of a file or directory.
* [connect](wp_filesystem_base/connect) — Connects filesystem.
* [copy](wp_filesystem_base/copy) — Copies a file.
* [cwd](wp_filesystem_base/cwd) — Gets the current working directory.
* [delete](wp_filesystem_base/delete) — Deletes a file or directory.
* [dirlist](wp_filesystem_base/dirlist) — Gets details for files in a directory or a specific file.
* [exists](wp_filesystem_base/exists) — Checks if a file or directory exists.
* [find\_base\_dir](wp_filesystem_base/find_base_dir) — Locates a folder on the remote filesystem. — deprecated
* [find\_folder](wp_filesystem_base/find_folder) — Locates a folder on the remote filesystem.
* [get\_base\_dir](wp_filesystem_base/get_base_dir) — Locates a folder on the remote filesystem. — deprecated
* [get\_contents](wp_filesystem_base/get_contents) — Reads entire file into a string.
* [get\_contents\_array](wp_filesystem_base/get_contents_array) — Reads entire file into an array.
* [getchmod](wp_filesystem_base/getchmod) — Gets the permissions of the specified file or filepath in their octal format.
* [gethchmod](wp_filesystem_base/gethchmod) — Returns the \*nix-style file permissions for a file.
* [getnumchmodfromh](wp_filesystem_base/getnumchmodfromh) — Converts \*nix-style file permissions to a octal number.
* [group](wp_filesystem_base/group) — Gets the file's group.
* [is\_binary](wp_filesystem_base/is_binary) — Determines if the string provided contains binary characters.
* [is\_dir](wp_filesystem_base/is_dir) — Checks if resource is a directory.
* [is\_file](wp_filesystem_base/is_file) — Checks if resource is a file.
* [is\_readable](wp_filesystem_base/is_readable) — Checks if a file is readable.
* [is\_writable](wp_filesystem_base/is_writable) — Checks if a file or directory is writable.
* [mkdir](wp_filesystem_base/mkdir) — Creates a directory.
* [move](wp_filesystem_base/move) — Moves a file.
* [mtime](wp_filesystem_base/mtime) — Gets the file modification time.
* [owner](wp_filesystem_base/owner) — Gets the file owner.
* [put\_contents](wp_filesystem_base/put_contents) — Writes a string to a file.
* [rmdir](wp_filesystem_base/rmdir) — Deletes a directory.
* [search\_for\_folder](wp_filesystem_base/search_for_folder) — Locates a folder on the remote filesystem.
* [size](wp_filesystem_base/size) — Gets the file size (in bytes).
* [touch](wp_filesystem_base/touch) — Sets the access and modification times of a file.
* [wp\_content\_dir](wp_filesystem_base/wp_content_dir) — Returns the path on the remote filesystem of WP\_CONTENT\_DIR.
* [wp\_lang\_dir](wp_filesystem_base/wp_lang_dir) — Returns the path on the remote filesystem of WP\_LANG\_DIR.
* [wp\_plugins\_dir](wp_filesystem_base/wp_plugins_dir) — Returns the path on the remote filesystem of WP\_PLUGIN\_DIR.
* [wp\_themes\_dir](wp_filesystem_base/wp_themes_dir) — Returns the path on the remote filesystem of the Themes Directory.
File: `wp-admin/includes/class-wp-filesystem-base.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-filesystem-base.php/)
```
class WP_Filesystem_Base {
/**
* Whether to display debug data for the connection.
*
* @since 2.5.0
* @var bool
*/
public $verbose = false;
/**
* Cached list of local filepaths to mapped remote filepaths.
*
* @since 2.7.0
* @var array
*/
public $cache = array();
/**
* The Access method of the current connection, Set automatically.
*
* @since 2.5.0
* @var string
*/
public $method = '';
/**
* @var WP_Error
*/
public $errors = null;
/**
*/
public $options = array();
/**
* Returns the path on the remote filesystem of ABSPATH.
*
* @since 2.7.0
*
* @return string The location of the remote path.
*/
public function abspath() {
$folder = $this->find_folder( ABSPATH );
// Perhaps the FTP folder is rooted at the WordPress install.
// Check for wp-includes folder in root. Could have some false positives, but rare.
if ( ! $folder && $this->is_dir( '/' . WPINC ) ) {
$folder = '/';
}
return $folder;
}
/**
* Returns the path on the remote filesystem of WP_CONTENT_DIR.
*
* @since 2.7.0
*
* @return string The location of the remote path.
*/
public function wp_content_dir() {
return $this->find_folder( WP_CONTENT_DIR );
}
/**
* Returns the path on the remote filesystem of WP_PLUGIN_DIR.
*
* @since 2.7.0
*
* @return string The location of the remote path.
*/
public function wp_plugins_dir() {
return $this->find_folder( WP_PLUGIN_DIR );
}
/**
* Returns the path on the remote filesystem of the Themes Directory.
*
* @since 2.7.0
*
* @param string|false $theme Optional. The theme stylesheet or template for the directory.
* Default false.
* @return string The location of the remote path.
*/
public function wp_themes_dir( $theme = false ) {
$theme_root = get_theme_root( $theme );
// Account for relative theme roots.
if ( '/themes' === $theme_root || ! is_dir( $theme_root ) ) {
$theme_root = WP_CONTENT_DIR . $theme_root;
}
return $this->find_folder( $theme_root );
}
/**
* Returns the path on the remote filesystem of WP_LANG_DIR.
*
* @since 3.2.0
*
* @return string The location of the remote path.
*/
public function wp_lang_dir() {
return $this->find_folder( WP_LANG_DIR );
}
/**
* Locates a folder on the remote filesystem.
*
* @since 2.5.0
* @deprecated 2.7.0 use WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir() instead.
* @see WP_Filesystem_Base::abspath()
* @see WP_Filesystem_Base::wp_content_dir()
* @see WP_Filesystem_Base::wp_plugins_dir()
* @see WP_Filesystem_Base::wp_themes_dir()
* @see WP_Filesystem_Base::wp_lang_dir()
*
* @param string $base Optional. The folder to start searching from. Default '.'.
* @param bool $verbose Optional. True to display debug information. Default false.
* @return string The location of the remote path.
*/
public function find_base_dir( $base = '.', $verbose = false ) {
_deprecated_function( __FUNCTION__, '2.7.0', 'WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir()' );
$this->verbose = $verbose;
return $this->abspath();
}
/**
* Locates a folder on the remote filesystem.
*
* @since 2.5.0
* @deprecated 2.7.0 use WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir() methods instead.
* @see WP_Filesystem_Base::abspath()
* @see WP_Filesystem_Base::wp_content_dir()
* @see WP_Filesystem_Base::wp_plugins_dir()
* @see WP_Filesystem_Base::wp_themes_dir()
* @see WP_Filesystem_Base::wp_lang_dir()
*
* @param string $base Optional. The folder to start searching from. Default '.'.
* @param bool $verbose Optional. True to display debug information. Default false.
* @return string The location of the remote path.
*/
public function get_base_dir( $base = '.', $verbose = false ) {
_deprecated_function( __FUNCTION__, '2.7.0', 'WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir()' );
$this->verbose = $verbose;
return $this->abspath();
}
/**
* Locates a folder on the remote filesystem.
*
* Assumes that on Windows systems, Stripping off the Drive
* letter is OK Sanitizes \\ to / in Windows filepaths.
*
* @since 2.7.0
*
* @param string $folder the folder to locate.
* @return string|false The location of the remote path, false on failure.
*/
public function find_folder( $folder ) {
if ( isset( $this->cache[ $folder ] ) ) {
return $this->cache[ $folder ];
}
if ( stripos( $this->method, 'ftp' ) !== false ) {
$constant_overrides = array(
'FTP_BASE' => ABSPATH,
'FTP_CONTENT_DIR' => WP_CONTENT_DIR,
'FTP_PLUGIN_DIR' => WP_PLUGIN_DIR,
'FTP_LANG_DIR' => WP_LANG_DIR,
);
// Direct matches ( folder = CONSTANT/ ).
foreach ( $constant_overrides as $constant => $dir ) {
if ( ! defined( $constant ) ) {
continue;
}
if ( $folder === $dir ) {
return trailingslashit( constant( $constant ) );
}
}
// Prefix matches ( folder = CONSTANT/subdir ),
foreach ( $constant_overrides as $constant => $dir ) {
if ( ! defined( $constant ) ) {
continue;
}
if ( 0 === stripos( $folder, $dir ) ) { // $folder starts with $dir.
$potential_folder = preg_replace( '#^' . preg_quote( $dir, '#' ) . '/#i', trailingslashit( constant( $constant ) ), $folder );
$potential_folder = trailingslashit( $potential_folder );
if ( $this->is_dir( $potential_folder ) ) {
$this->cache[ $folder ] = $potential_folder;
return $potential_folder;
}
}
}
} elseif ( 'direct' === $this->method ) {
$folder = str_replace( '\\', '/', $folder ); // Windows path sanitisation.
return trailingslashit( $folder );
}
$folder = preg_replace( '|^([a-z]{1}):|i', '', $folder ); // Strip out Windows drive letter if it's there.
$folder = str_replace( '\\', '/', $folder ); // Windows path sanitisation.
if ( isset( $this->cache[ $folder ] ) ) {
return $this->cache[ $folder ];
}
if ( $this->exists( $folder ) ) { // Folder exists at that absolute path.
$folder = trailingslashit( $folder );
$this->cache[ $folder ] = $folder;
return $folder;
}
$return = $this->search_for_folder( $folder );
if ( $return ) {
$this->cache[ $folder ] = $return;
}
return $return;
}
/**
* Locates a folder on the remote filesystem.
*
* Expects Windows sanitized path.
*
* @since 2.7.0
*
* @param string $folder The folder to locate.
* @param string $base The folder to start searching from.
* @param bool $loop If the function has recursed. Internal use only.
* @return string|false The location of the remote path, false to cease looping.
*/
public function search_for_folder( $folder, $base = '.', $loop = false ) {
if ( empty( $base ) || '.' === $base ) {
$base = trailingslashit( $this->cwd() );
}
$folder = untrailingslashit( $folder );
if ( $this->verbose ) {
/* translators: 1: Folder to locate, 2: Folder to start searching from. */
printf( "\n" . __( 'Looking for %1$s in %2$s' ) . "<br />\n", $folder, $base );
}
$folder_parts = explode( '/', $folder );
$folder_part_keys = array_keys( $folder_parts );
$last_index = array_pop( $folder_part_keys );
$last_path = $folder_parts[ $last_index ];
$files = $this->dirlist( $base );
foreach ( $folder_parts as $index => $key ) {
if ( $index === $last_index ) {
continue; // We want this to be caught by the next code block.
}
/*
* Working from /home/ to /user/ to /wordpress/ see if that file exists within
* the current folder, If it's found, change into it and follow through looking
* for it. If it can't find WordPress down that route, it'll continue onto the next
* folder level, and see if that matches, and so on. If it reaches the end, and still
* can't find it, it'll return false for the entire function.
*/
if ( isset( $files[ $key ] ) ) {
// Let's try that folder:
$newdir = trailingslashit( path_join( $base, $key ) );
if ( $this->verbose ) {
/* translators: %s: Directory name. */
printf( "\n" . __( 'Changing to %s' ) . "<br />\n", $newdir );
}
// Only search for the remaining path tokens in the directory, not the full path again.
$newfolder = implode( '/', array_slice( $folder_parts, $index + 1 ) );
$ret = $this->search_for_folder( $newfolder, $newdir, $loop );
if ( $ret ) {
return $ret;
}
}
}
// Only check this as a last resort, to prevent locating the incorrect install.
// All above procedures will fail quickly if this is the right branch to take.
if ( isset( $files[ $last_path ] ) ) {
if ( $this->verbose ) {
/* translators: %s: Directory name. */
printf( "\n" . __( 'Found %s' ) . "<br />\n", $base . $last_path );
}
return trailingslashit( $base . $last_path );
}
// Prevent this function from looping again.
// No need to proceed if we've just searched in `/`.
if ( $loop || '/' === $base ) {
return false;
}
// As an extra last resort, Change back to / if the folder wasn't found.
// This comes into effect when the CWD is /home/user/ but WP is at /var/www/....
return $this->search_for_folder( $folder, '/', true );
}
/**
* Returns the *nix-style file permissions for a file.
*
* From the PHP documentation page for fileperms().
*
* @link https://www.php.net/manual/en/function.fileperms.php
*
* @since 2.5.0
*
* @param string $file String filename.
* @return string The *nix-style representation of permissions.
*/
public function gethchmod( $file ) {
$perms = intval( $this->getchmod( $file ), 8 );
if ( ( $perms & 0xC000 ) === 0xC000 ) { // Socket.
$info = 's';
} elseif ( ( $perms & 0xA000 ) === 0xA000 ) { // Symbolic Link.
$info = 'l';
} elseif ( ( $perms & 0x8000 ) === 0x8000 ) { // Regular.
$info = '-';
} elseif ( ( $perms & 0x6000 ) === 0x6000 ) { // Block special.
$info = 'b';
} elseif ( ( $perms & 0x4000 ) === 0x4000 ) { // Directory.
$info = 'd';
} elseif ( ( $perms & 0x2000 ) === 0x2000 ) { // Character special.
$info = 'c';
} elseif ( ( $perms & 0x1000 ) === 0x1000 ) { // FIFO pipe.
$info = 'p';
} else { // Unknown.
$info = 'u';
}
// Owner.
$info .= ( ( $perms & 0x0100 ) ? 'r' : '-' );
$info .= ( ( $perms & 0x0080 ) ? 'w' : '-' );
$info .= ( ( $perms & 0x0040 ) ?
( ( $perms & 0x0800 ) ? 's' : 'x' ) :
( ( $perms & 0x0800 ) ? 'S' : '-' ) );
// Group.
$info .= ( ( $perms & 0x0020 ) ? 'r' : '-' );
$info .= ( ( $perms & 0x0010 ) ? 'w' : '-' );
$info .= ( ( $perms & 0x0008 ) ?
( ( $perms & 0x0400 ) ? 's' : 'x' ) :
( ( $perms & 0x0400 ) ? 'S' : '-' ) );
// World.
$info .= ( ( $perms & 0x0004 ) ? 'r' : '-' );
$info .= ( ( $perms & 0x0002 ) ? 'w' : '-' );
$info .= ( ( $perms & 0x0001 ) ?
( ( $perms & 0x0200 ) ? 't' : 'x' ) :
( ( $perms & 0x0200 ) ? 'T' : '-' ) );
return $info;
}
/**
* 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 ) {
return '777';
}
/**
* Converts *nix-style file permissions to a octal number.
*
* Converts '-rw-r--r--' to 0644
* From "info at rvgate dot nl"'s comment on the PHP documentation for chmod()
*
* @link https://www.php.net/manual/en/function.chmod.php#49614
*
* @since 2.5.0
*
* @param string $mode string The *nix-style file permissions.
* @return string Octal representation of permissions.
*/
public function getnumchmodfromh( $mode ) {
$realmode = '';
$legal = array( '', 'w', 'r', 'x', '-' );
$attarray = preg_split( '//', $mode );
for ( $i = 0, $c = count( $attarray ); $i < $c; $i++ ) {
$key = array_search( $attarray[ $i ], $legal, true );
if ( $key ) {
$realmode .= $legal[ $key ];
}
}
$mode = str_pad( $realmode, 10, '-', STR_PAD_LEFT );
$trans = array(
'-' => '0',
'r' => '4',
'w' => '2',
'x' => '1',
);
$mode = strtr( $mode, $trans );
$newmode = $mode[0];
$newmode .= $mode[1] + $mode[2] + $mode[3];
$newmode .= $mode[4] + $mode[5] + $mode[6];
$newmode .= $mode[7] + $mode[8] + $mode[9];
return $newmode;
}
/**
* Determines if the string provided contains binary characters.
*
* @since 2.7.0
*
* @param string $text String to test against.
* @return bool True if string is binary, false otherwise.
*/
public function is_binary( $text ) {
return (bool) preg_match( '|[^\x20-\x7E]|', $text ); // chr(32)..chr(127)
}
/**
* Changes the owner of a file or directory.
*
* Default behavior is to do nothing, override this in your subclass, if desired.
*
* @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 ) {
return false;
}
/**
* Connects filesystem.
*
* @since 2.5.0
* @abstract
*
* @return bool True on success, false on failure (always true for WP_Filesystem_Direct).
*/
public function connect() {
return true;
}
/**
* Reads entire file into a string.
*
* @since 2.5.0
* @abstract
*
* @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 false;
}
/**
* Reads entire file into an array.
*
* @since 2.5.0
* @abstract
*
* @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 false;
}
/**
* Writes a string to a file.
*
* @since 2.5.0
* @abstract
*
* @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 ) {
return false;
}
/**
* Gets the current working directory.
*
* @since 2.5.0
* @abstract
*
* @return string|false The current working directory on success, false on failure.
*/
public function cwd() {
return false;
}
/**
* Changes current directory.
*
* @since 2.5.0
* @abstract
*
* @param string $dir The new current directory.
* @return bool True on success, false on failure.
*/
public function chdir( $dir ) {
return false;
}
/**
* Changes the file group.
*
* @since 2.5.0
* @abstract
*
* @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 ) {
return false;
}
/**
* Changes filesystem permissions.
*
* @since 2.5.0
* @abstract
*
* @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 ) {
return false;
}
/**
* Gets the file owner.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to the file.
* @return string|false Username of the owner on success, false on failure.
*/
public function owner( $file ) {
return false;
}
/**
* Gets the file's group.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to the file.
* @return string|false The group on success, false on failure.
*/
public function group( $file ) {
return false;
}
/**
* Copies a file.
*
* @since 2.5.0
* @abstract
*
* @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 ) {
return false;
}
/**
* Moves a file.
*
* @since 2.5.0
* @abstract
*
* @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 false;
}
/**
* Deletes a file or directory.
*
* @since 2.5.0
* @abstract
*
* @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 ) {
return false;
}
/**
* Checks if a file or directory exists.
*
* @since 2.5.0
* @abstract
*
* @param string $path Path to file or directory.
* @return bool Whether $path exists or not.
*/
public function exists( $path ) {
return false;
}
/**
* Checks if resource is a file.
*
* @since 2.5.0
* @abstract
*
* @param string $file File path.
* @return bool Whether $file is a file.
*/
public function is_file( $file ) {
return false;
}
/**
* Checks if resource is a directory.
*
* @since 2.5.0
* @abstract
*
* @param string $path Directory path.
* @return bool Whether $path is a directory.
*/
public function is_dir( $path ) {
return false;
}
/**
* Checks if a file is readable.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to file.
* @return bool Whether $file is readable.
*/
public function is_readable( $file ) {
return false;
}
/**
* Checks if a file or directory is writable.
*
* @since 2.5.0
* @abstract
*
* @param string $path Path to file or directory.
* @return bool Whether $path is writable.
*/
public function is_writable( $path ) {
return false;
}
/**
* Gets the file's last access time.
*
* @since 2.5.0
* @abstract
*
* @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
* @abstract
*
* @param string $file Path to file.
* @return int|false Unix timestamp representing modification time, false on failure.
*/
public function mtime( $file ) {
return false;
}
/**
* Gets the file size (in bytes).
*
* @since 2.5.0
* @abstract
*
* @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 false;
}
/**
* Sets the access and modification times of a file.
*
* Note: If $file doesn't exist, it will be created.
*
* @since 2.5.0
* @abstract
*
* @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
* @abstract
*
* @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 ) {
return false;
}
/**
* Deletes a directory.
*
* @since 2.5.0
* @abstract
*
* @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 false;
}
/**
* Gets details for files in a directory or a specific file.
*
* @since 2.5.0
* @abstract
*
* @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 ) {
return false;
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Filesystem\_SSH2](wp_filesystem_ssh2) wp-admin/includes/class-wp-filesystem-ssh2.php | WordPress Filesystem Class for implementing SSH2 |
| [WP\_Filesystem\_FTPext](wp_filesystem_ftpext) wp-admin/includes/class-wp-filesystem-ftpext.php | WordPress Filesystem Class for implementing FTP. |
| [WP\_Filesystem\_Direct](wp_filesystem_direct) wp-admin/includes/class-wp-filesystem-direct.php | WordPress Filesystem Class for direct PHP file and folder manipulation. |
| [WP\_Filesystem\_ftpsockets](wp_filesystem_ftpsockets) wp-admin/includes/class-wp-filesystem-ftpsockets.php | WordPress Filesystem Class for implementing FTP Sockets. |
| Version | Description |
| --- | --- |
| [2.5.0](https://developer.wordpress.org/reference/since/2.5.0/) | Introduced. |
| programming_docs |
wordpress class WP_Customize_Filter_Setting {} class WP\_Customize\_Filter\_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_filter_setting/update) — Saves the value of the setting, using the related API.
File: `wp-includes/customize/class-wp-customize-filter-setting.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-filter-setting.php/)
```
class WP_Customize_Filter_Setting extends WP_Customize_Setting {
/**
* Saves the value of the setting, using the related API.
*
* @since 3.4.0
*
* @param mixed $value The value to update.
*/
public function update( $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 POMO_CachedIntFileReader {} class POMO\_CachedIntFileReader {}
==================================
Reads the contents of the file in the beginning.
* [\_\_construct](pomo_cachedintfilereader/__construct) — PHP5 constructor.
* [POMO\_CachedIntFileReader](pomo_cachedintfilereader/pomo_cachedintfilereader) — 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_CachedIntFileReader extends POMO_CachedFileReader {
/**
* PHP5 constructor.
*/
public function __construct( $filename ) {
parent::__construct( $filename );
}
/**
* PHP4 constructor.
*
* @deprecated 5.4.0 Use __construct() instead.
*
* @see POMO_CachedIntFileReader::__construct()
*/
public function POMO_CachedIntFileReader( $filename ) {
_deprecated_constructor( self::class, '5.4.0', static::class );
self::__construct( $filename );
}
}
```
| Uses | Description |
| --- | --- |
| [POMO\_CachedFileReader](pomo_cachedfilereader) wp-includes/pomo/streams.php | Reads the contents of the file in the beginning. |
wordpress class WP_Widget_Form_Customize_Control {} class WP\_Widget\_Form\_Customize\_Control {}
=============================================
Widget Form Customize Control class.
* [WP\_Customize\_Control](wp_customize_control)
* [active\_callback](wp_widget_form_customize_control/active_callback) — Whether the current widget is rendered on the page.
* [render\_content](wp_widget_form_customize_control/render_content) — Override render\_content to be no-op since content is exported via to\_json for deferred embedding.
* [to\_json](wp_widget_form_customize_control/to_json) — Gather control params for exporting to JavaScript.
File: `wp-includes/customize/class-wp-widget-form-customize-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-widget-form-customize-control.php/)
```
class WP_Widget_Form_Customize_Control extends WP_Customize_Control {
/**
* Customize control type.
*
* @since 3.9.0
* @var string
*/
public $type = 'widget_form';
/**
* Widget ID.
*
* @since 3.9.0
* @var string
*/
public $widget_id;
/**
* Widget ID base.
*
* @since 3.9.0
* @var string
*/
public $widget_id_base;
/**
* Sidebar ID.
*
* @since 3.9.0
* @var string
*/
public $sidebar_id;
/**
* Widget status.
*
* @since 3.9.0
* @var bool True if new, false otherwise. Default false.
*/
public $is_new = false;
/**
* Widget width.
*
* @since 3.9.0
* @var int
*/
public $width;
/**
* Widget height.
*
* @since 3.9.0
* @var int
*/
public $height;
/**
* Widget mode.
*
* @since 3.9.0
* @var bool True if wide, false otherwise. Default false.
*/
public $is_wide = false;
/**
* Gather control params for exporting to JavaScript.
*
* @since 3.9.0
*
* @global array $wp_registered_widgets
*/
public function to_json() {
global $wp_registered_widgets;
parent::to_json();
$exported_properties = array( 'widget_id', 'widget_id_base', 'sidebar_id', 'width', 'height', 'is_wide' );
foreach ( $exported_properties as $key ) {
$this->json[ $key ] = $this->$key;
}
// Get the widget_control and widget_content.
require_once ABSPATH . 'wp-admin/includes/widgets.php';
$widget = $wp_registered_widgets[ $this->widget_id ];
if ( ! isset( $widget['params'][0] ) ) {
$widget['params'][0] = array();
}
$args = array(
'widget_id' => $widget['id'],
'widget_name' => $widget['name'],
);
$args = wp_list_widget_controls_dynamic_sidebar(
array(
0 => $args,
1 => $widget['params'][0],
)
);
$widget_control_parts = $this->manager->widgets->get_widget_control_parts( $args );
$this->json['widget_control'] = $widget_control_parts['control'];
$this->json['widget_content'] = $widget_control_parts['content'];
}
/**
* Override render_content to be no-op since content is exported via to_json for deferred embedding.
*
* @since 3.9.0
*/
public function render_content() {}
/**
* Whether the current widget is rendered on the page.
*
* @since 4.0.0
*
* @return bool Whether the widget is rendered.
*/
public function active_callback() {
return $this->manager->widgets->is_widget_rendered( $this->widget_id );
}
}
```
| 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 Requests_Exception_Transport_cURL {} class Requests\_Exception\_Transport\_cURL {}
=============================================
* [\_\_construct](requests_exception_transport_curl/__construct)
* [getReason](requests_exception_transport_curl/getreason) — Get the error message
File: `wp-includes/Requests/Exception/Transport/cURL.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/exception/transport/curl.php/)
```
class Requests_Exception_Transport_cURL extends Requests_Exception_Transport {
const EASY = 'cURLEasy';
const MULTI = 'cURLMulti';
const SHARE = 'cURLShare';
/**
* cURL error code
*
* @var integer
*/
protected $code = -1;
/**
* Which type of cURL error
*
* EASY|MULTI|SHARE
*
* @var string
*/
protected $type = 'Unknown';
/**
* Clear text error message
*
* @var string
*/
protected $reason = 'Unknown';
public function __construct($message, $type, $data = null, $code = 0) {
if ($type !== null) {
$this->type = $type;
}
if ($code !== null) {
$this->code = $code;
}
if ($message !== null) {
$this->reason = $message;
}
$message = sprintf('%d %s', $this->code, $this->reason);
parent::__construct($message, $this->type, $data, $this->code);
}
/**
* Get the error message
*/
public function getReason() {
return $this->reason;
}
}
```
| Uses | Description |
| --- | --- |
| [Requests\_Exception\_Transport](requests_exception_transport) wp-includes/Requests/Exception/Transport.php | |
wordpress class Requests_IPv6 {} class Requests\_IPv6 {}
=======================
Class to validate and to work with IPv6 addresses
This was originally based on the PEAR class of the same name, but has been entirely rewritten.
* [check\_ipv6](requests_ipv6/check_ipv6) — Checks an IPv6 address
* [compress](requests_ipv6/compress) — Compresses an IPv6 address
* [split\_v6\_v4](requests_ipv6/split_v6_v4) — Splits an IPv6 address into the IPv6 and IPv4 representation parts
* [uncompress](requests_ipv6/uncompress) — Uncompresses an IPv6 address
File: `wp-includes/Requests/IPv6.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/requests/ipv6.php/)
```
class Requests_IPv6 {
/**
* Uncompresses an IPv6 address
*
* RFC 4291 allows you to compress consecutive zero pieces in an address to
* '::'. This method expects a valid IPv6 address and expands the '::' to
* the required number of zero pieces.
*
* Example: FF01::101 -> FF01:0:0:0:0:0:0:101
* ::1 -> 0:0:0:0:0:0:0:1
*
* @author Alexander Merz <[email protected]>
* @author elfrink at introweb dot nl
* @author Josh Peck <jmp at joshpeck dot org>
* @copyright 2003-2005 The PHP Group
* @license http://www.opensource.org/licenses/bsd-license.php
* @param string $ip An IPv6 address
* @return string The uncompressed IPv6 address
*/
public static function uncompress($ip) {
if (substr_count($ip, '::') !== 1) {
return $ip;
}
list($ip1, $ip2) = explode('::', $ip);
$c1 = ($ip1 === '') ? -1 : substr_count($ip1, ':');
$c2 = ($ip2 === '') ? -1 : substr_count($ip2, ':');
if (strpos($ip2, '.') !== false) {
$c2++;
}
// ::
if ($c1 === -1 && $c2 === -1) {
$ip = '0:0:0:0:0:0:0:0';
}
// ::xxx
elseif ($c1 === -1) {
$fill = str_repeat('0:', 7 - $c2);
$ip = str_replace('::', $fill, $ip);
}
// xxx::
elseif ($c2 === -1) {
$fill = str_repeat(':0', 7 - $c1);
$ip = str_replace('::', $fill, $ip);
}
// xxx::xxx
else {
$fill = ':' . str_repeat('0:', 6 - $c2 - $c1);
$ip = str_replace('::', $fill, $ip);
}
return $ip;
}
/**
* Compresses an IPv6 address
*
* RFC 4291 allows you to compress consecutive zero pieces in an address to
* '::'. This method expects a valid IPv6 address and compresses consecutive
* zero pieces to '::'.
*
* Example: FF01:0:0:0:0:0:0:101 -> FF01::101
* 0:0:0:0:0:0:0:1 -> ::1
*
* @see uncompress()
* @param string $ip An IPv6 address
* @return string The compressed IPv6 address
*/
public static function compress($ip) {
// Prepare the IP to be compressed
$ip = self::uncompress($ip);
$ip_parts = self::split_v6_v4($ip);
// Replace all leading zeros
$ip_parts[0] = preg_replace('/(^|:)0+([0-9])/', '\1\2', $ip_parts[0]);
// Find bunches of zeros
if (preg_match_all('/(?:^|:)(?:0(?::|$))+/', $ip_parts[0], $matches, PREG_OFFSET_CAPTURE)) {
$max = 0;
$pos = null;
foreach ($matches[0] as $match) {
if (strlen($match[0]) > $max) {
$max = strlen($match[0]);
$pos = $match[1];
}
}
$ip_parts[0] = substr_replace($ip_parts[0], '::', $pos, $max);
}
if ($ip_parts[1] !== '') {
return implode(':', $ip_parts);
}
else {
return $ip_parts[0];
}
}
/**
* Splits an IPv6 address into the IPv6 and IPv4 representation parts
*
* RFC 4291 allows you to represent the last two parts of an IPv6 address
* using the standard IPv4 representation
*
* Example: 0:0:0:0:0:0:13.1.68.3
* 0:0:0:0:0:FFFF:129.144.52.38
*
* @param string $ip An IPv6 address
* @return string[] [0] contains the IPv6 represented part, and [1] the IPv4 represented part
*/
protected static function split_v6_v4($ip) {
if (strpos($ip, '.') !== false) {
$pos = strrpos($ip, ':');
$ipv6_part = substr($ip, 0, $pos);
$ipv4_part = substr($ip, $pos + 1);
return array($ipv6_part, $ipv4_part);
}
else {
return array($ip, '');
}
}
/**
* Checks an IPv6 address
*
* Checks if the given IP is a valid IPv6 address
*
* @param string $ip An IPv6 address
* @return bool true if $ip is a valid IPv6 address
*/
public static function check_ipv6($ip) {
$ip = self::uncompress($ip);
list($ipv6, $ipv4) = self::split_v6_v4($ip);
$ipv6 = explode(':', $ipv6);
$ipv4 = explode('.', $ipv4);
if (count($ipv6) === 8 && count($ipv4) === 1 || count($ipv6) === 6 && count($ipv4) === 4) {
foreach ($ipv6 as $ipv6_part) {
// The section can't be empty
if ($ipv6_part === '') {
return false;
}
// Nor can it be over four characters
if (strlen($ipv6_part) > 4) {
return false;
}
// Remove leading zeros (this is safe because of the above)
$ipv6_part = ltrim($ipv6_part, '0');
if ($ipv6_part === '') {
$ipv6_part = '0';
}
// Check the value is valid
$value = hexdec($ipv6_part);
if (dechex($value) !== strtolower($ipv6_part) || $value < 0 || $value > 0xFFFF) {
return false;
}
}
if (count($ipv4) === 4) {
foreach ($ipv4 as $ipv4_part) {
$value = (int) $ipv4_part;
if ((string) $value !== $ipv4_part || $value < 0 || $value > 0xFF) {
return false;
}
}
}
return true;
}
else {
return false;
}
}
}
```
wordpress class wp_xmlrpc_server {} class wp\_xmlrpc\_server {}
===========================
WordPress XMLRPC server implementation.
Implements compatibility for Blogger API, MetaWeblog API, MovableType, and pingback. Additional WordPress API for managing comments, pages, posts, options, etc.
As of WordPress 3.5.0, XML-RPC is enabled by default. It can be disabled via the [‘xmlrpc\_enabled’](../hooks/xmlrpc_enabled) filter found in [wp\_xmlrpc\_server::set\_is\_enabled()](wp_xmlrpc_server/set_is_enabled).
* [IXR\_Server](ixr_server)
* [\_\_call](wp_xmlrpc_server/__call) — Make private/protected methods readable for backward compatibility.
* [\_\_construct](wp_xmlrpc_server/__construct) — Registers all of the XMLRPC methods that XMLRPC server understands.
* [\_convert\_date](wp_xmlrpc_server/_convert_date) — Convert a WordPress date string to an IXR\_Date object.
* [\_convert\_date\_gmt](wp_xmlrpc_server/_convert_date_gmt) — Convert a WordPress GMT date string to an IXR\_Date object.
* [\_getOptions](wp_xmlrpc_server/_getoptions) — Retrieve blog options value from list.
* [\_insert\_post](wp_xmlrpc_server/_insert_post) — Helper method for wp\_newPost() and wp\_editPost(), containing shared logic.
* [\_is\_greater\_than\_one](wp_xmlrpc_server/_is_greater_than_one) — Helper method for filtering out elements from an array.
* [\_multisite\_getUsersBlogs](wp_xmlrpc_server/_multisite_getusersblogs) — Private function for retrieving a users blogs for multisite setups
* [\_prepare\_comment](wp_xmlrpc_server/_prepare_comment) — Prepares comment data for return in an XML-RPC object.
* [\_prepare\_media\_item](wp_xmlrpc_server/_prepare_media_item) — Prepares media item data for return in an XML-RPC object.
* [\_prepare\_page](wp_xmlrpc_server/_prepare_page) — Prepares page data for return in an XML-RPC object.
* [\_prepare\_post](wp_xmlrpc_server/_prepare_post) — Prepares post data for return in an XML-RPC object.
* [\_prepare\_post\_type](wp_xmlrpc_server/_prepare_post_type) — Prepares post data for return in an XML-RPC object.
* [\_prepare\_taxonomy](wp_xmlrpc_server/_prepare_taxonomy) — Prepares taxonomy data for return in an XML-RPC object.
* [\_prepare\_term](wp_xmlrpc_server/_prepare_term) — Prepares term data for return in an XML-RPC object.
* [\_prepare\_user](wp_xmlrpc_server/_prepare_user) — Prepares user data for return in an XML-RPC object.
* [\_toggle\_sticky](wp_xmlrpc_server/_toggle_sticky) — Encapsulate the logic for sticking a post and determining if the user has permission to do so
* [add\_enclosure\_if\_new](wp_xmlrpc_server/add_enclosure_if_new) — Adds an enclosure to a post if it's new.
* [addTwoNumbers](wp_xmlrpc_server/addtwonumbers) — Test XMLRPC API by adding two numbers for client.
* [attach\_uploads](wp_xmlrpc_server/attach_uploads) — Attach upload to a post.
* [blogger\_deletePost](wp_xmlrpc_server/blogger_deletepost) — Remove a post.
* [blogger\_editPost](wp_xmlrpc_server/blogger_editpost) — Edit a post.
* [blogger\_getPost](wp_xmlrpc_server/blogger_getpost) — Retrieve post.
* [blogger\_getRecentPosts](wp_xmlrpc_server/blogger_getrecentposts) — Retrieve list of recent posts.
* [blogger\_getTemplate](wp_xmlrpc_server/blogger_gettemplate) — Deprecated. — deprecated
* [blogger\_getUserInfo](wp_xmlrpc_server/blogger_getuserinfo) — Retrieve user's data.
* [blogger\_getUsersBlogs](wp_xmlrpc_server/blogger_getusersblogs) — Retrieve blogs that user owns.
* [blogger\_newPost](wp_xmlrpc_server/blogger_newpost) — Creates new post.
* [blogger\_setTemplate](wp_xmlrpc_server/blogger_settemplate) — Deprecated. — deprecated
* [error](wp_xmlrpc_server/error) — Send error response to client.
* [escape](wp_xmlrpc_server/escape) — Escape string or array of strings for database.
* [get\_custom\_fields](wp_xmlrpc_server/get_custom_fields) — Retrieve custom fields for post.
* [get\_term\_custom\_fields](wp_xmlrpc_server/get_term_custom_fields) — Retrieve custom fields for a term.
* [initialise\_blog\_option\_info](wp_xmlrpc_server/initialise_blog_option_info) — Set up blog options property.
* [login](wp_xmlrpc_server/login) — Log user in.
* [login\_pass\_ok](wp_xmlrpc_server/login_pass_ok) — Check user's credentials. Deprecated. — deprecated
* [minimum\_args](wp_xmlrpc_server/minimum_args) — Checks if the method received at least the minimum number of arguments.
* [mt\_getCategoryList](wp_xmlrpc_server/mt_getcategorylist) — Retrieve list of all categories on blog.
* [mt\_getPostCategories](wp_xmlrpc_server/mt_getpostcategories) — Retrieve post categories.
* [mt\_getRecentPostTitles](wp_xmlrpc_server/mt_getrecentposttitles) — Retrieve the post titles of recent posts.
* [mt\_getTrackbackPings](wp_xmlrpc_server/mt_gettrackbackpings) — Retrieve trackbacks sent to a given post.
* [mt\_publishPost](wp_xmlrpc_server/mt_publishpost) — Sets a post's publish status to 'publish'.
* [mt\_setPostCategories](wp_xmlrpc_server/mt_setpostcategories) — Sets categories for a post.
* [mt\_supportedMethods](wp_xmlrpc_server/mt_supportedmethods) — Retrieve an array of methods supported by this server.
* [mt\_supportedTextFilters](wp_xmlrpc_server/mt_supportedtextfilters) — Retrieve an empty array because we don't support per-post text filters.
* [mw\_editPost](wp_xmlrpc_server/mw_editpost) — Edit a post.
* [mw\_getCategories](wp_xmlrpc_server/mw_getcategories) — Retrieve the list of categories on a given blog.
* [mw\_getPost](wp_xmlrpc_server/mw_getpost) — Retrieve post.
* [mw\_getRecentPosts](wp_xmlrpc_server/mw_getrecentposts) — Retrieve list of recent posts.
* [mw\_newMediaObject](wp_xmlrpc_server/mw_newmediaobject) — Uploads a file, following your settings.
* [mw\_newPost](wp_xmlrpc_server/mw_newpost) — Create a new post.
* [pingback\_error](wp_xmlrpc_server/pingback_error) — Sends a pingback error based on the given error code and message.
* [pingback\_extensions\_getPingbacks](wp_xmlrpc_server/pingback_extensions_getpingbacks) — Retrieve array of URLs that pingbacked the given URL.
* [pingback\_ping](wp_xmlrpc_server/pingback_ping) — Retrieves a pingback and registers it.
* [sayHello](wp_xmlrpc_server/sayhello) — Test XMLRPC API by saying, "Hello!" to client.
* [serve\_request](wp_xmlrpc_server/serve_request) — Serves the XML-RPC request.
* [set\_custom\_fields](wp_xmlrpc_server/set_custom_fields) — Set custom fields for post.
* [set\_is\_enabled](wp_xmlrpc_server/set_is_enabled) — Set wp\_xmlrpc\_server::$is\_enabled property.
* [set\_term\_custom\_fields](wp_xmlrpc_server/set_term_custom_fields) — Set custom fields for a term.
* [wp\_deleteCategory](wp_xmlrpc_server/wp_deletecategory) — Remove category.
* [wp\_deleteComment](wp_xmlrpc_server/wp_deletecomment) — Delete a comment.
* [wp\_deletePage](wp_xmlrpc_server/wp_deletepage) — Delete page.
* [wp\_deletePost](wp_xmlrpc_server/wp_deletepost) — Delete a post for any registered post type.
* [wp\_deleteTerm](wp_xmlrpc_server/wp_deleteterm) — Delete a term.
* [wp\_editComment](wp_xmlrpc_server/wp_editcomment) — Edit comment.
* [wp\_editPage](wp_xmlrpc_server/wp_editpage) — Edit page.
* [wp\_editPost](wp_xmlrpc_server/wp_editpost) — Edit a post for any registered post type.
* [wp\_editProfile](wp_xmlrpc_server/wp_editprofile) — Edit user's profile.
* [wp\_editTerm](wp_xmlrpc_server/wp_editterm) — Edit a term.
* [wp\_getAuthors](wp_xmlrpc_server/wp_getauthors) — Retrieve authors list.
* [wp\_getComment](wp_xmlrpc_server/wp_getcomment) — Retrieve comment.
* [wp\_getCommentCount](wp_xmlrpc_server/wp_getcommentcount) — Retrieve comment count.
* [wp\_getComments](wp_xmlrpc_server/wp_getcomments) — Retrieve comments.
* [wp\_getCommentStatusList](wp_xmlrpc_server/wp_getcommentstatuslist) — Retrieve all of the comment status.
* [wp\_getMediaItem](wp_xmlrpc_server/wp_getmediaitem) — Retrieve a media item by ID
* [wp\_getMediaLibrary](wp_xmlrpc_server/wp_getmedialibrary) — Retrieves a collection of media library items (or attachments)
* [wp\_getOptions](wp_xmlrpc_server/wp_getoptions) — Retrieve blog options.
* [wp\_getPage](wp_xmlrpc_server/wp_getpage) — Retrieve page.
* [wp\_getPageList](wp_xmlrpc_server/wp_getpagelist) — Retrieve page list.
* [wp\_getPages](wp_xmlrpc_server/wp_getpages) — Retrieve Pages.
* [wp\_getPageStatusList](wp_xmlrpc_server/wp_getpagestatuslist) — Retrieve page statuses.
* [wp\_getPageTemplates](wp_xmlrpc_server/wp_getpagetemplates) — Retrieve page templates.
* [wp\_getPost](wp_xmlrpc_server/wp_getpost) — Retrieve a post.
* [wp\_getPostFormats](wp_xmlrpc_server/wp_getpostformats) — Retrieves a list of post formats used by the site.
* [wp\_getPosts](wp_xmlrpc_server/wp_getposts) — Retrieve posts.
* [wp\_getPostStatusList](wp_xmlrpc_server/wp_getpoststatuslist) — Retrieve post statuses.
* [wp\_getPostType](wp_xmlrpc_server/wp_getposttype) — Retrieves a post type
* [wp\_getPostTypes](wp_xmlrpc_server/wp_getposttypes) — Retrieves a post types
* [wp\_getProfile](wp_xmlrpc_server/wp_getprofile) — Retrieve information about the requesting user.
* [wp\_getRevisions](wp_xmlrpc_server/wp_getrevisions) — Retrieve revisions for a specific post.
* [wp\_getTags](wp_xmlrpc_server/wp_gettags) — Get list of all tags
* [wp\_getTaxonomies](wp_xmlrpc_server/wp_gettaxonomies) — Retrieve all taxonomies.
* [wp\_getTaxonomy](wp_xmlrpc_server/wp_gettaxonomy) — Retrieve a taxonomy.
* [wp\_getTerm](wp_xmlrpc_server/wp_getterm) — Retrieve a term.
* [wp\_getTerms](wp_xmlrpc_server/wp_getterms) — Retrieve all terms for a taxonomy.
* [wp\_getUser](wp_xmlrpc_server/wp_getuser) — Retrieve a user.
* [wp\_getUsers](wp_xmlrpc_server/wp_getusers) — Retrieve users.
* [wp\_getUsersBlogs](wp_xmlrpc_server/wp_getusersblogs) — Retrieve the blogs of the user.
* [wp\_newCategory](wp_xmlrpc_server/wp_newcategory) — Create new category.
* [wp\_newComment](wp_xmlrpc_server/wp_newcomment) — Create new comment.
* [wp\_newPage](wp_xmlrpc_server/wp_newpage) — Create new page.
* [wp\_newPost](wp_xmlrpc_server/wp_newpost) — Create a new post for any registered post type.
* [wp\_newTerm](wp_xmlrpc_server/wp_newterm) — Create a new term.
* [wp\_restoreRevision](wp_xmlrpc_server/wp_restorerevision) — Restore a post revision
* [wp\_setOptions](wp_xmlrpc_server/wp_setoptions) — Update blog options.
* [wp\_suggestCategories](wp_xmlrpc_server/wp_suggestcategories) — Retrieve category list.
File: `wp-includes/class-wp-xmlrpc-server.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-xmlrpc-server.php/)
```
class wp_xmlrpc_server extends IXR_Server {
/**
* Methods.
*
* @var array
*/
public $methods;
/**
* Blog options.
*
* @var array
*/
public $blog_options;
/**
* IXR_Error instance.
*
* @var IXR_Error
*/
public $error;
/**
* Flags that the user authentication has failed in this instance of wp_xmlrpc_server.
*
* @var bool
*/
protected $auth_failed = false;
/**
* Flags that XML-RPC is enabled
*
* @var bool
*/
private $is_enabled;
/**
* Registers all of the XMLRPC methods that XMLRPC server understands.
*
* Sets up server and method property. Passes XMLRPC
* methods through the {@see 'xmlrpc_methods'} filter to allow plugins to extend
* or replace XML-RPC methods.
*
* @since 1.5.0
*/
public function __construct() {
$this->methods = array(
// WordPress API.
'wp.getUsersBlogs' => 'this:wp_getUsersBlogs',
'wp.newPost' => 'this:wp_newPost',
'wp.editPost' => 'this:wp_editPost',
'wp.deletePost' => 'this:wp_deletePost',
'wp.getPost' => 'this:wp_getPost',
'wp.getPosts' => 'this:wp_getPosts',
'wp.newTerm' => 'this:wp_newTerm',
'wp.editTerm' => 'this:wp_editTerm',
'wp.deleteTerm' => 'this:wp_deleteTerm',
'wp.getTerm' => 'this:wp_getTerm',
'wp.getTerms' => 'this:wp_getTerms',
'wp.getTaxonomy' => 'this:wp_getTaxonomy',
'wp.getTaxonomies' => 'this:wp_getTaxonomies',
'wp.getUser' => 'this:wp_getUser',
'wp.getUsers' => 'this:wp_getUsers',
'wp.getProfile' => 'this:wp_getProfile',
'wp.editProfile' => 'this:wp_editProfile',
'wp.getPage' => 'this:wp_getPage',
'wp.getPages' => 'this:wp_getPages',
'wp.newPage' => 'this:wp_newPage',
'wp.deletePage' => 'this:wp_deletePage',
'wp.editPage' => 'this:wp_editPage',
'wp.getPageList' => 'this:wp_getPageList',
'wp.getAuthors' => 'this:wp_getAuthors',
'wp.getCategories' => 'this:mw_getCategories', // Alias.
'wp.getTags' => 'this:wp_getTags',
'wp.newCategory' => 'this:wp_newCategory',
'wp.deleteCategory' => 'this:wp_deleteCategory',
'wp.suggestCategories' => 'this:wp_suggestCategories',
'wp.uploadFile' => 'this:mw_newMediaObject', // Alias.
'wp.deleteFile' => 'this:wp_deletePost', // Alias.
'wp.getCommentCount' => 'this:wp_getCommentCount',
'wp.getPostStatusList' => 'this:wp_getPostStatusList',
'wp.getPageStatusList' => 'this:wp_getPageStatusList',
'wp.getPageTemplates' => 'this:wp_getPageTemplates',
'wp.getOptions' => 'this:wp_getOptions',
'wp.setOptions' => 'this:wp_setOptions',
'wp.getComment' => 'this:wp_getComment',
'wp.getComments' => 'this:wp_getComments',
'wp.deleteComment' => 'this:wp_deleteComment',
'wp.editComment' => 'this:wp_editComment',
'wp.newComment' => 'this:wp_newComment',
'wp.getCommentStatusList' => 'this:wp_getCommentStatusList',
'wp.getMediaItem' => 'this:wp_getMediaItem',
'wp.getMediaLibrary' => 'this:wp_getMediaLibrary',
'wp.getPostFormats' => 'this:wp_getPostFormats',
'wp.getPostType' => 'this:wp_getPostType',
'wp.getPostTypes' => 'this:wp_getPostTypes',
'wp.getRevisions' => 'this:wp_getRevisions',
'wp.restoreRevision' => 'this:wp_restoreRevision',
// Blogger API.
'blogger.getUsersBlogs' => 'this:blogger_getUsersBlogs',
'blogger.getUserInfo' => 'this:blogger_getUserInfo',
'blogger.getPost' => 'this:blogger_getPost',
'blogger.getRecentPosts' => 'this:blogger_getRecentPosts',
'blogger.newPost' => 'this:blogger_newPost',
'blogger.editPost' => 'this:blogger_editPost',
'blogger.deletePost' => 'this:blogger_deletePost',
// MetaWeblog API (with MT extensions to structs).
'metaWeblog.newPost' => 'this:mw_newPost',
'metaWeblog.editPost' => 'this:mw_editPost',
'metaWeblog.getPost' => 'this:mw_getPost',
'metaWeblog.getRecentPosts' => 'this:mw_getRecentPosts',
'metaWeblog.getCategories' => 'this:mw_getCategories',
'metaWeblog.newMediaObject' => 'this:mw_newMediaObject',
// MetaWeblog API aliases for Blogger API.
// See http://www.xmlrpc.com/stories/storyReader$2460
'metaWeblog.deletePost' => 'this:blogger_deletePost',
'metaWeblog.getUsersBlogs' => 'this:blogger_getUsersBlogs',
// MovableType API.
'mt.getCategoryList' => 'this:mt_getCategoryList',
'mt.getRecentPostTitles' => 'this:mt_getRecentPostTitles',
'mt.getPostCategories' => 'this:mt_getPostCategories',
'mt.setPostCategories' => 'this:mt_setPostCategories',
'mt.supportedMethods' => 'this:mt_supportedMethods',
'mt.supportedTextFilters' => 'this:mt_supportedTextFilters',
'mt.getTrackbackPings' => 'this:mt_getTrackbackPings',
'mt.publishPost' => 'this:mt_publishPost',
// Pingback.
'pingback.ping' => 'this:pingback_ping',
'pingback.extensions.getPingbacks' => 'this:pingback_extensions_getPingbacks',
'demo.sayHello' => 'this:sayHello',
'demo.addTwoNumbers' => 'this:addTwoNumbers',
);
$this->initialise_blog_option_info();
/**
* Filters the methods exposed by the XML-RPC server.
*
* This filter can be used to add new methods, and remove built-in methods.
*
* @since 1.5.0
*
* @param string[] $methods An array of XML-RPC methods, keyed by their methodName.
*/
$this->methods = apply_filters( 'xmlrpc_methods', $this->methods );
$this->set_is_enabled();
}
/**
* Set wp_xmlrpc_server::$is_enabled property.
*
* Determine whether the xmlrpc server is enabled on this WordPress install
* and set the is_enabled property accordingly.
*
* @since 5.7.3
*/
private function set_is_enabled() {
/*
* Respect old get_option() filters left for back-compat when the 'enable_xmlrpc'
* option was deprecated in 3.5.0. Use the {@see 'xmlrpc_enabled'} hook instead.
*/
$is_enabled = apply_filters( 'pre_option_enable_xmlrpc', false );
if ( false === $is_enabled ) {
$is_enabled = apply_filters( 'option_enable_xmlrpc', true );
}
/**
* Filters whether XML-RPC methods requiring authentication are enabled.
*
* Contrary to the way it's named, this filter does not control whether XML-RPC is *fully*
* enabled, rather, it only controls whether XML-RPC methods requiring authentication - such
* as for publishing purposes - are enabled.
*
* Further, the filter does not control whether pingbacks or other custom endpoints that don't
* require authentication are enabled. This behavior is expected, and due to how parity was matched
* with the `enable_xmlrpc` UI option the filter replaced when it was introduced in 3.5.
*
* To disable XML-RPC methods that require authentication, use:
*
* add_filter( 'xmlrpc_enabled', '__return_false' );
*
* For more granular control over all XML-RPC methods and requests, see the {@see 'xmlrpc_methods'}
* and {@see 'xmlrpc_element_limit'} hooks.
*
* @since 3.5.0
*
* @param bool $is_enabled Whether XML-RPC is enabled. Default true.
*/
$this->is_enabled = apply_filters( 'xmlrpc_enabled', $is_enabled );
}
/**
* 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 array|IXR_Error|false Return value of the callback, false otherwise.
*/
public function __call( $name, $arguments ) {
if ( '_multisite_getUsersBlogs' === $name ) {
return $this->_multisite_getUsersBlogs( ...$arguments );
}
return false;
}
/**
* Serves the XML-RPC request.
*
* @since 2.9.0
*/
public function serve_request() {
$this->IXR_Server( $this->methods );
}
/**
* Test XMLRPC API by saying, "Hello!" to client.
*
* @since 1.5.0
*
* @return string Hello string response.
*/
public function sayHello() {
return 'Hello!';
}
/**
* Test XMLRPC API by adding two numbers for client.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 A number to add.
* @type int $1 A second number to add.
* }
* @return int Sum of the two given numbers.
*/
public function addTwoNumbers( $args ) {
$number1 = $args[0];
$number2 = $args[1];
return $number1 + $number2;
}
/**
* Log user in.
*
* @since 2.8.0
*
* @param string $username User's username.
* @param string $password User's password.
* @return WP_User|false WP_User object if authentication passed, false otherwise
*/
public function login( $username, $password ) {
if ( ! $this->is_enabled ) {
$this->error = new IXR_Error( 405, sprintf( __( 'XML-RPC services are disabled on this site.' ) ) );
return false;
}
if ( $this->auth_failed ) {
$user = new WP_Error( 'login_prevented' );
} else {
$user = wp_authenticate( $username, $password );
}
if ( is_wp_error( $user ) ) {
$this->error = new IXR_Error( 403, __( 'Incorrect username or password.' ) );
// Flag that authentication has failed once on this wp_xmlrpc_server instance.
$this->auth_failed = true;
/**
* Filters the XML-RPC user login error message.
*
* @since 3.5.0
*
* @param IXR_Error $error The XML-RPC error message.
* @param WP_Error $user WP_Error object.
*/
$this->error = apply_filters( 'xmlrpc_login_error', $this->error, $user );
return false;
}
wp_set_current_user( $user->ID );
return $user;
}
/**
* Check user's credentials. Deprecated.
*
* @since 1.5.0
* @deprecated 2.8.0 Use wp_xmlrpc_server::login()
* @see wp_xmlrpc_server::login()
*
* @param string $username User's username.
* @param string $password User's password.
* @return bool Whether authentication passed.
*/
public function login_pass_ok( $username, $password ) {
return (bool) $this->login( $username, $password );
}
/**
* Escape string or array of strings for database.
*
* @since 1.5.2
*
* @param string|array $data Escape single string or array of strings.
* @return string|void Returns with string is passed, alters by-reference
* when array is passed.
*/
public function escape( &$data ) {
if ( ! is_array( $data ) ) {
return wp_slash( $data );
}
foreach ( $data as &$v ) {
if ( is_array( $v ) ) {
$this->escape( $v );
} elseif ( ! is_object( $v ) ) {
$v = wp_slash( $v );
}
}
}
/**
* Send error response to client.
*
* Send an XML error response to the client. If the endpoint is enabled
* an HTTP 200 response is always sent per the XML-RPC specification.
*
* @since 5.7.3
*
* @param IXR_Error|string $error Error code or an error object.
* @param false $message Error message. Optional.
*/
public function error( $error, $message = false ) {
// Accepts either an error object or an error code and message
if ( $message && ! is_object( $error ) ) {
$error = new IXR_Error( $error, $message );
}
if ( ! $this->is_enabled ) {
status_header( $error->code );
}
$this->output( $error->getXml() );
}
/**
* Retrieve custom fields for post.
*
* @since 2.5.0
*
* @param int $post_id Post ID.
* @return array Custom fields, if exist.
*/
public function get_custom_fields( $post_id ) {
$post_id = (int) $post_id;
$custom_fields = array();
foreach ( (array) has_meta( $post_id ) as $meta ) {
// Don't expose protected fields.
if ( ! current_user_can( 'edit_post_meta', $post_id, $meta['meta_key'] ) ) {
continue;
}
$custom_fields[] = array(
'id' => $meta['meta_id'],
'key' => $meta['meta_key'],
'value' => $meta['meta_value'],
);
}
return $custom_fields;
}
/**
* Set custom fields for post.
*
* @since 2.5.0
*
* @param int $post_id Post ID.
* @param array $fields Custom fields.
*/
public function set_custom_fields( $post_id, $fields ) {
$post_id = (int) $post_id;
foreach ( (array) $fields as $meta ) {
if ( isset( $meta['id'] ) ) {
$meta['id'] = (int) $meta['id'];
$pmeta = get_metadata_by_mid( 'post', $meta['id'] );
if ( ! $pmeta || $pmeta->post_id != $post_id ) {
continue;
}
if ( isset( $meta['key'] ) ) {
$meta['key'] = wp_unslash( $meta['key'] );
if ( $meta['key'] !== $pmeta->meta_key ) {
continue;
}
$meta['value'] = wp_unslash( $meta['value'] );
if ( current_user_can( 'edit_post_meta', $post_id, $meta['key'] ) ) {
update_metadata_by_mid( 'post', $meta['id'], $meta['value'] );
}
} elseif ( current_user_can( 'delete_post_meta', $post_id, $pmeta->meta_key ) ) {
delete_metadata_by_mid( 'post', $meta['id'] );
}
} elseif ( current_user_can( 'add_post_meta', $post_id, wp_unslash( $meta['key'] ) ) ) {
add_post_meta( $post_id, $meta['key'], $meta['value'] );
}
}
}
/**
* Retrieve custom fields for a term.
*
* @since 4.9.0
*
* @param int $term_id Term ID.
* @return array Array of custom fields, if they exist.
*/
public function get_term_custom_fields( $term_id ) {
$term_id = (int) $term_id;
$custom_fields = array();
foreach ( (array) has_term_meta( $term_id ) as $meta ) {
if ( ! current_user_can( 'edit_term_meta', $term_id ) ) {
continue;
}
$custom_fields[] = array(
'id' => $meta['meta_id'],
'key' => $meta['meta_key'],
'value' => $meta['meta_value'],
);
}
return $custom_fields;
}
/**
* Set custom fields for a term.
*
* @since 4.9.0
*
* @param int $term_id Term ID.
* @param array $fields Custom fields.
*/
public function set_term_custom_fields( $term_id, $fields ) {
$term_id = (int) $term_id;
foreach ( (array) $fields as $meta ) {
if ( isset( $meta['id'] ) ) {
$meta['id'] = (int) $meta['id'];
$pmeta = get_metadata_by_mid( 'term', $meta['id'] );
if ( isset( $meta['key'] ) ) {
$meta['key'] = wp_unslash( $meta['key'] );
if ( $meta['key'] !== $pmeta->meta_key ) {
continue;
}
$meta['value'] = wp_unslash( $meta['value'] );
if ( current_user_can( 'edit_term_meta', $term_id ) ) {
update_metadata_by_mid( 'term', $meta['id'], $meta['value'] );
}
} elseif ( current_user_can( 'delete_term_meta', $term_id ) ) {
delete_metadata_by_mid( 'term', $meta['id'] );
}
} elseif ( current_user_can( 'add_term_meta', $term_id ) ) {
add_term_meta( $term_id, $meta['key'], $meta['value'] );
}
}
}
/**
* Set up blog options property.
*
* Passes property through {@see 'xmlrpc_blog_options'} filter.
*
* @since 2.6.0
*/
public function initialise_blog_option_info() {
$this->blog_options = array(
// Read-only options.
'software_name' => array(
'desc' => __( 'Software Name' ),
'readonly' => true,
'value' => 'WordPress',
),
'software_version' => array(
'desc' => __( 'Software Version' ),
'readonly' => true,
'value' => get_bloginfo( 'version' ),
),
'blog_url' => array(
'desc' => __( 'WordPress Address (URL)' ),
'readonly' => true,
'option' => 'siteurl',
),
'home_url' => array(
'desc' => __( 'Site Address (URL)' ),
'readonly' => true,
'option' => 'home',
),
'login_url' => array(
'desc' => __( 'Login Address (URL)' ),
'readonly' => true,
'value' => wp_login_url(),
),
'admin_url' => array(
'desc' => __( 'The URL to the admin area' ),
'readonly' => true,
'value' => get_admin_url(),
),
'image_default_link_type' => array(
'desc' => __( 'Image default link type' ),
'readonly' => true,
'option' => 'image_default_link_type',
),
'image_default_size' => array(
'desc' => __( 'Image default size' ),
'readonly' => true,
'option' => 'image_default_size',
),
'image_default_align' => array(
'desc' => __( 'Image default align' ),
'readonly' => true,
'option' => 'image_default_align',
),
'template' => array(
'desc' => __( 'Template' ),
'readonly' => true,
'option' => 'template',
),
'stylesheet' => array(
'desc' => __( 'Stylesheet' ),
'readonly' => true,
'option' => 'stylesheet',
),
'post_thumbnail' => array(
'desc' => __( 'Post Thumbnail' ),
'readonly' => true,
'value' => current_theme_supports( 'post-thumbnails' ),
),
// Updatable options.
'time_zone' => array(
'desc' => __( 'Time Zone' ),
'readonly' => false,
'option' => 'gmt_offset',
),
'blog_title' => array(
'desc' => __( 'Site Title' ),
'readonly' => false,
'option' => 'blogname',
),
'blog_tagline' => array(
'desc' => __( 'Site Tagline' ),
'readonly' => false,
'option' => 'blogdescription',
),
'date_format' => array(
'desc' => __( 'Date Format' ),
'readonly' => false,
'option' => 'date_format',
),
'time_format' => array(
'desc' => __( 'Time Format' ),
'readonly' => false,
'option' => 'time_format',
),
'users_can_register' => array(
'desc' => __( 'Allow new users to sign up' ),
'readonly' => false,
'option' => 'users_can_register',
),
'thumbnail_size_w' => array(
'desc' => __( 'Thumbnail Width' ),
'readonly' => false,
'option' => 'thumbnail_size_w',
),
'thumbnail_size_h' => array(
'desc' => __( 'Thumbnail Height' ),
'readonly' => false,
'option' => 'thumbnail_size_h',
),
'thumbnail_crop' => array(
'desc' => __( 'Crop thumbnail to exact dimensions' ),
'readonly' => false,
'option' => 'thumbnail_crop',
),
'medium_size_w' => array(
'desc' => __( 'Medium size image width' ),
'readonly' => false,
'option' => 'medium_size_w',
),
'medium_size_h' => array(
'desc' => __( 'Medium size image height' ),
'readonly' => false,
'option' => 'medium_size_h',
),
'medium_large_size_w' => array(
'desc' => __( 'Medium-Large size image width' ),
'readonly' => false,
'option' => 'medium_large_size_w',
),
'medium_large_size_h' => array(
'desc' => __( 'Medium-Large size image height' ),
'readonly' => false,
'option' => 'medium_large_size_h',
),
'large_size_w' => array(
'desc' => __( 'Large size image width' ),
'readonly' => false,
'option' => 'large_size_w',
),
'large_size_h' => array(
'desc' => __( 'Large size image height' ),
'readonly' => false,
'option' => 'large_size_h',
),
'default_comment_status' => array(
'desc' => __( 'Allow people to submit comments on new posts.' ),
'readonly' => false,
'option' => 'default_comment_status',
),
'default_ping_status' => array(
'desc' => __( 'Allow link notifications from other blogs (pingbacks and trackbacks) on new posts.' ),
'readonly' => false,
'option' => 'default_ping_status',
),
);
/**
* Filters the XML-RPC blog options property.
*
* @since 2.6.0
*
* @param array $blog_options An array of XML-RPC blog options.
*/
$this->blog_options = apply_filters( 'xmlrpc_blog_options', $this->blog_options );
}
/**
* Retrieve the blogs of the user.
*
* @since 2.6.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type string $0 Username.
* @type string $1 Password.
* }
* @return array|IXR_Error Array contains:
* - 'isAdmin'
* - 'isPrimary' - whether the blog is the user's primary blog
* - 'url'
* - 'blogid'
* - 'blogName'
* - 'xmlrpc' - url of xmlrpc endpoint
*/
public function wp_getUsersBlogs( $args ) {
if ( ! $this->minimum_args( $args, 2 ) ) {
return $this->error;
}
// If this isn't on WPMU then just use blogger_getUsersBlogs().
if ( ! is_multisite() ) {
array_unshift( $args, 1 );
return $this->blogger_getUsersBlogs( $args );
}
$this->escape( $args );
$username = $args[0];
$password = $args[1];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/**
* Fires after the XML-RPC user has been authenticated but before the rest of
* the method logic begins.
*
* All built-in XML-RPC methods use the action xmlrpc_call, with a parameter
* equal to the method's name, e.g., wp.getUsersBlogs, wp.newPost, etc.
*
* @since 2.5.0
* @since 5.7.0 Added the `$args` and `$server` parameters.
*
* @param string $name The method name.
* @param array|string $args The escaped arguments passed to the method.
* @param wp_xmlrpc_server $server The XML-RPC server instance.
*/
do_action( 'xmlrpc_call', 'wp.getUsersBlogs', $args, $this );
$blogs = (array) get_blogs_of_user( $user->ID );
$struct = array();
$primary_blog_id = 0;
$active_blog = get_active_blog_for_user( $user->ID );
if ( $active_blog ) {
$primary_blog_id = (int) $active_blog->blog_id;
}
foreach ( $blogs as $blog ) {
// Don't include blogs that aren't hosted at this site.
if ( get_current_network_id() != $blog->site_id ) {
continue;
}
$blog_id = $blog->userblog_id;
switch_to_blog( $blog_id );
$is_admin = current_user_can( 'manage_options' );
$is_primary = ( (int) $blog_id === $primary_blog_id );
$struct[] = array(
'isAdmin' => $is_admin,
'isPrimary' => $is_primary,
'url' => home_url( '/' ),
'blogid' => (string) $blog_id,
'blogName' => get_option( 'blogname' ),
'xmlrpc' => site_url( 'xmlrpc.php', 'rpc' ),
);
restore_current_blog();
}
return $struct;
}
/**
* Checks if the method received at least the minimum number of arguments.
*
* @since 3.4.0
*
* @param array $args An array of arguments to check.
* @param int $count Minimum number of arguments.
* @return bool True if `$args` contains at least `$count` arguments, false otherwise.
*/
protected function minimum_args( $args, $count ) {
if ( ! is_array( $args ) || count( $args ) < $count ) {
$this->error = new IXR_Error( 400, __( 'Insufficient arguments passed to this XML-RPC method.' ) );
return false;
}
return true;
}
/**
* Prepares taxonomy data for return in an XML-RPC object.
*
* @param WP_Taxonomy $taxonomy The unprepared taxonomy data.
* @param array $fields The subset of taxonomy fields to return.
* @return array The prepared taxonomy data.
*/
protected function _prepare_taxonomy( $taxonomy, $fields ) {
$_taxonomy = array(
'name' => $taxonomy->name,
'label' => $taxonomy->label,
'hierarchical' => (bool) $taxonomy->hierarchical,
'public' => (bool) $taxonomy->public,
'show_ui' => (bool) $taxonomy->show_ui,
'_builtin' => (bool) $taxonomy->_builtin,
);
if ( in_array( 'labels', $fields, true ) ) {
$_taxonomy['labels'] = (array) $taxonomy->labels;
}
if ( in_array( 'cap', $fields, true ) ) {
$_taxonomy['cap'] = (array) $taxonomy->cap;
}
if ( in_array( 'menu', $fields, true ) ) {
$_taxonomy['show_in_menu'] = (bool) $taxonomy->show_in_menu;
}
if ( in_array( 'object_type', $fields, true ) ) {
$_taxonomy['object_type'] = array_unique( (array) $taxonomy->object_type );
}
/**
* Filters XML-RPC-prepared data for the given taxonomy.
*
* @since 3.4.0
*
* @param array $_taxonomy An array of taxonomy data.
* @param WP_Taxonomy $taxonomy Taxonomy object.
* @param array $fields The subset of taxonomy fields to return.
*/
return apply_filters( 'xmlrpc_prepare_taxonomy', $_taxonomy, $taxonomy, $fields );
}
/**
* Prepares term data for return in an XML-RPC object.
*
* @param array|object $term The unprepared term data.
* @return array The prepared term data.
*/
protected function _prepare_term( $term ) {
$_term = $term;
if ( ! is_array( $_term ) ) {
$_term = get_object_vars( $_term );
}
// For integers which may be larger than XML-RPC supports ensure we return strings.
$_term['term_id'] = (string) $_term['term_id'];
$_term['term_group'] = (string) $_term['term_group'];
$_term['term_taxonomy_id'] = (string) $_term['term_taxonomy_id'];
$_term['parent'] = (string) $_term['parent'];
// Count we are happy to return as an integer because people really shouldn't use terms that much.
$_term['count'] = (int) $_term['count'];
// Get term meta.
$_term['custom_fields'] = $this->get_term_custom_fields( $_term['term_id'] );
/**
* Filters XML-RPC-prepared data for the given term.
*
* @since 3.4.0
*
* @param array $_term An array of term data.
* @param array|object $term Term object or array.
*/
return apply_filters( 'xmlrpc_prepare_term', $_term, $term );
}
/**
* Convert a WordPress date string to an IXR_Date object.
*
* @param string $date Date string to convert.
* @return IXR_Date IXR_Date object.
*/
protected function _convert_date( $date ) {
if ( '0000-00-00 00:00:00' === $date ) {
return new IXR_Date( '00000000T00:00:00Z' );
}
return new IXR_Date( mysql2date( 'Ymd\TH:i:s', $date, false ) );
}
/**
* Convert a WordPress GMT date string to an IXR_Date object.
*
* @param string $date_gmt WordPress GMT date string.
* @param string $date Date string.
* @return IXR_Date IXR_Date object.
*/
protected function _convert_date_gmt( $date_gmt, $date ) {
if ( '0000-00-00 00:00:00' !== $date && '0000-00-00 00:00:00' === $date_gmt ) {
return new IXR_Date( get_gmt_from_date( mysql2date( 'Y-m-d H:i:s', $date, false ), 'Ymd\TH:i:s' ) );
}
return $this->_convert_date( $date_gmt );
}
/**
* Prepares post data for return in an XML-RPC object.
*
* @param array $post The unprepared post data.
* @param array $fields The subset of post type fields to return.
* @return array The prepared post data.
*/
protected function _prepare_post( $post, $fields ) {
// Holds the data for this post. built up based on $fields.
$_post = array( 'post_id' => (string) $post['ID'] );
// Prepare common post fields.
$post_fields = array(
'post_title' => $post['post_title'],
'post_date' => $this->_convert_date( $post['post_date'] ),
'post_date_gmt' => $this->_convert_date_gmt( $post['post_date_gmt'], $post['post_date'] ),
'post_modified' => $this->_convert_date( $post['post_modified'] ),
'post_modified_gmt' => $this->_convert_date_gmt( $post['post_modified_gmt'], $post['post_modified'] ),
'post_status' => $post['post_status'],
'post_type' => $post['post_type'],
'post_name' => $post['post_name'],
'post_author' => $post['post_author'],
'post_password' => $post['post_password'],
'post_excerpt' => $post['post_excerpt'],
'post_content' => $post['post_content'],
'post_parent' => (string) $post['post_parent'],
'post_mime_type' => $post['post_mime_type'],
'link' => get_permalink( $post['ID'] ),
'guid' => $post['guid'],
'menu_order' => (int) $post['menu_order'],
'comment_status' => $post['comment_status'],
'ping_status' => $post['ping_status'],
'sticky' => ( 'post' === $post['post_type'] && is_sticky( $post['ID'] ) ),
);
// Thumbnail.
$post_fields['post_thumbnail'] = array();
$thumbnail_id = get_post_thumbnail_id( $post['ID'] );
if ( $thumbnail_id ) {
$thumbnail_size = current_theme_supports( 'post-thumbnail' ) ? 'post-thumbnail' : 'thumbnail';
$post_fields['post_thumbnail'] = $this->_prepare_media_item( get_post( $thumbnail_id ), $thumbnail_size );
}
// Consider future posts as published.
if ( 'future' === $post_fields['post_status'] ) {
$post_fields['post_status'] = 'publish';
}
// Fill in blank post format.
$post_fields['post_format'] = get_post_format( $post['ID'] );
if ( empty( $post_fields['post_format'] ) ) {
$post_fields['post_format'] = 'standard';
}
// Merge requested $post_fields fields into $_post.
if ( in_array( 'post', $fields, true ) ) {
$_post = array_merge( $_post, $post_fields );
} else {
$requested_fields = array_intersect_key( $post_fields, array_flip( $fields ) );
$_post = array_merge( $_post, $requested_fields );
}
$all_taxonomy_fields = in_array( 'taxonomies', $fields, true );
if ( $all_taxonomy_fields || in_array( 'terms', $fields, true ) ) {
$post_type_taxonomies = get_object_taxonomies( $post['post_type'], 'names' );
$terms = wp_get_object_terms( $post['ID'], $post_type_taxonomies );
$_post['terms'] = array();
foreach ( $terms as $term ) {
$_post['terms'][] = $this->_prepare_term( $term );
}
}
if ( in_array( 'custom_fields', $fields, true ) ) {
$_post['custom_fields'] = $this->get_custom_fields( $post['ID'] );
}
if ( in_array( 'enclosure', $fields, true ) ) {
$_post['enclosure'] = array();
$enclosures = (array) get_post_meta( $post['ID'], 'enclosure' );
if ( ! empty( $enclosures ) ) {
$encdata = explode( "\n", $enclosures[0] );
$_post['enclosure']['url'] = trim( htmlspecialchars( $encdata[0] ) );
$_post['enclosure']['length'] = (int) trim( $encdata[1] );
$_post['enclosure']['type'] = trim( $encdata[2] );
}
}
/**
* Filters XML-RPC-prepared date for the given post.
*
* @since 3.4.0
*
* @param array $_post An array of modified post data.
* @param array $post An array of post data.
* @param array $fields An array of post fields.
*/
return apply_filters( 'xmlrpc_prepare_post', $_post, $post, $fields );
}
/**
* Prepares post data for return in an XML-RPC object.
*
* @since 3.4.0
* @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
*
* @param WP_Post_Type $post_type Post type object.
* @param array $fields The subset of post fields to return.
* @return array The prepared post type data.
*/
protected function _prepare_post_type( $post_type, $fields ) {
$_post_type = array(
'name' => $post_type->name,
'label' => $post_type->label,
'hierarchical' => (bool) $post_type->hierarchical,
'public' => (bool) $post_type->public,
'show_ui' => (bool) $post_type->show_ui,
'_builtin' => (bool) $post_type->_builtin,
'has_archive' => (bool) $post_type->has_archive,
'supports' => get_all_post_type_supports( $post_type->name ),
);
if ( in_array( 'labels', $fields, true ) ) {
$_post_type['labels'] = (array) $post_type->labels;
}
if ( in_array( 'cap', $fields, true ) ) {
$_post_type['cap'] = (array) $post_type->cap;
$_post_type['map_meta_cap'] = (bool) $post_type->map_meta_cap;
}
if ( in_array( 'menu', $fields, true ) ) {
$_post_type['menu_position'] = (int) $post_type->menu_position;
$_post_type['menu_icon'] = $post_type->menu_icon;
$_post_type['show_in_menu'] = (bool) $post_type->show_in_menu;
}
if ( in_array( 'taxonomies', $fields, true ) ) {
$_post_type['taxonomies'] = get_object_taxonomies( $post_type->name, 'names' );
}
/**
* Filters XML-RPC-prepared date for the given post type.
*
* @since 3.4.0
* @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object.
*
* @param array $_post_type An array of post type data.
* @param WP_Post_Type $post_type Post type object.
*/
return apply_filters( 'xmlrpc_prepare_post_type', $_post_type, $post_type );
}
/**
* Prepares media item data for return in an XML-RPC object.
*
* @param WP_Post $media_item The unprepared media item data.
* @param string $thumbnail_size The image size to use for the thumbnail URL.
* @return array The prepared media item data.
*/
protected function _prepare_media_item( $media_item, $thumbnail_size = 'thumbnail' ) {
$_media_item = array(
'attachment_id' => (string) $media_item->ID,
'date_created_gmt' => $this->_convert_date_gmt( $media_item->post_date_gmt, $media_item->post_date ),
'parent' => $media_item->post_parent,
'link' => wp_get_attachment_url( $media_item->ID ),
'title' => $media_item->post_title,
'caption' => $media_item->post_excerpt,
'description' => $media_item->post_content,
'metadata' => wp_get_attachment_metadata( $media_item->ID ),
'type' => $media_item->post_mime_type,
);
$thumbnail_src = image_downsize( $media_item->ID, $thumbnail_size );
if ( $thumbnail_src ) {
$_media_item['thumbnail'] = $thumbnail_src[0];
} else {
$_media_item['thumbnail'] = $_media_item['link'];
}
/**
* Filters XML-RPC-prepared data for the given media item.
*
* @since 3.4.0
*
* @param array $_media_item An array of media item data.
* @param WP_Post $media_item Media item object.
* @param string $thumbnail_size Image size.
*/
return apply_filters( 'xmlrpc_prepare_media_item', $_media_item, $media_item, $thumbnail_size );
}
/**
* Prepares page data for return in an XML-RPC object.
*
* @param WP_Post $page The unprepared page data.
* @return array The prepared page data.
*/
protected function _prepare_page( $page ) {
// Get all of the page content and link.
$full_page = get_extended( $page->post_content );
$link = get_permalink( $page->ID );
// Get info the page parent if there is one.
$parent_title = '';
if ( ! empty( $page->post_parent ) ) {
$parent = get_post( $page->post_parent );
$parent_title = $parent->post_title;
}
// Determine comment and ping settings.
$allow_comments = comments_open( $page->ID ) ? 1 : 0;
$allow_pings = pings_open( $page->ID ) ? 1 : 0;
// Format page date.
$page_date = $this->_convert_date( $page->post_date );
$page_date_gmt = $this->_convert_date_gmt( $page->post_date_gmt, $page->post_date );
// Pull the categories info together.
$categories = array();
if ( is_object_in_taxonomy( 'page', 'category' ) ) {
foreach ( wp_get_post_categories( $page->ID ) as $cat_id ) {
$categories[] = get_cat_name( $cat_id );
}
}
// Get the author info.
$author = get_userdata( $page->post_author );
$page_template = get_page_template_slug( $page->ID );
if ( empty( $page_template ) ) {
$page_template = 'default';
}
$_page = array(
'dateCreated' => $page_date,
'userid' => $page->post_author,
'page_id' => $page->ID,
'page_status' => $page->post_status,
'description' => $full_page['main'],
'title' => $page->post_title,
'link' => $link,
'permaLink' => $link,
'categories' => $categories,
'excerpt' => $page->post_excerpt,
'text_more' => $full_page['extended'],
'mt_allow_comments' => $allow_comments,
'mt_allow_pings' => $allow_pings,
'wp_slug' => $page->post_name,
'wp_password' => $page->post_password,
'wp_author' => $author->display_name,
'wp_page_parent_id' => $page->post_parent,
'wp_page_parent_title' => $parent_title,
'wp_page_order' => $page->menu_order,
'wp_author_id' => (string) $author->ID,
'wp_author_display_name' => $author->display_name,
'date_created_gmt' => $page_date_gmt,
'custom_fields' => $this->get_custom_fields( $page->ID ),
'wp_page_template' => $page_template,
);
/**
* Filters XML-RPC-prepared data for the given page.
*
* @since 3.4.0
*
* @param array $_page An array of page data.
* @param WP_Post $page Page object.
*/
return apply_filters( 'xmlrpc_prepare_page', $_page, $page );
}
/**
* Prepares comment data for return in an XML-RPC object.
*
* @param WP_Comment $comment The unprepared comment data.
* @return array The prepared comment data.
*/
protected function _prepare_comment( $comment ) {
// Format page date.
$comment_date_gmt = $this->_convert_date_gmt( $comment->comment_date_gmt, $comment->comment_date );
if ( '0' == $comment->comment_approved ) {
$comment_status = 'hold';
} elseif ( 'spam' === $comment->comment_approved ) {
$comment_status = 'spam';
} elseif ( '1' == $comment->comment_approved ) {
$comment_status = 'approve';
} else {
$comment_status = $comment->comment_approved;
}
$_comment = array(
'date_created_gmt' => $comment_date_gmt,
'user_id' => $comment->user_id,
'comment_id' => $comment->comment_ID,
'parent' => $comment->comment_parent,
'status' => $comment_status,
'content' => $comment->comment_content,
'link' => get_comment_link( $comment ),
'post_id' => $comment->comment_post_ID,
'post_title' => get_the_title( $comment->comment_post_ID ),
'author' => $comment->comment_author,
'author_url' => $comment->comment_author_url,
'author_email' => $comment->comment_author_email,
'author_ip' => $comment->comment_author_IP,
'type' => $comment->comment_type,
);
/**
* Filters XML-RPC-prepared data for the given comment.
*
* @since 3.4.0
*
* @param array $_comment An array of prepared comment data.
* @param WP_Comment $comment Comment object.
*/
return apply_filters( 'xmlrpc_prepare_comment', $_comment, $comment );
}
/**
* Prepares user data for return in an XML-RPC object.
*
* @param WP_User $user The unprepared user object.
* @param array $fields The subset of user fields to return.
* @return array The prepared user data.
*/
protected function _prepare_user( $user, $fields ) {
$_user = array( 'user_id' => (string) $user->ID );
$user_fields = array(
'username' => $user->user_login,
'first_name' => $user->user_firstname,
'last_name' => $user->user_lastname,
'registered' => $this->_convert_date( $user->user_registered ),
'bio' => $user->user_description,
'email' => $user->user_email,
'nickname' => $user->nickname,
'nicename' => $user->user_nicename,
'url' => $user->user_url,
'display_name' => $user->display_name,
'roles' => $user->roles,
);
if ( in_array( 'all', $fields, true ) ) {
$_user = array_merge( $_user, $user_fields );
} else {
if ( in_array( 'basic', $fields, true ) ) {
$basic_fields = array( 'username', 'email', 'registered', 'display_name', 'nicename' );
$fields = array_merge( $fields, $basic_fields );
}
$requested_fields = array_intersect_key( $user_fields, array_flip( $fields ) );
$_user = array_merge( $_user, $requested_fields );
}
/**
* Filters XML-RPC-prepared data for the given user.
*
* @since 3.5.0
*
* @param array $_user An array of user data.
* @param WP_User $user User object.
* @param array $fields An array of user fields.
*/
return apply_filters( 'xmlrpc_prepare_user', $_user, $user, $fields );
}
/**
* Create a new post for any registered post type.
*
* @since 3.4.0
*
* @link https://en.wikipedia.org/wiki/RSS_enclosure for information on RSS enclosures.
*
* @param array $args {
* Method arguments. Note: top-level arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 {
* Content struct for adding a new post. See wp_insert_post() for information on
* additional post fields
*
* @type string $post_type Post type. Default 'post'.
* @type string $post_status Post status. Default 'draft'
* @type string $post_title Post title.
* @type int $post_author Post author ID.
* @type string $post_excerpt Post excerpt.
* @type string $post_content Post content.
* @type string $post_date_gmt Post date in GMT.
* @type string $post_date Post date.
* @type string $post_password Post password (20-character limit).
* @type string $comment_status Post comment enabled status. Accepts 'open' or 'closed'.
* @type string $ping_status Post ping status. Accepts 'open' or 'closed'.
* @type bool $sticky Whether the post should be sticky. Automatically false if
* `$post_status` is 'private'.
* @type int $post_thumbnail ID of an image to use as the post thumbnail/featured image.
* @type array $custom_fields Array of meta key/value pairs to add to the post.
* @type array $terms Associative array with taxonomy names as keys and arrays
* of term IDs as values.
* @type array $terms_names Associative array with taxonomy names as keys and arrays
* of term names as values.
* @type array $enclosure {
* Array of feed enclosure data to add to post meta.
*
* @type string $url URL for the feed enclosure.
* @type int $length Size in bytes of the enclosure.
* @type string $type Mime-type for the enclosure.
* }
* }
* }
* @return int|IXR_Error Post ID on success, IXR_Error instance otherwise.
*/
public function wp_newPost( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$content_struct = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
// Convert the date field back to IXR form.
if ( isset( $content_struct['post_date'] ) && ! ( $content_struct['post_date'] instanceof IXR_Date ) ) {
$content_struct['post_date'] = $this->_convert_date( $content_struct['post_date'] );
}
/*
* Ignore the existing GMT date if it is empty or a non-GMT date was supplied in $content_struct,
* since _insert_post() will ignore the non-GMT date if the GMT date is set.
*/
if ( isset( $content_struct['post_date_gmt'] ) && ! ( $content_struct['post_date_gmt'] instanceof IXR_Date ) ) {
if ( '0000-00-00 00:00:00' === $content_struct['post_date_gmt'] || isset( $content_struct['post_date'] ) ) {
unset( $content_struct['post_date_gmt'] );
} else {
$content_struct['post_date_gmt'] = $this->_convert_date( $content_struct['post_date_gmt'] );
}
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.newPost', $args, $this );
unset( $content_struct['ID'] );
return $this->_insert_post( $user, $content_struct );
}
/**
* Helper method for filtering out elements from an array.
*
* @since 3.4.0
*
* @param int $count Number to compare to one.
* @return bool True if the number is greater than one, false otherwise.
*/
private function _is_greater_than_one( $count ) {
return $count > 1;
}
/**
* Encapsulate the logic for sticking a post
* and determining if the user has permission to do so
*
* @since 4.3.0
*
* @param array $post_data
* @param bool $update
* @return void|IXR_Error
*/
private function _toggle_sticky( $post_data, $update = false ) {
$post_type = get_post_type_object( $post_data['post_type'] );
// Private and password-protected posts cannot be stickied.
if ( 'private' === $post_data['post_status'] || ! empty( $post_data['post_password'] ) ) {
// Error if the client tried to stick the post, otherwise, silently unstick.
if ( ! empty( $post_data['sticky'] ) ) {
return new IXR_Error( 401, __( 'Sorry, you cannot stick a private post.' ) );
}
if ( $update ) {
unstick_post( $post_data['ID'] );
}
} elseif ( isset( $post_data['sticky'] ) ) {
if ( ! current_user_can( $post_type->cap->edit_others_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to make posts sticky.' ) );
}
$sticky = wp_validate_boolean( $post_data['sticky'] );
if ( $sticky ) {
stick_post( $post_data['ID'] );
} else {
unstick_post( $post_data['ID'] );
}
}
}
/**
* Helper method for wp_newPost() and wp_editPost(), containing shared logic.
*
* @since 3.4.0
*
* @see wp_insert_post()
*
* @param WP_User $user The post author if post_author isn't set in $content_struct.
* @param array|IXR_Error $content_struct Post data to insert.
* @return IXR_Error|string
*/
protected function _insert_post( $user, $content_struct ) {
$defaults = array(
'post_status' => 'draft',
'post_type' => 'post',
'post_author' => 0,
'post_password' => '',
'post_excerpt' => '',
'post_content' => '',
'post_title' => '',
'post_date' => '',
'post_date_gmt' => '',
'post_format' => null,
'post_name' => null,
'post_thumbnail' => null,
'post_parent' => 0,
'ping_status' => '',
'comment_status' => '',
'custom_fields' => null,
'terms_names' => null,
'terms' => null,
'sticky' => null,
'enclosure' => null,
'ID' => null,
);
$post_data = wp_parse_args( array_intersect_key( $content_struct, $defaults ), $defaults );
$post_type = get_post_type_object( $post_data['post_type'] );
if ( ! $post_type ) {
return new IXR_Error( 403, __( 'Invalid post type.' ) );
}
$update = ! empty( $post_data['ID'] );
if ( $update ) {
if ( ! get_post( $post_data['ID'] ) ) {
return new IXR_Error( 401, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_data['ID'] ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
if ( get_post_type( $post_data['ID'] ) !== $post_data['post_type'] ) {
return new IXR_Error( 401, __( 'The post type may not be changed.' ) );
}
} else {
if ( ! current_user_can( $post_type->cap->create_posts ) || ! current_user_can( $post_type->cap->edit_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to post on this site.' ) );
}
}
switch ( $post_data['post_status'] ) {
case 'draft':
case 'pending':
break;
case 'private':
if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to create private posts in this post type.' ) );
}
break;
case 'publish':
case 'future':
if ( ! current_user_can( $post_type->cap->publish_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish posts in this post type.' ) );
}
break;
default:
if ( ! get_post_status_object( $post_data['post_status'] ) ) {
$post_data['post_status'] = 'draft';
}
break;
}
if ( ! empty( $post_data['post_password'] ) && ! current_user_can( $post_type->cap->publish_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to create password protected posts in this post type.' ) );
}
$post_data['post_author'] = absint( $post_data['post_author'] );
if ( ! empty( $post_data['post_author'] ) && $post_data['post_author'] != $user->ID ) {
if ( ! current_user_can( $post_type->cap->edit_others_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to create posts as this user.' ) );
}
$author = get_userdata( $post_data['post_author'] );
if ( ! $author ) {
return new IXR_Error( 404, __( 'Invalid author ID.' ) );
}
} else {
$post_data['post_author'] = $user->ID;
}
if ( 'open' !== $post_data['comment_status'] && 'closed' !== $post_data['comment_status'] ) {
unset( $post_data['comment_status'] );
}
if ( 'open' !== $post_data['ping_status'] && 'closed' !== $post_data['ping_status'] ) {
unset( $post_data['ping_status'] );
}
// Do some timestamp voodoo.
if ( ! empty( $post_data['post_date_gmt'] ) ) {
// We know this is supposed to be GMT, so we're going to slap that Z on there by force.
$dateCreated = rtrim( $post_data['post_date_gmt']->getIso(), 'Z' ) . 'Z';
} elseif ( ! empty( $post_data['post_date'] ) ) {
$dateCreated = $post_data['post_date']->getIso();
}
// Default to not flagging the post date to be edited unless it's intentional.
$post_data['edit_date'] = false;
if ( ! empty( $dateCreated ) ) {
$post_data['post_date'] = iso8601_to_datetime( $dateCreated );
$post_data['post_date_gmt'] = iso8601_to_datetime( $dateCreated, 'gmt' );
// Flag the post date to be edited.
$post_data['edit_date'] = true;
}
if ( ! isset( $post_data['ID'] ) ) {
$post_data['ID'] = get_default_post_to_edit( $post_data['post_type'], true )->ID;
}
$post_ID = $post_data['ID'];
if ( 'post' === $post_data['post_type'] ) {
$error = $this->_toggle_sticky( $post_data, $update );
if ( $error ) {
return $error;
}
}
if ( isset( $post_data['post_thumbnail'] ) ) {
// Empty value deletes, non-empty value adds/updates.
if ( ! $post_data['post_thumbnail'] ) {
delete_post_thumbnail( $post_ID );
} elseif ( ! get_post( absint( $post_data['post_thumbnail'] ) ) ) {
return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
}
set_post_thumbnail( $post_ID, $post_data['post_thumbnail'] );
unset( $content_struct['post_thumbnail'] );
}
if ( isset( $post_data['custom_fields'] ) ) {
$this->set_custom_fields( $post_ID, $post_data['custom_fields'] );
}
if ( isset( $post_data['terms'] ) || isset( $post_data['terms_names'] ) ) {
$post_type_taxonomies = get_object_taxonomies( $post_data['post_type'], 'objects' );
// Accumulate term IDs from terms and terms_names.
$terms = array();
// First validate the terms specified by ID.
if ( isset( $post_data['terms'] ) && is_array( $post_data['terms'] ) ) {
$taxonomies = array_keys( $post_data['terms'] );
// Validating term IDs.
foreach ( $taxonomies as $taxonomy ) {
if ( ! array_key_exists( $taxonomy, $post_type_taxonomies ) ) {
return new IXR_Error( 401, __( 'Sorry, one of the given taxonomies is not supported by the post type.' ) );
}
if ( ! current_user_can( $post_type_taxonomies[ $taxonomy ]->cap->assign_terms ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign a term to one of the given taxonomies.' ) );
}
$term_ids = $post_data['terms'][ $taxonomy ];
$terms[ $taxonomy ] = array();
foreach ( $term_ids as $term_id ) {
$term = get_term_by( 'id', $term_id, $taxonomy );
if ( ! $term ) {
return new IXR_Error( 403, __( 'Invalid term ID.' ) );
}
$terms[ $taxonomy ][] = (int) $term_id;
}
}
}
// Now validate terms specified by name.
if ( isset( $post_data['terms_names'] ) && is_array( $post_data['terms_names'] ) ) {
$taxonomies = array_keys( $post_data['terms_names'] );
foreach ( $taxonomies as $taxonomy ) {
if ( ! array_key_exists( $taxonomy, $post_type_taxonomies ) ) {
return new IXR_Error( 401, __( 'Sorry, one of the given taxonomies is not supported by the post type.' ) );
}
if ( ! current_user_can( $post_type_taxonomies[ $taxonomy ]->cap->assign_terms ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign a term to one of the given taxonomies.' ) );
}
/*
* For hierarchical taxonomies, we can't assign a term when multiple terms
* in the hierarchy share the same name.
*/
$ambiguous_terms = array();
if ( is_taxonomy_hierarchical( $taxonomy ) ) {
$tax_term_names = get_terms(
array(
'taxonomy' => $taxonomy,
'fields' => 'names',
'hide_empty' => false,
)
);
// Count the number of terms with the same name.
$tax_term_names_count = array_count_values( $tax_term_names );
// Filter out non-ambiguous term names.
$ambiguous_tax_term_counts = array_filter( $tax_term_names_count, array( $this, '_is_greater_than_one' ) );
$ambiguous_terms = array_keys( $ambiguous_tax_term_counts );
}
$term_names = $post_data['terms_names'][ $taxonomy ];
foreach ( $term_names as $term_name ) {
if ( in_array( $term_name, $ambiguous_terms, true ) ) {
return new IXR_Error( 401, __( 'Ambiguous term name used in a hierarchical taxonomy. Please use term ID instead.' ) );
}
$term = get_term_by( 'name', $term_name, $taxonomy );
if ( ! $term ) {
// Term doesn't exist, so check that the user is allowed to create new terms.
if ( ! current_user_can( $post_type_taxonomies[ $taxonomy ]->cap->edit_terms ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to add a term to one of the given taxonomies.' ) );
}
// Create the new term.
$term_info = wp_insert_term( $term_name, $taxonomy );
if ( is_wp_error( $term_info ) ) {
return new IXR_Error( 500, $term_info->get_error_message() );
}
$terms[ $taxonomy ][] = (int) $term_info['term_id'];
} else {
$terms[ $taxonomy ][] = (int) $term->term_id;
}
}
}
}
$post_data['tax_input'] = $terms;
unset( $post_data['terms'], $post_data['terms_names'] );
}
if ( isset( $post_data['post_format'] ) ) {
$format = set_post_format( $post_ID, $post_data['post_format'] );
if ( is_wp_error( $format ) ) {
return new IXR_Error( 500, $format->get_error_message() );
}
unset( $post_data['post_format'] );
}
// Handle enclosures.
$enclosure = isset( $post_data['enclosure'] ) ? $post_data['enclosure'] : null;
$this->add_enclosure_if_new( $post_ID, $enclosure );
$this->attach_uploads( $post_ID, $post_data['post_content'] );
/**
* Filters post data array to be inserted via XML-RPC.
*
* @since 3.4.0
*
* @param array $post_data Parsed array of post data.
* @param array $content_struct Post data array.
*/
$post_data = apply_filters( 'xmlrpc_wp_insert_post_data', $post_data, $content_struct );
// Remove all null values to allow for using the insert/update post default values for those keys instead.
$post_data = array_filter(
$post_data,
static function ( $value ) {
return null !== $value;
}
);
$post_ID = $update ? wp_update_post( $post_data, true ) : wp_insert_post( $post_data, true );
if ( is_wp_error( $post_ID ) ) {
return new IXR_Error( 500, $post_ID->get_error_message() );
}
if ( ! $post_ID ) {
if ( $update ) {
return new IXR_Error( 401, __( 'Sorry, the post could not be updated.' ) );
} else {
return new IXR_Error( 401, __( 'Sorry, the post could not be created.' ) );
}
}
return (string) $post_ID;
}
/**
* Edit a post for any registered post type.
*
* The $content_struct parameter only needs to contain fields that
* should be changed. All other fields will retain their existing values.
*
* @since 3.4.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Post ID.
* @type array $4 Extra content arguments.
* }
* @return true|IXR_Error True on success, IXR_Error on failure.
*/
public function wp_editPost( $args ) {
if ( ! $this->minimum_args( $args, 5 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$post_id = (int) $args[3];
$content_struct = $args[4];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.editPost', $args, $this );
$post = get_post( $post_id, ARRAY_A );
if ( empty( $post['ID'] ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( isset( $content_struct['if_not_modified_since'] ) ) {
// If the post has been modified since the date provided, return an error.
if ( mysql2date( 'U', $post['post_modified_gmt'] ) > $content_struct['if_not_modified_since']->getTimestamp() ) {
return new IXR_Error( 409, __( 'There is a revision of this post that is more recent.' ) );
}
}
// Convert the date field back to IXR form.
$post['post_date'] = $this->_convert_date( $post['post_date'] );
/*
* Ignore the existing GMT date if it is empty or a non-GMT date was supplied in $content_struct,
* since _insert_post() will ignore the non-GMT date if the GMT date is set.
*/
if ( '0000-00-00 00:00:00' === $post['post_date_gmt'] || isset( $content_struct['post_date'] ) ) {
unset( $post['post_date_gmt'] );
} else {
$post['post_date_gmt'] = $this->_convert_date( $post['post_date_gmt'] );
}
/*
* If the API client did not provide 'post_date', then we must not perpetuate the value that
* was stored in the database, or it will appear to be an intentional edit. Conveying it here
* as if it was coming from the API client will cause an otherwise zeroed out 'post_date_gmt'
* to get set with the value that was originally stored in the database when the draft was created.
*/
if ( ! isset( $content_struct['post_date'] ) ) {
unset( $post['post_date'] );
}
$this->escape( $post );
$merged_content_struct = array_merge( $post, $content_struct );
$retval = $this->_insert_post( $user, $merged_content_struct );
if ( $retval instanceof IXR_Error ) {
return $retval;
}
return true;
}
/**
* Delete a post for any registered post type.
*
* @since 3.4.0
*
* @see wp_delete_post()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Post ID.
* }
* @return true|IXR_Error True on success, IXR_Error instance on failure.
*/
public function wp_deletePost( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$post_id = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.deletePost', $args, $this );
$post = get_post( $post_id, ARRAY_A );
if ( empty( $post['ID'] ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'delete_post', $post_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this post.' ) );
}
$result = wp_delete_post( $post_id );
if ( ! $result ) {
return new IXR_Error( 500, __( 'Sorry, the post could not be deleted.' ) );
}
return true;
}
/**
* Retrieve a post.
*
* @since 3.4.0
*
* The optional $fields parameter specifies what fields will be included
* in the response array. This should be a list of field names. 'post_id' will
* always be included in the response regardless of the value of $fields.
*
* Instead of, or in addition to, individual field names, conceptual group
* names can be used to specify multiple fields. The available conceptual
* groups are 'post' (all basic fields), 'taxonomies', 'custom_fields',
* and 'enclosure'.
*
* @see get_post()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Post ID.
* @type array $4 Optional. The subset of post type fields to return.
* }
* @return array|IXR_Error Array contains (based on $fields parameter):
* - 'post_id'
* - 'post_title'
* - 'post_date'
* - 'post_date_gmt'
* - 'post_modified'
* - 'post_modified_gmt'
* - 'post_status'
* - 'post_type'
* - 'post_name'
* - 'post_author'
* - 'post_password'
* - 'post_excerpt'
* - 'post_content'
* - 'link'
* - 'comment_status'
* - 'ping_status'
* - 'sticky'
* - 'custom_fields'
* - 'terms'
* - 'categories'
* - 'tags'
* - 'enclosure'
*/
public function wp_getPost( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$post_id = (int) $args[3];
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/**
* Filters the list of post query fields used by the given XML-RPC method.
*
* @since 3.4.0
*
* @param array $fields Array of post fields. Default array contains 'post', 'terms', and 'custom_fields'.
* @param string $method Method name.
*/
$fields = apply_filters( 'xmlrpc_default_post_fields', array( 'post', 'terms', 'custom_fields' ), 'wp.getPost' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPost', $args, $this );
$post = get_post( $post_id, ARRAY_A );
if ( empty( $post['ID'] ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
return $this->_prepare_post( $post, $fields );
}
/**
* Retrieve posts.
*
* @since 3.4.0
*
* @see wp_get_recent_posts()
* @see wp_getPost() for more on `$fields`
* @see get_posts() for more on `$filter` values
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Optional. Modifies the query used to retrieve posts. Accepts 'post_type',
* 'post_status', 'number', 'offset', 'orderby', 's', and 'order'.
* Default empty array.
* @type array $4 Optional. The subset of post type fields to return in the response array.
* }
* @return array|IXR_Error Array contains a collection of posts.
*/
public function wp_getPosts( $args ) {
if ( ! $this->minimum_args( $args, 3 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$filter = isset( $args[3] ) ? $args[3] : array();
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
$fields = apply_filters( 'xmlrpc_default_post_fields', array( 'post', 'terms', 'custom_fields' ), 'wp.getPosts' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPosts', $args, $this );
$query = array();
if ( isset( $filter['post_type'] ) ) {
$post_type = get_post_type_object( $filter['post_type'] );
if ( ! ( (bool) $post_type ) ) {
return new IXR_Error( 403, __( 'Invalid post type.' ) );
}
} else {
$post_type = get_post_type_object( 'post' );
}
if ( ! current_user_can( $post_type->cap->edit_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts in this post type.' ) );
}
$query['post_type'] = $post_type->name;
if ( isset( $filter['post_status'] ) ) {
$query['post_status'] = $filter['post_status'];
}
if ( isset( $filter['number'] ) ) {
$query['numberposts'] = absint( $filter['number'] );
}
if ( isset( $filter['offset'] ) ) {
$query['offset'] = absint( $filter['offset'] );
}
if ( isset( $filter['orderby'] ) ) {
$query['orderby'] = $filter['orderby'];
if ( isset( $filter['order'] ) ) {
$query['order'] = $filter['order'];
}
}
if ( isset( $filter['s'] ) ) {
$query['s'] = $filter['s'];
}
$posts_list = wp_get_recent_posts( $query );
if ( ! $posts_list ) {
return array();
}
// Holds all the posts data.
$struct = array();
foreach ( $posts_list as $post ) {
if ( ! current_user_can( 'edit_post', $post['ID'] ) ) {
continue;
}
$struct[] = $this->_prepare_post( $post, $fields );
}
return $struct;
}
/**
* Create a new term.
*
* @since 3.4.0
*
* @see wp_insert_term()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Content struct for adding a new term. The struct must contain
* the term 'name' and 'taxonomy'. Optional accepted values include
* 'parent', 'description', and 'slug'.
* }
* @return int|IXR_Error The term ID on success, or an IXR_Error object on failure.
*/
public function wp_newTerm( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$content_struct = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.newTerm', $args, $this );
if ( ! taxonomy_exists( $content_struct['taxonomy'] ) ) {
return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
}
$taxonomy = get_taxonomy( $content_struct['taxonomy'] );
if ( ! current_user_can( $taxonomy->cap->edit_terms ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to create terms in this taxonomy.' ) );
}
$taxonomy = (array) $taxonomy;
// Hold the data of the term.
$term_data = array();
$term_data['name'] = trim( $content_struct['name'] );
if ( empty( $term_data['name'] ) ) {
return new IXR_Error( 403, __( 'The term name cannot be empty.' ) );
}
if ( isset( $content_struct['parent'] ) ) {
if ( ! $taxonomy['hierarchical'] ) {
return new IXR_Error( 403, __( 'This taxonomy is not hierarchical.' ) );
}
$parent_term_id = (int) $content_struct['parent'];
$parent_term = get_term( $parent_term_id, $taxonomy['name'] );
if ( is_wp_error( $parent_term ) ) {
return new IXR_Error( 500, $parent_term->get_error_message() );
}
if ( ! $parent_term ) {
return new IXR_Error( 403, __( 'Parent term does not exist.' ) );
}
$term_data['parent'] = $content_struct['parent'];
}
if ( isset( $content_struct['description'] ) ) {
$term_data['description'] = $content_struct['description'];
}
if ( isset( $content_struct['slug'] ) ) {
$term_data['slug'] = $content_struct['slug'];
}
$term = wp_insert_term( $term_data['name'], $taxonomy['name'], $term_data );
if ( is_wp_error( $term ) ) {
return new IXR_Error( 500, $term->get_error_message() );
}
if ( ! $term ) {
return new IXR_Error( 500, __( 'Sorry, the term could not be created.' ) );
}
// Add term meta.
if ( isset( $content_struct['custom_fields'] ) ) {
$this->set_term_custom_fields( $term['term_id'], $content_struct['custom_fields'] );
}
return (string) $term['term_id'];
}
/**
* Edit a term.
*
* @since 3.4.0
*
* @see wp_update_term()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Term ID.
* @type array $4 Content struct for editing a term. The struct must contain the
* term 'taxonomy'. Optional accepted values include 'name', 'parent',
* 'description', and 'slug'.
* }
* @return true|IXR_Error True on success, IXR_Error instance on failure.
*/
public function wp_editTerm( $args ) {
if ( ! $this->minimum_args( $args, 5 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$term_id = (int) $args[3];
$content_struct = $args[4];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.editTerm', $args, $this );
if ( ! taxonomy_exists( $content_struct['taxonomy'] ) ) {
return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
}
$taxonomy = get_taxonomy( $content_struct['taxonomy'] );
$taxonomy = (array) $taxonomy;
// Hold the data of the term.
$term_data = array();
$term = get_term( $term_id, $content_struct['taxonomy'] );
if ( is_wp_error( $term ) ) {
return new IXR_Error( 500, $term->get_error_message() );
}
if ( ! $term ) {
return new IXR_Error( 404, __( 'Invalid term ID.' ) );
}
if ( ! current_user_can( 'edit_term', $term_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this term.' ) );
}
if ( isset( $content_struct['name'] ) ) {
$term_data['name'] = trim( $content_struct['name'] );
if ( empty( $term_data['name'] ) ) {
return new IXR_Error( 403, __( 'The term name cannot be empty.' ) );
}
}
if ( ! empty( $content_struct['parent'] ) ) {
if ( ! $taxonomy['hierarchical'] ) {
return new IXR_Error( 403, __( 'Cannot set parent term, taxonomy is not hierarchical.' ) );
}
$parent_term_id = (int) $content_struct['parent'];
$parent_term = get_term( $parent_term_id, $taxonomy['name'] );
if ( is_wp_error( $parent_term ) ) {
return new IXR_Error( 500, $parent_term->get_error_message() );
}
if ( ! $parent_term ) {
return new IXR_Error( 403, __( 'Parent term does not exist.' ) );
}
$term_data['parent'] = $content_struct['parent'];
}
if ( isset( $content_struct['description'] ) ) {
$term_data['description'] = $content_struct['description'];
}
if ( isset( $content_struct['slug'] ) ) {
$term_data['slug'] = $content_struct['slug'];
}
$term = wp_update_term( $term_id, $taxonomy['name'], $term_data );
if ( is_wp_error( $term ) ) {
return new IXR_Error( 500, $term->get_error_message() );
}
if ( ! $term ) {
return new IXR_Error( 500, __( 'Sorry, editing the term failed.' ) );
}
// Update term meta.
if ( isset( $content_struct['custom_fields'] ) ) {
$this->set_term_custom_fields( $term_id, $content_struct['custom_fields'] );
}
return true;
}
/**
* Delete a term.
*
* @since 3.4.0
*
* @see wp_delete_term()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type string $3 Taxonomy name.
* @type int $4 Term ID.
* }
* @return true|IXR_Error True on success, IXR_Error instance on failure.
*/
public function wp_deleteTerm( $args ) {
if ( ! $this->minimum_args( $args, 5 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$taxonomy = $args[3];
$term_id = (int) $args[4];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.deleteTerm', $args, $this );
if ( ! taxonomy_exists( $taxonomy ) ) {
return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
}
$taxonomy = get_taxonomy( $taxonomy );
$term = get_term( $term_id, $taxonomy->name );
if ( is_wp_error( $term ) ) {
return new IXR_Error( 500, $term->get_error_message() );
}
if ( ! $term ) {
return new IXR_Error( 404, __( 'Invalid term ID.' ) );
}
if ( ! current_user_can( 'delete_term', $term_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this term.' ) );
}
$result = wp_delete_term( $term_id, $taxonomy->name );
if ( is_wp_error( $result ) ) {
return new IXR_Error( 500, $term->get_error_message() );
}
if ( ! $result ) {
return new IXR_Error( 500, __( 'Sorry, deleting the term failed.' ) );
}
return $result;
}
/**
* Retrieve a term.
*
* @since 3.4.0
*
* @see get_term()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type string $3 Taxonomy name.
* @type int $4 Term ID.
* }
* @return array|IXR_Error IXR_Error on failure, array on success, containing:
* - 'term_id'
* - 'name'
* - 'slug'
* - 'term_group'
* - 'term_taxonomy_id'
* - 'taxonomy'
* - 'description'
* - 'parent'
* - 'count'
*/
public function wp_getTerm( $args ) {
if ( ! $this->minimum_args( $args, 5 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$taxonomy = $args[3];
$term_id = (int) $args[4];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getTerm', $args, $this );
if ( ! taxonomy_exists( $taxonomy ) ) {
return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
}
$taxonomy = get_taxonomy( $taxonomy );
$term = get_term( $term_id, $taxonomy->name, ARRAY_A );
if ( is_wp_error( $term ) ) {
return new IXR_Error( 500, $term->get_error_message() );
}
if ( ! $term ) {
return new IXR_Error( 404, __( 'Invalid term ID.' ) );
}
if ( ! current_user_can( 'assign_term', $term_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign this term.' ) );
}
return $this->_prepare_term( $term );
}
/**
* Retrieve all terms for a taxonomy.
*
* @since 3.4.0
*
* The optional $filter parameter modifies the query used to retrieve terms.
* Accepted keys are 'number', 'offset', 'orderby', 'order', 'hide_empty', and 'search'.
*
* @see get_terms()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type string $3 Taxonomy name.
* @type array $4 Optional. Modifies the query used to retrieve posts. Accepts 'number',
* 'offset', 'orderby', 'order', 'hide_empty', and 'search'. Default empty array.
* }
* @return array|IXR_Error An associative array of terms data on success, IXR_Error instance otherwise.
*/
public function wp_getTerms( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$taxonomy = $args[3];
$filter = isset( $args[4] ) ? $args[4] : array();
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getTerms', $args, $this );
if ( ! taxonomy_exists( $taxonomy ) ) {
return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
}
$taxonomy = get_taxonomy( $taxonomy );
if ( ! current_user_can( $taxonomy->cap->assign_terms ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign terms in this taxonomy.' ) );
}
$query = array( 'taxonomy' => $taxonomy->name );
if ( isset( $filter['number'] ) ) {
$query['number'] = absint( $filter['number'] );
}
if ( isset( $filter['offset'] ) ) {
$query['offset'] = absint( $filter['offset'] );
}
if ( isset( $filter['orderby'] ) ) {
$query['orderby'] = $filter['orderby'];
if ( isset( $filter['order'] ) ) {
$query['order'] = $filter['order'];
}
}
if ( isset( $filter['hide_empty'] ) ) {
$query['hide_empty'] = $filter['hide_empty'];
} else {
$query['get'] = 'all';
}
if ( isset( $filter['search'] ) ) {
$query['search'] = $filter['search'];
}
$terms = get_terms( $query );
if ( is_wp_error( $terms ) ) {
return new IXR_Error( 500, $terms->get_error_message() );
}
$struct = array();
foreach ( $terms as $term ) {
$struct[] = $this->_prepare_term( $term );
}
return $struct;
}
/**
* Retrieve a taxonomy.
*
* @since 3.4.0
*
* @see get_taxonomy()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type string $3 Taxonomy name.
* @type array $4 Optional. Array of taxonomy fields to limit to in the return.
* Accepts 'labels', 'cap', 'menu', and 'object_type'.
* Default empty array.
* }
* @return array|IXR_Error An array of taxonomy data on success, IXR_Error instance otherwise.
*/
public function wp_getTaxonomy( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$taxonomy = $args[3];
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/**
* Filters the taxonomy query fields used by the given XML-RPC method.
*
* @since 3.4.0
*
* @param array $fields An array of taxonomy fields to retrieve.
* @param string $method The method name.
*/
$fields = apply_filters( 'xmlrpc_default_taxonomy_fields', array( 'labels', 'cap', 'object_type' ), 'wp.getTaxonomy' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getTaxonomy', $args, $this );
if ( ! taxonomy_exists( $taxonomy ) ) {
return new IXR_Error( 403, __( 'Invalid taxonomy.' ) );
}
$taxonomy = get_taxonomy( $taxonomy );
if ( ! current_user_can( $taxonomy->cap->assign_terms ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to assign terms in this taxonomy.' ) );
}
return $this->_prepare_taxonomy( $taxonomy, $fields );
}
/**
* Retrieve all taxonomies.
*
* @since 3.4.0
*
* @see get_taxonomies()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Optional. An array of arguments for retrieving taxonomies.
* @type array $4 Optional. The subset of taxonomy fields to return.
* }
* @return array|IXR_Error An associative array of taxonomy data with returned fields determined
* by `$fields`, or an IXR_Error instance on failure.
*/
public function wp_getTaxonomies( $args ) {
if ( ! $this->minimum_args( $args, 3 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$filter = isset( $args[3] ) ? $args[3] : array( 'public' => true );
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
$fields = apply_filters( 'xmlrpc_default_taxonomy_fields', array( 'labels', 'cap', 'object_type' ), 'wp.getTaxonomies' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getTaxonomies', $args, $this );
$taxonomies = get_taxonomies( $filter, 'objects' );
// Holds all the taxonomy data.
$struct = array();
foreach ( $taxonomies as $taxonomy ) {
// Capability check for post types.
if ( ! current_user_can( $taxonomy->cap->assign_terms ) ) {
continue;
}
$struct[] = $this->_prepare_taxonomy( $taxonomy, $fields );
}
return $struct;
}
/**
* Retrieve a user.
*
* The optional $fields parameter specifies what fields will be included
* in the response array. This should be a list of field names. 'user_id' will
* always be included in the response regardless of the value of $fields.
*
* Instead of, or in addition to, individual field names, conceptual group
* names can be used to specify multiple fields. The available conceptual
* groups are 'basic' and 'all'.
*
* @uses get_userdata()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 User ID.
* @type array $4 Optional. Array of fields to return.
* }
* @return array|IXR_Error Array contains (based on $fields parameter):
* - 'user_id'
* - 'username'
* - 'first_name'
* - 'last_name'
* - 'registered'
* - 'bio'
* - 'email'
* - 'nickname'
* - 'nicename'
* - 'url'
* - 'display_name'
* - 'roles'
*/
public function wp_getUser( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user_id = (int) $args[3];
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/**
* Filters the default user query fields used by the given XML-RPC method.
*
* @since 3.5.0
*
* @param array $fields User query fields for given method. Default 'all'.
* @param string $method The method name.
*/
$fields = apply_filters( 'xmlrpc_default_user_fields', array( 'all' ), 'wp.getUser' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getUser', $args, $this );
if ( ! current_user_can( 'edit_user', $user_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this user.' ) );
}
$user_data = get_userdata( $user_id );
if ( ! $user_data ) {
return new IXR_Error( 404, __( 'Invalid user ID.' ) );
}
return $this->_prepare_user( $user_data, $fields );
}
/**
* Retrieve users.
*
* The optional $filter parameter modifies the query used to retrieve users.
* Accepted keys are 'number' (default: 50), 'offset' (default: 0), 'role',
* 'who', 'orderby', and 'order'.
*
* The optional $fields parameter specifies what fields will be included
* in the response array.
*
* @uses get_users()
* @see wp_getUser() for more on $fields and return values
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Optional. Arguments for the user query.
* @type array $4 Optional. Fields to return.
* }
* @return array|IXR_Error users data
*/
public function wp_getUsers( $args ) {
if ( ! $this->minimum_args( $args, 3 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$filter = isset( $args[3] ) ? $args[3] : array();
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
$fields = apply_filters( 'xmlrpc_default_user_fields', array( 'all' ), 'wp.getUsers' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getUsers', $args, $this );
if ( ! current_user_can( 'list_users' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to list users.' ) );
}
$query = array( 'fields' => 'all_with_meta' );
$query['number'] = ( isset( $filter['number'] ) ) ? absint( $filter['number'] ) : 50;
$query['offset'] = ( isset( $filter['offset'] ) ) ? absint( $filter['offset'] ) : 0;
if ( isset( $filter['orderby'] ) ) {
$query['orderby'] = $filter['orderby'];
if ( isset( $filter['order'] ) ) {
$query['order'] = $filter['order'];
}
}
if ( isset( $filter['role'] ) ) {
if ( get_role( $filter['role'] ) === null ) {
return new IXR_Error( 403, __( 'Invalid role.' ) );
}
$query['role'] = $filter['role'];
}
if ( isset( $filter['who'] ) ) {
$query['who'] = $filter['who'];
}
$users = get_users( $query );
$_users = array();
foreach ( $users as $user_data ) {
if ( current_user_can( 'edit_user', $user_data->ID ) ) {
$_users[] = $this->_prepare_user( $user_data, $fields );
}
}
return $_users;
}
/**
* Retrieve information about the requesting user.
*
* @uses get_userdata()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username
* @type string $2 Password
* @type array $3 Optional. Fields to return.
* }
* @return array|IXR_Error (@see wp_getUser)
*/
public function wp_getProfile( $args ) {
if ( ! $this->minimum_args( $args, 3 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
if ( isset( $args[3] ) ) {
$fields = $args[3];
} else {
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
$fields = apply_filters( 'xmlrpc_default_user_fields', array( 'all' ), 'wp.getProfile' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getProfile', $args, $this );
if ( ! current_user_can( 'edit_user', $user->ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit your profile.' ) );
}
$user_data = get_userdata( $user->ID );
return $this->_prepare_user( $user_data, $fields );
}
/**
* Edit user's profile.
*
* @uses wp_update_user()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Content struct. It can optionally contain:
* - 'first_name'
* - 'last_name'
* - 'website'
* - 'display_name'
* - 'nickname'
* - 'nicename'
* - 'bio'
* }
* @return true|IXR_Error True, on success.
*/
public function wp_editProfile( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$content_struct = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.editProfile', $args, $this );
if ( ! current_user_can( 'edit_user', $user->ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit your profile.' ) );
}
// Holds data of the user.
$user_data = array();
$user_data['ID'] = $user->ID;
// Only set the user details if they were given.
if ( isset( $content_struct['first_name'] ) ) {
$user_data['first_name'] = $content_struct['first_name'];
}
if ( isset( $content_struct['last_name'] ) ) {
$user_data['last_name'] = $content_struct['last_name'];
}
if ( isset( $content_struct['url'] ) ) {
$user_data['user_url'] = $content_struct['url'];
}
if ( isset( $content_struct['display_name'] ) ) {
$user_data['display_name'] = $content_struct['display_name'];
}
if ( isset( $content_struct['nickname'] ) ) {
$user_data['nickname'] = $content_struct['nickname'];
}
if ( isset( $content_struct['nicename'] ) ) {
$user_data['user_nicename'] = $content_struct['nicename'];
}
if ( isset( $content_struct['bio'] ) ) {
$user_data['description'] = $content_struct['bio'];
}
$result = wp_update_user( $user_data );
if ( is_wp_error( $result ) ) {
return new IXR_Error( 500, $result->get_error_message() );
}
if ( ! $result ) {
return new IXR_Error( 500, __( 'Sorry, the user could not be updated.' ) );
}
return true;
}
/**
* Retrieve page.
*
* @since 2.2.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type int $1 Page ID.
* @type string $2 Username.
* @type string $3 Password.
* }
* @return array|IXR_Error
*/
public function wp_getPage( $args ) {
$this->escape( $args );
$page_id = (int) $args[1];
$username = $args[2];
$password = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
$page = get_post( $page_id );
if ( ! $page ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_page', $page_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this page.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPage', $args, $this );
// If we found the page then format the data.
if ( $page->ID && ( 'page' === $page->post_type ) ) {
return $this->_prepare_page( $page );
} else {
// If the page doesn't exist, indicate that.
return new IXR_Error( 404, __( 'Sorry, no such page.' ) );
}
}
/**
* Retrieve Pages.
*
* @since 2.2.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Optional. Number of pages. Default 10.
* }
* @return array|IXR_Error
*/
public function wp_getPages( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$num_pages = isset( $args[3] ) ? (int) $args[3] : 10;
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_pages' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit pages.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPages', $args, $this );
$pages = get_posts(
array(
'post_type' => 'page',
'post_status' => 'any',
'numberposts' => $num_pages,
)
);
$num_pages = count( $pages );
// If we have pages, put together their info.
if ( $num_pages >= 1 ) {
$pages_struct = array();
foreach ( $pages as $page ) {
if ( current_user_can( 'edit_page', $page->ID ) ) {
$pages_struct[] = $this->_prepare_page( $page );
}
}
return $pages_struct;
}
return array();
}
/**
* Create new page.
*
* @since 2.2.0
*
* @see wp_xmlrpc_server::mw_newPost()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Content struct.
* }
* @return int|IXR_Error
*/
public function wp_newPage( $args ) {
// Items not escaped here will be escaped in wp_newPost().
$username = $this->escape( $args[1] );
$password = $this->escape( $args[2] );
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.newPage', $args, $this );
// Mark this as content for a page.
$args[3]['post_type'] = 'page';
// Let mw_newPost() do all of the heavy lifting.
return $this->mw_newPost( $args );
}
/**
* Delete page.
*
* @since 2.2.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Page ID.
* }
* @return true|IXR_Error True, if success.
*/
public function wp_deletePage( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$page_id = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.deletePage', $args, $this );
// Get the current page based on the 'page_id' and
// make sure it is a page and not a post.
$actual_page = get_post( $page_id, ARRAY_A );
if ( ! $actual_page || ( 'page' !== $actual_page['post_type'] ) ) {
return new IXR_Error( 404, __( 'Sorry, no such page.' ) );
}
// Make sure the user can delete pages.
if ( ! current_user_can( 'delete_page', $page_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this page.' ) );
}
// Attempt to delete the page.
$result = wp_delete_post( $page_id );
if ( ! $result ) {
return new IXR_Error( 500, __( 'Failed to delete the page.' ) );
}
/**
* Fires after a page has been successfully deleted via XML-RPC.
*
* @since 3.4.0
*
* @param int $page_id ID of the deleted page.
* @param array $args An array of arguments to delete the page.
*/
do_action( 'xmlrpc_call_success_wp_deletePage', $page_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return true;
}
/**
* Edit page.
*
* @since 2.2.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type int $1 Page ID.
* @type string $2 Username.
* @type string $3 Password.
* @type string $4 Content.
* @type int $5 Publish flag. 0 for draft, 1 for publish.
* }
* @return array|IXR_Error
*/
public function wp_editPage( $args ) {
// Items will be escaped in mw_editPost().
$page_id = (int) $args[1];
$username = $args[2];
$password = $args[3];
$content = $args[4];
$publish = $args[5];
$escaped_username = $this->escape( $username );
$escaped_password = $this->escape( $password );
$user = $this->login( $escaped_username, $escaped_password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.editPage', $args, $this );
// Get the page data and make sure it is a page.
$actual_page = get_post( $page_id, ARRAY_A );
if ( ! $actual_page || ( 'page' !== $actual_page['post_type'] ) ) {
return new IXR_Error( 404, __( 'Sorry, no such page.' ) );
}
// Make sure the user is allowed to edit pages.
if ( ! current_user_can( 'edit_page', $page_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this page.' ) );
}
// Mark this as content for a page.
$content['post_type'] = 'page';
// Arrange args in the way mw_editPost() understands.
$args = array(
$page_id,
$username,
$password,
$content,
$publish,
);
// Let mw_editPost() do all of the heavy lifting.
return $this->mw_editPost( $args );
}
/**
* Retrieve page list.
*
* @since 2.2.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error
*/
public function wp_getPageList( $args ) {
global $wpdb;
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_pages' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit pages.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPageList', $args, $this );
// Get list of page IDs and titles.
$page_list = $wpdb->get_results(
"
SELECT ID page_id,
post_title page_title,
post_parent page_parent_id,
post_date_gmt,
post_date,
post_status
FROM {$wpdb->posts}
WHERE post_type = 'page'
ORDER BY ID
"
);
// The date needs to be formatted properly.
$num_pages = count( $page_list );
for ( $i = 0; $i < $num_pages; $i++ ) {
$page_list[ $i ]->dateCreated = $this->_convert_date( $page_list[ $i ]->post_date );
$page_list[ $i ]->date_created_gmt = $this->_convert_date_gmt( $page_list[ $i ]->post_date_gmt, $page_list[ $i ]->post_date );
unset( $page_list[ $i ]->post_date_gmt );
unset( $page_list[ $i ]->post_date );
unset( $page_list[ $i ]->post_status );
}
return $page_list;
}
/**
* Retrieve authors list.
*
* @since 2.2.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error
*/
public function wp_getAuthors( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getAuthors', $args, $this );
$authors = array();
foreach ( get_users( array( 'fields' => array( 'ID', 'user_login', 'display_name' ) ) ) as $user ) {
$authors[] = array(
'user_id' => $user->ID,
'user_login' => $user->user_login,
'display_name' => $user->display_name,
);
}
return $authors;
}
/**
* Get list of all tags
*
* @since 2.7.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error
*/
public function wp_getTags( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view tags.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getKeywords', $args, $this );
$tags = array();
$all_tags = get_tags();
if ( $all_tags ) {
foreach ( (array) $all_tags as $tag ) {
$struct = array();
$struct['tag_id'] = $tag->term_id;
$struct['name'] = $tag->name;
$struct['count'] = $tag->count;
$struct['slug'] = $tag->slug;
$struct['html_url'] = esc_html( get_tag_link( $tag->term_id ) );
$struct['rss_url'] = esc_html( get_tag_feed_link( $tag->term_id ) );
$tags[] = $struct;
}
}
return $tags;
}
/**
* Create new category.
*
* @since 2.2.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Category.
* }
* @return int|IXR_Error Category ID.
*/
public function wp_newCategory( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$category = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.newCategory', $args, $this );
// Make sure the user is allowed to add a category.
if ( ! current_user_can( 'manage_categories' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to add a category.' ) );
}
// If no slug was provided, make it empty
// so that WordPress will generate one.
if ( empty( $category['slug'] ) ) {
$category['slug'] = '';
}
// If no parent_id was provided, make it empty
// so that it will be a top-level page (no parent).
if ( ! isset( $category['parent_id'] ) ) {
$category['parent_id'] = '';
}
// If no description was provided, make it empty.
if ( empty( $category['description'] ) ) {
$category['description'] = '';
}
$new_category = array(
'cat_name' => $category['name'],
'category_nicename' => $category['slug'],
'category_parent' => $category['parent_id'],
'category_description' => $category['description'],
);
$cat_id = wp_insert_category( $new_category, true );
if ( is_wp_error( $cat_id ) ) {
if ( 'term_exists' === $cat_id->get_error_code() ) {
return (int) $cat_id->get_error_data();
} else {
return new IXR_Error( 500, __( 'Sorry, the category could not be created.' ) );
}
} elseif ( ! $cat_id ) {
return new IXR_Error( 500, __( 'Sorry, the category could not be created.' ) );
}
/**
* Fires after a new category has been successfully created via XML-RPC.
*
* @since 3.4.0
*
* @param int $cat_id ID of the new category.
* @param array $args An array of new category arguments.
*/
do_action( 'xmlrpc_call_success_wp_newCategory', $cat_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return $cat_id;
}
/**
* Remove category.
*
* @since 2.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Category ID.
* }
* @return bool|IXR_Error See wp_delete_term() for return info.
*/
public function wp_deleteCategory( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$category_id = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.deleteCategory', $args, $this );
if ( ! current_user_can( 'delete_term', $category_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this category.' ) );
}
$status = wp_delete_term( $category_id, 'category' );
if ( true == $status ) {
/**
* Fires after a category has been successfully deleted via XML-RPC.
*
* @since 3.4.0
*
* @param int $category_id ID of the deleted category.
* @param array $args An array of arguments to delete the category.
*/
do_action( 'xmlrpc_call_success_wp_deleteCategory', $category_id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
}
return $status;
}
/**
* Retrieve category list.
*
* @since 2.2.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Category
* @type int $4 Max number of results.
* }
* @return array|IXR_Error
*/
public function wp_suggestCategories( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$category = $args[3];
$max_results = (int) $args[4];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view categories.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.suggestCategories', $args, $this );
$category_suggestions = array();
$args = array(
'get' => 'all',
'number' => $max_results,
'name__like' => $category,
);
foreach ( (array) get_categories( $args ) as $cat ) {
$category_suggestions[] = array(
'category_id' => $cat->term_id,
'category_name' => $cat->name,
);
}
return $category_suggestions;
}
/**
* Retrieve comment.
*
* @since 2.7.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Comment ID.
* }
* @return array|IXR_Error
*/
public function wp_getComment( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$comment_id = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getComment', $args, $this );
$comment = get_comment( $comment_id );
if ( ! $comment ) {
return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
}
if ( ! current_user_can( 'edit_comment', $comment_id ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to moderate or edit this comment.' ) );
}
return $this->_prepare_comment( $comment );
}
/**
* Retrieve comments.
*
* Besides the common blog_id (unused), username, and password arguments, it takes a filter
* array as last argument.
*
* Accepted 'filter' keys are 'status', 'post_id', 'offset', and 'number'.
*
* The defaults are as follows:
* - 'status' - Default is ''. Filter by status (e.g., 'approve', 'hold')
* - 'post_id' - Default is ''. The post where the comment is posted. Empty string shows all comments.
* - 'number' - Default is 10. Total number of media items to retrieve.
* - 'offset' - Default is 0. See WP_Query::query() for more.
*
* @since 2.7.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Optional. Query arguments.
* }
* @return array|IXR_Error Contains a collection of comments. See wp_xmlrpc_server::wp_getComment() for a description of each item contents
*/
public function wp_getComments( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$struct = isset( $args[3] ) ? $args[3] : array();
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getComments', $args, $this );
if ( isset( $struct['status'] ) ) {
$status = $struct['status'];
} else {
$status = '';
}
if ( ! current_user_can( 'moderate_comments' ) && 'approve' !== $status ) {
return new IXR_Error( 401, __( 'Invalid comment status.' ) );
}
$post_id = '';
if ( isset( $struct['post_id'] ) ) {
$post_id = absint( $struct['post_id'] );
}
$post_type = '';
if ( isset( $struct['post_type'] ) ) {
$post_type_object = get_post_type_object( $struct['post_type'] );
if ( ! $post_type_object || ! post_type_supports( $post_type_object->name, 'comments' ) ) {
return new IXR_Error( 404, __( 'Invalid post type.' ) );
}
$post_type = $struct['post_type'];
}
$offset = 0;
if ( isset( $struct['offset'] ) ) {
$offset = absint( $struct['offset'] );
}
$number = 10;
if ( isset( $struct['number'] ) ) {
$number = absint( $struct['number'] );
}
$comments = get_comments(
array(
'status' => $status,
'post_id' => $post_id,
'offset' => $offset,
'number' => $number,
'post_type' => $post_type,
)
);
$comments_struct = array();
if ( is_array( $comments ) ) {
foreach ( $comments as $comment ) {
$comments_struct[] = $this->_prepare_comment( $comment );
}
}
return $comments_struct;
}
/**
* Delete a comment.
*
* By default, the comment will be moved to the Trash instead of deleted.
* See wp_delete_comment() for more information on this behavior.
*
* @since 2.7.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Comment ID.
* }
* @return bool|IXR_Error See wp_delete_comment().
*/
public function wp_deleteComment( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$comment_ID = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! get_comment( $comment_ID ) ) {
return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
}
if ( ! current_user_can( 'edit_comment', $comment_ID ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to delete this comment.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.deleteComment', $args, $this );
$status = wp_delete_comment( $comment_ID );
if ( $status ) {
/**
* Fires after a comment has been successfully deleted via XML-RPC.
*
* @since 3.4.0
*
* @param int $comment_ID ID of the deleted comment.
* @param array $args An array of arguments to delete the comment.
*/
do_action( 'xmlrpc_call_success_wp_deleteComment', $comment_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
}
return $status;
}
/**
* Edit comment.
*
* Besides the common blog_id (unused), username, and password arguments, it takes a
* comment_id integer and a content_struct array as last argument.
*
* The allowed keys in the content_struct array are:
* - 'author'
* - 'author_url'
* - 'author_email'
* - 'content'
* - 'date_created_gmt'
* - 'status'. Common statuses are 'approve', 'hold', 'spam'. See get_comment_statuses() for more details
*
* @since 2.7.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Comment ID.
* @type array $4 Content structure.
* }
* @return true|IXR_Error True, on success.
*/
public function wp_editComment( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$comment_ID = (int) $args[3];
$content_struct = $args[4];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! get_comment( $comment_ID ) ) {
return new IXR_Error( 404, __( 'Invalid comment ID.' ) );
}
if ( ! current_user_can( 'edit_comment', $comment_ID ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to moderate or edit this comment.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.editComment', $args, $this );
$comment = array(
'comment_ID' => $comment_ID,
);
if ( isset( $content_struct['status'] ) ) {
$statuses = get_comment_statuses();
$statuses = array_keys( $statuses );
if ( ! in_array( $content_struct['status'], $statuses, true ) ) {
return new IXR_Error( 401, __( 'Invalid comment status.' ) );
}
$comment['comment_approved'] = $content_struct['status'];
}
// Do some timestamp voodoo.
if ( ! empty( $content_struct['date_created_gmt'] ) ) {
// We know this is supposed to be GMT, so we're going to slap that Z on there by force.
$dateCreated = rtrim( $content_struct['date_created_gmt']->getIso(), 'Z' ) . 'Z';
$comment['comment_date'] = get_date_from_gmt( $dateCreated );
$comment['comment_date_gmt'] = iso8601_to_datetime( $dateCreated, 'gmt' );
}
if ( isset( $content_struct['content'] ) ) {
$comment['comment_content'] = $content_struct['content'];
}
if ( isset( $content_struct['author'] ) ) {
$comment['comment_author'] = $content_struct['author'];
}
if ( isset( $content_struct['author_url'] ) ) {
$comment['comment_author_url'] = $content_struct['author_url'];
}
if ( isset( $content_struct['author_email'] ) ) {
$comment['comment_author_email'] = $content_struct['author_email'];
}
$result = wp_update_comment( $comment, true );
if ( is_wp_error( $result ) ) {
return new IXR_Error( 500, $result->get_error_message() );
}
if ( ! $result ) {
return new IXR_Error( 500, __( 'Sorry, the comment could not be updated.' ) );
}
/**
* Fires after a comment has been successfully updated via XML-RPC.
*
* @since 3.4.0
*
* @param int $comment_ID ID of the updated comment.
* @param array $args An array of arguments to update the comment.
*/
do_action( 'xmlrpc_call_success_wp_editComment', $comment_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return true;
}
/**
* Create new comment.
*
* @since 2.7.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type string|int $3 Post ID or URL.
* @type array $4 Content structure.
* }
* @return int|IXR_Error See wp_new_comment().
*/
public function wp_newComment( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$post = $args[3];
$content_struct = $args[4];
/**
* Filters whether to allow anonymous comments over XML-RPC.
*
* @since 2.7.0
*
* @param bool $allow Whether to allow anonymous commenting via XML-RPC.
* Default false.
*/
$allow_anon = apply_filters( 'xmlrpc_allow_anonymous_comments', false );
$user = $this->login( $username, $password );
if ( ! $user ) {
$logged_in = false;
if ( $allow_anon && get_option( 'comment_registration' ) ) {
return new IXR_Error( 403, __( 'Sorry, you must be logged in to comment.' ) );
} elseif ( ! $allow_anon ) {
return $this->error;
}
} else {
$logged_in = true;
}
if ( is_numeric( $post ) ) {
$post_id = absint( $post );
} else {
$post_id = url_to_postid( $post );
}
if ( ! $post_id ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! get_post( $post_id ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! comments_open( $post_id ) ) {
return new IXR_Error( 403, __( 'Sorry, comments are closed for this item.' ) );
}
if (
'publish' === get_post_status( $post_id ) &&
! current_user_can( 'edit_post', $post_id ) &&
post_password_required( $post_id )
) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to comment on this post.' ) );
}
if (
'private' === get_post_status( $post_id ) &&
! current_user_can( 'read_post', $post_id )
) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to comment on this post.' ) );
}
$comment = array(
'comment_post_ID' => $post_id,
'comment_content' => trim( $content_struct['content'] ),
);
if ( $logged_in ) {
$display_name = $user->display_name;
$user_email = $user->user_email;
$user_url = $user->user_url;
$comment['comment_author'] = $this->escape( $display_name );
$comment['comment_author_email'] = $this->escape( $user_email );
$comment['comment_author_url'] = $this->escape( $user_url );
$comment['user_id'] = $user->ID;
} else {
$comment['comment_author'] = '';
if ( isset( $content_struct['author'] ) ) {
$comment['comment_author'] = $content_struct['author'];
}
$comment['comment_author_email'] = '';
if ( isset( $content_struct['author_email'] ) ) {
$comment['comment_author_email'] = $content_struct['author_email'];
}
$comment['comment_author_url'] = '';
if ( isset( $content_struct['author_url'] ) ) {
$comment['comment_author_url'] = $content_struct['author_url'];
}
$comment['user_id'] = 0;
if ( get_option( 'require_name_email' ) ) {
if ( strlen( $comment['comment_author_email'] ) < 6 || '' === $comment['comment_author'] ) {
return new IXR_Error( 403, __( 'Comment author name and email are required.' ) );
} elseif ( ! is_email( $comment['comment_author_email'] ) ) {
return new IXR_Error( 403, __( 'A valid email address is required.' ) );
}
}
}
$comment['comment_parent'] = isset( $content_struct['comment_parent'] ) ? absint( $content_struct['comment_parent'] ) : 0;
/** This filter is documented in wp-includes/comment.php */
$allow_empty = apply_filters( 'allow_empty_comment', false, $comment );
if ( ! $allow_empty && '' === $comment['comment_content'] ) {
return new IXR_Error( 403, __( 'Comment is required.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.newComment', $args, $this );
$comment_ID = wp_new_comment( $comment, true );
if ( is_wp_error( $comment_ID ) ) {
return new IXR_Error( 403, $comment_ID->get_error_message() );
}
if ( ! $comment_ID ) {
return new IXR_Error( 403, __( 'Something went wrong.' ) );
}
/**
* Fires after a new comment has been successfully created via XML-RPC.
*
* @since 3.4.0
*
* @param int $comment_ID ID of the new comment.
* @param array $args An array of new comment arguments.
*/
do_action( 'xmlrpc_call_success_wp_newComment', $comment_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return $comment_ID;
}
/**
* Retrieve all of the comment status.
*
* @since 2.7.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error
*/
public function wp_getCommentStatusList( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'publish_posts' ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getCommentStatusList', $args, $this );
return get_comment_statuses();
}
/**
* Retrieve comment count.
*
* @since 2.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Post ID.
* }
* @return array|IXR_Error
*/
public function wp_getCommentCount( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$post_id = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
$post = get_post( $post_id, ARRAY_A );
if ( empty( $post['ID'] ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details of this post.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getCommentCount', $args, $this );
$count = wp_count_comments( $post_id );
return array(
'approved' => $count->approved,
'awaiting_moderation' => $count->moderated,
'spam' => $count->spam,
'total_comments' => $count->total_comments,
);
}
/**
* Retrieve post statuses.
*
* @since 2.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error
*/
public function wp_getPostStatusList( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPostStatusList', $args, $this );
return get_post_statuses();
}
/**
* Retrieve page statuses.
*
* @since 2.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error
*/
public function wp_getPageStatusList( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_pages' ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPageStatusList', $args, $this );
return get_page_statuses();
}
/**
* Retrieve page templates.
*
* @since 2.6.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error
*/
public function wp_getPageTemplates( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_pages' ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
}
$templates = get_page_templates();
$templates['Default'] = 'default';
return $templates;
}
/**
* Retrieve blog options.
*
* @since 2.6.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Optional. Options.
* }
* @return array|IXR_Error
*/
public function wp_getOptions( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$options = isset( $args[3] ) ? (array) $args[3] : array();
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
// If no specific options where asked for, return all of them.
if ( count( $options ) == 0 ) {
$options = array_keys( $this->blog_options );
}
return $this->_getOptions( $options );
}
/**
* Retrieve blog options value from list.
*
* @since 2.6.0
*
* @param array $options Options to retrieve.
* @return array
*/
public function _getOptions( $options ) {
$data = array();
$can_manage = current_user_can( 'manage_options' );
foreach ( $options as $option ) {
if ( array_key_exists( $option, $this->blog_options ) ) {
$data[ $option ] = $this->blog_options[ $option ];
// Is the value static or dynamic?
if ( isset( $data[ $option ]['option'] ) ) {
$data[ $option ]['value'] = get_option( $data[ $option ]['option'] );
unset( $data[ $option ]['option'] );
}
if ( ! $can_manage ) {
$data[ $option ]['readonly'] = true;
}
}
}
return $data;
}
/**
* Update blog options.
*
* @since 2.6.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Options.
* }
* @return array|IXR_Error
*/
public function wp_setOptions( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$options = (array) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'manage_options' ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to update options.' ) );
}
$option_names = array();
foreach ( $options as $o_name => $o_value ) {
$option_names[] = $o_name;
if ( ! array_key_exists( $o_name, $this->blog_options ) ) {
continue;
}
if ( true == $this->blog_options[ $o_name ]['readonly'] ) {
continue;
}
update_option( $this->blog_options[ $o_name ]['option'], wp_unslash( $o_value ) );
}
// Now return the updated values.
return $this->_getOptions( $option_names );
}
/**
* Retrieve a media item by ID
*
* @since 3.1.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Attachment ID.
* }
* @return array|IXR_Error Associative array contains:
* - 'date_created_gmt'
* - 'parent'
* - 'link'
* - 'thumbnail'
* - 'title'
* - 'caption'
* - 'description'
* - 'metadata'
*/
public function wp_getMediaItem( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$attachment_id = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'upload_files' ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to upload files.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getMediaItem', $args, $this );
$attachment = get_post( $attachment_id );
if ( ! $attachment || 'attachment' !== $attachment->post_type ) {
return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
}
return $this->_prepare_media_item( $attachment );
}
/**
* Retrieves a collection of media library items (or attachments)
*
* Besides the common blog_id (unused), username, and password arguments, it takes a filter
* array as last argument.
*
* Accepted 'filter' keys are 'parent_id', 'mime_type', 'offset', and 'number'.
*
* The defaults are as follows:
* - 'number' - Default is 5. Total number of media items to retrieve.
* - 'offset' - Default is 0. See WP_Query::query() for more.
* - 'parent_id' - Default is ''. The post where the media item is attached. Empty string shows all media items. 0 shows unattached media items.
* - 'mime_type' - Default is ''. Filter by mime type (e.g., 'image/jpeg', 'application/pdf')
*
* @since 3.1.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Query arguments.
* }
* @return array|IXR_Error Contains a collection of media items. See wp_xmlrpc_server::wp_getMediaItem() for a description of each item contents
*/
public function wp_getMediaLibrary( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$struct = isset( $args[3] ) ? $args[3] : array();
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'upload_files' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to upload files.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getMediaLibrary', $args, $this );
$parent_id = ( isset( $struct['parent_id'] ) ) ? absint( $struct['parent_id'] ) : '';
$mime_type = ( isset( $struct['mime_type'] ) ) ? $struct['mime_type'] : '';
$offset = ( isset( $struct['offset'] ) ) ? absint( $struct['offset'] ) : 0;
$number = ( isset( $struct['number'] ) ) ? absint( $struct['number'] ) : -1;
$attachments = get_posts(
array(
'post_type' => 'attachment',
'post_parent' => $parent_id,
'offset' => $offset,
'numberposts' => $number,
'post_mime_type' => $mime_type,
)
);
$attachments_struct = array();
foreach ( $attachments as $attachment ) {
$attachments_struct[] = $this->_prepare_media_item( $attachment );
}
return $attachments_struct;
}
/**
* Retrieves a list of post formats used by the site.
*
* @since 3.1.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error List of post formats, otherwise IXR_Error object.
*/
public function wp_getPostFormats( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 403, __( 'Sorry, you are not allowed to access details about this site.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPostFormats', $args, $this );
$formats = get_post_format_strings();
// Find out if they want a list of currently supports formats.
if ( isset( $args[3] ) && is_array( $args[3] ) ) {
if ( $args[3]['show-supported'] ) {
if ( current_theme_supports( 'post-formats' ) ) {
$supported = get_theme_support( 'post-formats' );
$data = array();
$data['all'] = $formats;
$data['supported'] = $supported[0];
$formats = $data;
}
}
}
return $formats;
}
/**
* Retrieves a post type
*
* @since 3.4.0
*
* @see get_post_type_object()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type string $3 Post type name.
* @type array $4 Optional. Fields to fetch.
* }
* @return array|IXR_Error Array contains:
* - 'labels'
* - 'description'
* - 'capability_type'
* - 'cap'
* - 'map_meta_cap'
* - 'hierarchical'
* - 'menu_position'
* - 'taxonomies'
* - 'supports'
*/
public function wp_getPostType( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$post_type_name = $args[3];
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/**
* Filters the default query fields used by the given XML-RPC method.
*
* @since 3.4.0
*
* @param array $fields An array of post type query fields for the given method.
* @param string $method The method name.
*/
$fields = apply_filters( 'xmlrpc_default_posttype_fields', array( 'labels', 'cap', 'taxonomies' ), 'wp.getPostType' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPostType', $args, $this );
if ( ! post_type_exists( $post_type_name ) ) {
return new IXR_Error( 403, __( 'Invalid post type.' ) );
}
$post_type = get_post_type_object( $post_type_name );
if ( ! current_user_can( $post_type->cap->edit_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts in this post type.' ) );
}
return $this->_prepare_post_type( $post_type, $fields );
}
/**
* Retrieves a post types
*
* @since 3.4.0
*
* @see get_post_types()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Optional. Query arguments.
* @type array $4 Optional. Fields to fetch.
* }
* @return array|IXR_Error
*/
public function wp_getPostTypes( $args ) {
if ( ! $this->minimum_args( $args, 3 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$filter = isset( $args[3] ) ? $args[3] : array( 'public' => true );
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
$fields = apply_filters( 'xmlrpc_default_posttype_fields', array( 'labels', 'cap', 'taxonomies' ), 'wp.getPostTypes' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getPostTypes', $args, $this );
$post_types = get_post_types( $filter, 'objects' );
$struct = array();
foreach ( $post_types as $post_type ) {
if ( ! current_user_can( $post_type->cap->edit_posts ) ) {
continue;
}
$struct[ $post_type->name ] = $this->_prepare_post_type( $post_type, $fields );
}
return $struct;
}
/**
* Retrieve revisions for a specific post.
*
* @since 3.5.0
*
* The optional $fields parameter specifies what fields will be included
* in the response array.
*
* @uses wp_get_post_revisions()
* @see wp_getPost() for more on $fields
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Post ID.
* @type array $4 Optional. Fields to fetch.
* }
* @return array|IXR_Error contains a collection of posts.
*/
public function wp_getRevisions( $args ) {
if ( ! $this->minimum_args( $args, 4 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$post_id = (int) $args[3];
if ( isset( $args[4] ) ) {
$fields = $args[4];
} else {
/**
* Filters the default revision query fields used by the given XML-RPC method.
*
* @since 3.5.0
*
* @param array $field An array of revision query fields.
* @param string $method The method name.
*/
$fields = apply_filters( 'xmlrpc_default_revision_fields', array( 'post_date', 'post_date_gmt' ), 'wp.getRevisions' );
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.getRevisions', $args, $this );
$post = get_post( $post_id );
if ( ! $post ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
}
// Check if revisions are enabled.
if ( ! wp_revisions_enabled( $post ) ) {
return new IXR_Error( 401, __( 'Sorry, revisions are disabled.' ) );
}
$revisions = wp_get_post_revisions( $post_id );
if ( ! $revisions ) {
return array();
}
$struct = array();
foreach ( $revisions as $revision ) {
if ( ! current_user_can( 'read_post', $revision->ID ) ) {
continue;
}
// Skip autosaves.
if ( wp_is_post_autosave( $revision ) ) {
continue;
}
$struct[] = $this->_prepare_post( get_object_vars( $revision ), $fields );
}
return $struct;
}
/**
* Restore a post revision
*
* @since 3.5.0
*
* @uses wp_restore_post_revision()
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Revision ID.
* }
* @return bool|IXR_Error false if there was an error restoring, true if success.
*/
public function wp_restoreRevision( $args ) {
if ( ! $this->minimum_args( $args, 3 ) ) {
return $this->error;
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$revision_id = (int) $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'wp.restoreRevision', $args, $this );
$revision = wp_get_post_revision( $revision_id );
if ( ! $revision ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( wp_is_post_autosave( $revision ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
$post = get_post( $revision->post_parent );
if ( ! $post ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $revision->post_parent ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
// Check if revisions are disabled.
if ( ! wp_revisions_enabled( $post ) ) {
return new IXR_Error( 401, __( 'Sorry, revisions are disabled.' ) );
}
$post = wp_restore_post_revision( $revision_id );
return (bool) $post;
}
/*
* Blogger API functions.
* Specs on http://plant.blogger.com/api and https://groups.yahoo.com/group/bloggerDev/
*/
/**
* Retrieve blogs that user owns.
*
* Will make more sense once we support multiple blogs.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error
*/
public function blogger_getUsersBlogs( $args ) {
if ( ! $this->minimum_args( $args, 3 ) ) {
return $this->error;
}
if ( is_multisite() ) {
return $this->_multisite_getUsersBlogs( $args );
}
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'blogger.getUsersBlogs', $args, $this );
$is_admin = current_user_can( 'manage_options' );
$struct = array(
'isAdmin' => $is_admin,
'url' => get_option( 'home' ) . '/',
'blogid' => '1',
'blogName' => get_option( 'blogname' ),
'xmlrpc' => site_url( 'xmlrpc.php', 'rpc' ),
);
return array( $struct );
}
/**
* Private function for retrieving a users blogs for multisite setups
*
* @since 3.0.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error
*/
protected function _multisite_getUsersBlogs( $args ) {
$current_blog = get_site();
$domain = $current_blog->domain;
$path = $current_blog->path . 'xmlrpc.php';
$blogs = $this->wp_getUsersBlogs( $args );
if ( $blogs instanceof IXR_Error ) {
return $blogs;
}
if ( $_SERVER['HTTP_HOST'] == $domain && $_SERVER['REQUEST_URI'] == $path ) {
return $blogs;
} else {
foreach ( (array) $blogs as $blog ) {
if ( strpos( $blog['url'], $_SERVER['HTTP_HOST'] ) ) {
return array( $blog );
}
}
return array();
}
}
/**
* Retrieve user's data.
*
* Gives your client some info about you, so you don't have to.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error
*/
public function blogger_getUserInfo( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to access user data on this site.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'blogger.getUserInfo', $args, $this );
$struct = array(
'nickname' => $user->nickname,
'userid' => $user->ID,
'url' => $user->user_url,
'lastname' => $user->last_name,
'firstname' => $user->first_name,
);
return $struct;
}
/**
* Retrieve post.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type int $1 Post ID.
* @type string $2 Username.
* @type string $3 Password.
* }
* @return array|IXR_Error
*/
public function blogger_getPost( $args ) {
$this->escape( $args );
$post_ID = (int) $args[1];
$username = $args[2];
$password = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
$post_data = get_post( $post_ID, ARRAY_A );
if ( ! $post_data ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'blogger.getPost', $args, $this );
$categories = implode( ',', wp_get_post_categories( $post_ID ) );
$content = '<title>' . wp_unslash( $post_data['post_title'] ) . '</title>';
$content .= '<category>' . $categories . '</category>';
$content .= wp_unslash( $post_data['post_content'] );
$struct = array(
'userid' => $post_data['post_author'],
'dateCreated' => $this->_convert_date( $post_data['post_date'] ),
'content' => $content,
'postid' => (string) $post_data['ID'],
);
return $struct;
}
/**
* Retrieve list of recent posts.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type string $0 App key (unused).
* @type int $1 Blog ID (unused).
* @type string $2 Username.
* @type string $3 Password.
* @type int $4 Optional. Number of posts.
* }
* @return array|IXR_Error
*/
public function blogger_getRecentPosts( $args ) {
$this->escape( $args );
// $args[0] = appkey - ignored.
$username = $args[2];
$password = $args[3];
if ( isset( $args[4] ) ) {
$query = array( 'numberposts' => absint( $args[4] ) );
} else {
$query = array();
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'blogger.getRecentPosts', $args, $this );
$posts_list = wp_get_recent_posts( $query );
if ( ! $posts_list ) {
$this->error = new IXR_Error( 500, __( 'Either there are no posts, or something went wrong.' ) );
return $this->error;
}
$recent_posts = array();
foreach ( $posts_list as $entry ) {
if ( ! current_user_can( 'edit_post', $entry['ID'] ) ) {
continue;
}
$post_date = $this->_convert_date( $entry['post_date'] );
$categories = implode( ',', wp_get_post_categories( $entry['ID'] ) );
$content = '<title>' . wp_unslash( $entry['post_title'] ) . '</title>';
$content .= '<category>' . $categories . '</category>';
$content .= wp_unslash( $entry['post_content'] );
$recent_posts[] = array(
'userid' => $entry['post_author'],
'dateCreated' => $post_date,
'content' => $content,
'postid' => (string) $entry['ID'],
);
}
return $recent_posts;
}
/**
* Deprecated.
*
* @since 1.5.0
* @deprecated 3.5.0
*
* @param array $args Unused.
* @return IXR_Error Error object.
*/
public function blogger_getTemplate( $args ) {
return new IXR_Error( 403, __( 'Sorry, this method is not supported.' ) );
}
/**
* Deprecated.
*
* @since 1.5.0
* @deprecated 3.5.0
*
* @param array $args Unused.
* @return IXR_Error Error object.
*/
public function blogger_setTemplate( $args ) {
return new IXR_Error( 403, __( 'Sorry, this method is not supported.' ) );
}
/**
* Creates new post.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type string $0 App key (unused).
* @type int $1 Blog ID (unused).
* @type string $2 Username.
* @type string $3 Password.
* @type string $4 Content.
* @type int $5 Publish flag. 0 for draft, 1 for publish.
* }
* @return int|IXR_Error
*/
public function blogger_newPost( $args ) {
$this->escape( $args );
$username = $args[2];
$password = $args[3];
$content = $args[4];
$publish = $args[5];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'blogger.newPost', $args, $this );
$cap = ( $publish ) ? 'publish_posts' : 'edit_posts';
if ( ! current_user_can( get_post_type_object( 'post' )->cap->create_posts ) || ! current_user_can( $cap ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to post on this site.' ) );
}
$post_status = ( $publish ) ? 'publish' : 'draft';
$post_author = $user->ID;
$post_title = xmlrpc_getposttitle( $content );
$post_category = xmlrpc_getpostcategory( $content );
$post_content = xmlrpc_removepostdata( $content );
$post_date = current_time( 'mysql' );
$post_date_gmt = current_time( 'mysql', 1 );
$post_data = compact( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status' );
$post_ID = wp_insert_post( $post_data );
if ( is_wp_error( $post_ID ) ) {
return new IXR_Error( 500, $post_ID->get_error_message() );
}
if ( ! $post_ID ) {
return new IXR_Error( 500, __( 'Sorry, the post could not be created.' ) );
}
$this->attach_uploads( $post_ID, $post_content );
/**
* Fires after a new post has been successfully created via the XML-RPC Blogger API.
*
* @since 3.4.0
*
* @param int $post_ID ID of the new post.
* @param array $args An array of new post arguments.
*/
do_action( 'xmlrpc_call_success_blogger_newPost', $post_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return $post_ID;
}
/**
* Edit a post.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type int $1 Post ID.
* @type string $2 Username.
* @type string $3 Password.
* @type string $4 Content
* @type int $5 Publish flag. 0 for draft, 1 for publish.
* }
* @return true|IXR_Error true when done.
*/
public function blogger_editPost( $args ) {
$this->escape( $args );
$post_ID = (int) $args[1];
$username = $args[2];
$password = $args[3];
$content = $args[4];
$publish = $args[5];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'blogger.editPost', $args, $this );
$actual_post = get_post( $post_ID, ARRAY_A );
if ( ! $actual_post || 'post' !== $actual_post['post_type'] ) {
return new IXR_Error( 404, __( 'Sorry, no such post.' ) );
}
$this->escape( $actual_post );
if ( ! current_user_can( 'edit_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
if ( 'publish' === $actual_post['post_status'] && ! current_user_can( 'publish_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this post.' ) );
}
$postdata = array();
$postdata['ID'] = $actual_post['ID'];
$postdata['post_content'] = xmlrpc_removepostdata( $content );
$postdata['post_title'] = xmlrpc_getposttitle( $content );
$postdata['post_category'] = xmlrpc_getpostcategory( $content );
$postdata['post_status'] = $actual_post['post_status'];
$postdata['post_excerpt'] = $actual_post['post_excerpt'];
$postdata['post_status'] = $publish ? 'publish' : 'draft';
$result = wp_update_post( $postdata );
if ( ! $result ) {
return new IXR_Error( 500, __( 'Sorry, the post could not be updated.' ) );
}
$this->attach_uploads( $actual_post['ID'], $postdata['post_content'] );
/**
* Fires after a post has been successfully updated via the XML-RPC Blogger API.
*
* @since 3.4.0
*
* @param int $post_ID ID of the updated post.
* @param array $args An array of arguments for the post to edit.
*/
do_action( 'xmlrpc_call_success_blogger_editPost', $post_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return true;
}
/**
* Remove a post.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type int $1 Post ID.
* @type string $2 Username.
* @type string $3 Password.
* }
* @return true|IXR_Error True when post is deleted.
*/
public function blogger_deletePost( $args ) {
$this->escape( $args );
$post_ID = (int) $args[1];
$username = $args[2];
$password = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'blogger.deletePost', $args, $this );
$actual_post = get_post( $post_ID, ARRAY_A );
if ( ! $actual_post || 'post' !== $actual_post['post_type'] ) {
return new IXR_Error( 404, __( 'Sorry, no such post.' ) );
}
if ( ! current_user_can( 'delete_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to delete this post.' ) );
}
$result = wp_delete_post( $post_ID );
if ( ! $result ) {
return new IXR_Error( 500, __( 'Sorry, the post could not be deleted.' ) );
}
/**
* Fires after a post has been successfully deleted via the XML-RPC Blogger API.
*
* @since 3.4.0
*
* @param int $post_ID ID of the deleted post.
* @param array $args An array of arguments to delete the post.
*/
do_action( 'xmlrpc_call_success_blogger_deletePost', $post_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return true;
}
/*
* MetaWeblog API functions.
* Specs on wherever Dave Winer wants them to be.
*/
/**
* Create a new post.
*
* The 'content_struct' argument must contain:
* - title
* - description
* - mt_excerpt
* - mt_text_more
* - mt_keywords
* - mt_tb_ping_urls
* - categories
*
* Also, it can optionally contain:
* - wp_slug
* - wp_password
* - wp_page_parent_id
* - wp_page_order
* - wp_author_id
* - post_status | page_status - can be 'draft', 'private', 'publish', or 'pending'
* - mt_allow_comments - can be 'open' or 'closed'
* - mt_allow_pings - can be 'open' or 'closed'
* - date_created_gmt
* - dateCreated
* - wp_post_thumbnail
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Content structure.
* @type int $4 Optional. Publish flag. 0 for draft, 1 for publish. Default 0.
* }
* @return int|IXR_Error
*/
public function mw_newPost( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$content_struct = $args[3];
$publish = isset( $args[4] ) ? $args[4] : 0;
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'metaWeblog.newPost', $args, $this );
$page_template = '';
if ( ! empty( $content_struct['post_type'] ) ) {
if ( 'page' === $content_struct['post_type'] ) {
if ( $publish ) {
$cap = 'publish_pages';
} elseif ( isset( $content_struct['page_status'] ) && 'publish' === $content_struct['page_status'] ) {
$cap = 'publish_pages';
} else {
$cap = 'edit_pages';
}
$error_message = __( 'Sorry, you are not allowed to publish pages on this site.' );
$post_type = 'page';
if ( ! empty( $content_struct['wp_page_template'] ) ) {
$page_template = $content_struct['wp_page_template'];
}
} elseif ( 'post' === $content_struct['post_type'] ) {
if ( $publish ) {
$cap = 'publish_posts';
} elseif ( isset( $content_struct['post_status'] ) && 'publish' === $content_struct['post_status'] ) {
$cap = 'publish_posts';
} else {
$cap = 'edit_posts';
}
$error_message = __( 'Sorry, you are not allowed to publish posts on this site.' );
$post_type = 'post';
} else {
// No other 'post_type' values are allowed here.
return new IXR_Error( 401, __( 'Invalid post type.' ) );
}
} else {
if ( $publish ) {
$cap = 'publish_posts';
} elseif ( isset( $content_struct['post_status'] ) && 'publish' === $content_struct['post_status'] ) {
$cap = 'publish_posts';
} else {
$cap = 'edit_posts';
}
$error_message = __( 'Sorry, you are not allowed to publish posts on this site.' );
$post_type = 'post';
}
if ( ! current_user_can( get_post_type_object( $post_type )->cap->create_posts ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish posts on this site.' ) );
}
if ( ! current_user_can( $cap ) ) {
return new IXR_Error( 401, $error_message );
}
// Check for a valid post format if one was given.
if ( isset( $content_struct['wp_post_format'] ) ) {
$content_struct['wp_post_format'] = sanitize_key( $content_struct['wp_post_format'] );
if ( ! array_key_exists( $content_struct['wp_post_format'], get_post_format_strings() ) ) {
return new IXR_Error( 404, __( 'Invalid post format.' ) );
}
}
// Let WordPress generate the 'post_name' (slug) unless
// one has been provided.
$post_name = null;
if ( isset( $content_struct['wp_slug'] ) ) {
$post_name = $content_struct['wp_slug'];
}
// Only use a password if one was given.
$post_password = '';
if ( isset( $content_struct['wp_password'] ) ) {
$post_password = $content_struct['wp_password'];
}
// Only set a post parent if one was given.
$post_parent = 0;
if ( isset( $content_struct['wp_page_parent_id'] ) ) {
$post_parent = $content_struct['wp_page_parent_id'];
}
// Only set the 'menu_order' if it was given.
$menu_order = 0;
if ( isset( $content_struct['wp_page_order'] ) ) {
$menu_order = $content_struct['wp_page_order'];
}
$post_author = $user->ID;
// If an author id was provided then use it instead.
if ( isset( $content_struct['wp_author_id'] ) && ( $user->ID != $content_struct['wp_author_id'] ) ) {
switch ( $post_type ) {
case 'post':
if ( ! current_user_can( 'edit_others_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to create posts as this user.' ) );
}
break;
case 'page':
if ( ! current_user_can( 'edit_others_pages' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to create pages as this user.' ) );
}
break;
default:
return new IXR_Error( 401, __( 'Invalid post type.' ) );
}
$author = get_userdata( $content_struct['wp_author_id'] );
if ( ! $author ) {
return new IXR_Error( 404, __( 'Invalid author ID.' ) );
}
$post_author = $content_struct['wp_author_id'];
}
$post_title = isset( $content_struct['title'] ) ? $content_struct['title'] : '';
$post_content = isset( $content_struct['description'] ) ? $content_struct['description'] : '';
$post_status = $publish ? 'publish' : 'draft';
if ( isset( $content_struct[ "{$post_type}_status" ] ) ) {
switch ( $content_struct[ "{$post_type}_status" ] ) {
case 'draft':
case 'pending':
case 'private':
case 'publish':
$post_status = $content_struct[ "{$post_type}_status" ];
break;
default:
// Deliberably left empty.
break;
}
}
$post_excerpt = isset( $content_struct['mt_excerpt'] ) ? $content_struct['mt_excerpt'] : '';
$post_more = isset( $content_struct['mt_text_more'] ) ? $content_struct['mt_text_more'] : '';
$tags_input = isset( $content_struct['mt_keywords'] ) ? $content_struct['mt_keywords'] : array();
if ( isset( $content_struct['mt_allow_comments'] ) ) {
if ( ! is_numeric( $content_struct['mt_allow_comments'] ) ) {
switch ( $content_struct['mt_allow_comments'] ) {
case 'closed':
$comment_status = 'closed';
break;
case 'open':
$comment_status = 'open';
break;
default:
$comment_status = get_default_comment_status( $post_type );
break;
}
} else {
switch ( (int) $content_struct['mt_allow_comments'] ) {
case 0:
case 2:
$comment_status = 'closed';
break;
case 1:
$comment_status = 'open';
break;
default:
$comment_status = get_default_comment_status( $post_type );
break;
}
}
} else {
$comment_status = get_default_comment_status( $post_type );
}
if ( isset( $content_struct['mt_allow_pings'] ) ) {
if ( ! is_numeric( $content_struct['mt_allow_pings'] ) ) {
switch ( $content_struct['mt_allow_pings'] ) {
case 'closed':
$ping_status = 'closed';
break;
case 'open':
$ping_status = 'open';
break;
default:
$ping_status = get_default_comment_status( $post_type, 'pingback' );
break;
}
} else {
switch ( (int) $content_struct['mt_allow_pings'] ) {
case 0:
$ping_status = 'closed';
break;
case 1:
$ping_status = 'open';
break;
default:
$ping_status = get_default_comment_status( $post_type, 'pingback' );
break;
}
}
} else {
$ping_status = get_default_comment_status( $post_type, 'pingback' );
}
if ( $post_more ) {
$post_content .= '<!--more-->' . $post_more;
}
$to_ping = '';
if ( isset( $content_struct['mt_tb_ping_urls'] ) ) {
$to_ping = $content_struct['mt_tb_ping_urls'];
if ( is_array( $to_ping ) ) {
$to_ping = implode( ' ', $to_ping );
}
}
// Do some timestamp voodoo.
if ( ! empty( $content_struct['date_created_gmt'] ) ) {
// We know this is supposed to be GMT, so we're going to slap that Z on there by force.
$dateCreated = rtrim( $content_struct['date_created_gmt']->getIso(), 'Z' ) . 'Z';
} elseif ( ! empty( $content_struct['dateCreated'] ) ) {
$dateCreated = $content_struct['dateCreated']->getIso();
}
$post_date = '';
$post_date_gmt = '';
if ( ! empty( $dateCreated ) ) {
$post_date = iso8601_to_datetime( $dateCreated );
$post_date_gmt = iso8601_to_datetime( $dateCreated, 'gmt' );
}
$post_category = array();
if ( isset( $content_struct['categories'] ) ) {
$catnames = $content_struct['categories'];
if ( is_array( $catnames ) ) {
foreach ( $catnames as $cat ) {
$post_category[] = get_cat_ID( $cat );
}
}
}
$postdata = compact( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'to_ping', 'post_type', 'post_name', 'post_password', 'post_parent', 'menu_order', 'tags_input', 'page_template' );
$post_ID = get_default_post_to_edit( $post_type, true )->ID;
$postdata['ID'] = $post_ID;
// Only posts can be sticky.
if ( 'post' === $post_type && isset( $content_struct['sticky'] ) ) {
$data = $postdata;
$data['sticky'] = $content_struct['sticky'];
$error = $this->_toggle_sticky( $data );
if ( $error ) {
return $error;
}
}
if ( isset( $content_struct['custom_fields'] ) ) {
$this->set_custom_fields( $post_ID, $content_struct['custom_fields'] );
}
if ( isset( $content_struct['wp_post_thumbnail'] ) ) {
if ( set_post_thumbnail( $post_ID, $content_struct['wp_post_thumbnail'] ) === false ) {
return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
}
unset( $content_struct['wp_post_thumbnail'] );
}
// Handle enclosures.
$thisEnclosure = isset( $content_struct['enclosure'] ) ? $content_struct['enclosure'] : null;
$this->add_enclosure_if_new( $post_ID, $thisEnclosure );
$this->attach_uploads( $post_ID, $post_content );
// Handle post formats if assigned, value is validated earlier
// in this function.
if ( isset( $content_struct['wp_post_format'] ) ) {
set_post_format( $post_ID, $content_struct['wp_post_format'] );
}
$post_ID = wp_insert_post( $postdata, true );
if ( is_wp_error( $post_ID ) ) {
return new IXR_Error( 500, $post_ID->get_error_message() );
}
if ( ! $post_ID ) {
return new IXR_Error( 500, __( 'Sorry, the post could not be created.' ) );
}
/**
* Fires after a new post has been successfully created via the XML-RPC MovableType API.
*
* @since 3.4.0
*
* @param int $post_ID ID of the new post.
* @param array $args An array of arguments to create the new post.
*/
do_action( 'xmlrpc_call_success_mw_newPost', $post_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return (string) $post_ID;
}
/**
* Adds an enclosure to a post if it's new.
*
* @since 2.8.0
*
* @param int $post_ID Post ID.
* @param array $enclosure Enclosure data.
*/
public function add_enclosure_if_new( $post_ID, $enclosure ) {
if ( is_array( $enclosure ) && isset( $enclosure['url'] ) && isset( $enclosure['length'] ) && isset( $enclosure['type'] ) ) {
$encstring = $enclosure['url'] . "\n" . $enclosure['length'] . "\n" . $enclosure['type'] . "\n";
$found = false;
$enclosures = get_post_meta( $post_ID, 'enclosure' );
if ( $enclosures ) {
foreach ( $enclosures as $enc ) {
// This method used to omit the trailing new line. #23219
if ( rtrim( $enc, "\n" ) == rtrim( $encstring, "\n" ) ) {
$found = true;
break;
}
}
}
if ( ! $found ) {
add_post_meta( $post_ID, 'enclosure', $encstring );
}
}
}
/**
* Attach upload to a post.
*
* @since 2.1.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $post_ID Post ID.
* @param string $post_content Post Content for attachment.
*/
public function attach_uploads( $post_ID, $post_content ) {
global $wpdb;
// Find any unattached files.
$attachments = $wpdb->get_results( "SELECT ID, guid FROM {$wpdb->posts} WHERE post_parent = '0' AND post_type = 'attachment'" );
if ( is_array( $attachments ) ) {
foreach ( $attachments as $file ) {
if ( ! empty( $file->guid ) && strpos( $post_content, $file->guid ) !== false ) {
$wpdb->update( $wpdb->posts, array( 'post_parent' => $post_ID ), array( 'ID' => $file->ID ) );
}
}
}
}
/**
* Edit a post.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Post ID.
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Content structure.
* @type int $4 Optional. Publish flag. 0 for draft, 1 for publish. Default 0.
* }
* @return true|IXR_Error True on success.
*/
public function mw_editPost( $args ) {
$this->escape( $args );
$post_ID = (int) $args[0];
$username = $args[1];
$password = $args[2];
$content_struct = $args[3];
$publish = isset( $args[4] ) ? $args[4] : 0;
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'metaWeblog.editPost', $args, $this );
$postdata = get_post( $post_ID, ARRAY_A );
/*
* If there is no post data for the give post ID, stop now and return an error.
* Otherwise a new post will be created (which was the old behavior).
*/
if ( ! $postdata || empty( $postdata['ID'] ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
// Use wp.editPost to edit post types other than post and page.
if ( ! in_array( $postdata['post_type'], array( 'post', 'page' ), true ) ) {
return new IXR_Error( 401, __( 'Invalid post type.' ) );
}
// Thwart attempt to change the post type.
if ( ! empty( $content_struct['post_type'] ) && ( $content_struct['post_type'] != $postdata['post_type'] ) ) {
return new IXR_Error( 401, __( 'The post type may not be changed.' ) );
}
// Check for a valid post format if one was given.
if ( isset( $content_struct['wp_post_format'] ) ) {
$content_struct['wp_post_format'] = sanitize_key( $content_struct['wp_post_format'] );
if ( ! array_key_exists( $content_struct['wp_post_format'], get_post_format_strings() ) ) {
return new IXR_Error( 404, __( 'Invalid post format.' ) );
}
}
$this->escape( $postdata );
$ID = $postdata['ID'];
$post_content = $postdata['post_content'];
$post_title = $postdata['post_title'];
$post_excerpt = $postdata['post_excerpt'];
$post_password = $postdata['post_password'];
$post_parent = $postdata['post_parent'];
$post_type = $postdata['post_type'];
$menu_order = $postdata['menu_order'];
$ping_status = $postdata['ping_status'];
$comment_status = $postdata['comment_status'];
// Let WordPress manage slug if none was provided.
$post_name = $postdata['post_name'];
if ( isset( $content_struct['wp_slug'] ) ) {
$post_name = $content_struct['wp_slug'];
}
// Only use a password if one was given.
if ( isset( $content_struct['wp_password'] ) ) {
$post_password = $content_struct['wp_password'];
}
// Only set a post parent if one was given.
if ( isset( $content_struct['wp_page_parent_id'] ) ) {
$post_parent = $content_struct['wp_page_parent_id'];
}
// Only set the 'menu_order' if it was given.
if ( isset( $content_struct['wp_page_order'] ) ) {
$menu_order = $content_struct['wp_page_order'];
}
$page_template = '';
if ( ! empty( $content_struct['wp_page_template'] ) && 'page' === $post_type ) {
$page_template = $content_struct['wp_page_template'];
}
$post_author = $postdata['post_author'];
// If an author id was provided then use it instead.
if ( isset( $content_struct['wp_author_id'] ) ) {
// Check permissions if attempting to switch author to or from another user.
if ( $user->ID != $content_struct['wp_author_id'] || $user->ID != $post_author ) {
switch ( $post_type ) {
case 'post':
if ( ! current_user_can( 'edit_others_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to change the post author as this user.' ) );
}
break;
case 'page':
if ( ! current_user_can( 'edit_others_pages' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to change the page author as this user.' ) );
}
break;
default:
return new IXR_Error( 401, __( 'Invalid post type.' ) );
}
$post_author = $content_struct['wp_author_id'];
}
}
if ( isset( $content_struct['mt_allow_comments'] ) ) {
if ( ! is_numeric( $content_struct['mt_allow_comments'] ) ) {
switch ( $content_struct['mt_allow_comments'] ) {
case 'closed':
$comment_status = 'closed';
break;
case 'open':
$comment_status = 'open';
break;
default:
$comment_status = get_default_comment_status( $post_type );
break;
}
} else {
switch ( (int) $content_struct['mt_allow_comments'] ) {
case 0:
case 2:
$comment_status = 'closed';
break;
case 1:
$comment_status = 'open';
break;
default:
$comment_status = get_default_comment_status( $post_type );
break;
}
}
}
if ( isset( $content_struct['mt_allow_pings'] ) ) {
if ( ! is_numeric( $content_struct['mt_allow_pings'] ) ) {
switch ( $content_struct['mt_allow_pings'] ) {
case 'closed':
$ping_status = 'closed';
break;
case 'open':
$ping_status = 'open';
break;
default:
$ping_status = get_default_comment_status( $post_type, 'pingback' );
break;
}
} else {
switch ( (int) $content_struct['mt_allow_pings'] ) {
case 0:
$ping_status = 'closed';
break;
case 1:
$ping_status = 'open';
break;
default:
$ping_status = get_default_comment_status( $post_type, 'pingback' );
break;
}
}
}
if ( isset( $content_struct['title'] ) ) {
$post_title = $content_struct['title'];
}
if ( isset( $content_struct['description'] ) ) {
$post_content = $content_struct['description'];
}
$post_category = array();
if ( isset( $content_struct['categories'] ) ) {
$catnames = $content_struct['categories'];
if ( is_array( $catnames ) ) {
foreach ( $catnames as $cat ) {
$post_category[] = get_cat_ID( $cat );
}
}
}
if ( isset( $content_struct['mt_excerpt'] ) ) {
$post_excerpt = $content_struct['mt_excerpt'];
}
$post_more = isset( $content_struct['mt_text_more'] ) ? $content_struct['mt_text_more'] : '';
$post_status = $publish ? 'publish' : 'draft';
if ( isset( $content_struct[ "{$post_type}_status" ] ) ) {
switch ( $content_struct[ "{$post_type}_status" ] ) {
case 'draft':
case 'pending':
case 'private':
case 'publish':
$post_status = $content_struct[ "{$post_type}_status" ];
break;
default:
$post_status = $publish ? 'publish' : 'draft';
break;
}
}
$tags_input = isset( $content_struct['mt_keywords'] ) ? $content_struct['mt_keywords'] : array();
if ( 'publish' === $post_status || 'private' === $post_status ) {
if ( 'page' === $post_type && ! current_user_can( 'publish_pages' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this page.' ) );
} elseif ( ! current_user_can( 'publish_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this post.' ) );
}
}
if ( $post_more ) {
$post_content = $post_content . '<!--more-->' . $post_more;
}
$to_ping = '';
if ( isset( $content_struct['mt_tb_ping_urls'] ) ) {
$to_ping = $content_struct['mt_tb_ping_urls'];
if ( is_array( $to_ping ) ) {
$to_ping = implode( ' ', $to_ping );
}
}
// Do some timestamp voodoo.
if ( ! empty( $content_struct['date_created_gmt'] ) ) {
// We know this is supposed to be GMT, so we're going to slap that Z on there by force.
$dateCreated = rtrim( $content_struct['date_created_gmt']->getIso(), 'Z' ) . 'Z';
} elseif ( ! empty( $content_struct['dateCreated'] ) ) {
$dateCreated = $content_struct['dateCreated']->getIso();
}
// Default to not flagging the post date to be edited unless it's intentional.
$edit_date = false;
if ( ! empty( $dateCreated ) ) {
$post_date = iso8601_to_datetime( $dateCreated );
$post_date_gmt = iso8601_to_datetime( $dateCreated, 'gmt' );
// Flag the post date to be edited.
$edit_date = true;
} else {
$post_date = $postdata['post_date'];
$post_date_gmt = $postdata['post_date_gmt'];
}
// We've got all the data -- post it.
$newpost = compact( 'ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'edit_date', 'post_date', 'post_date_gmt', 'to_ping', 'post_name', 'post_password', 'post_parent', 'menu_order', 'post_author', 'tags_input', 'page_template' );
$result = wp_update_post( $newpost, true );
if ( is_wp_error( $result ) ) {
return new IXR_Error( 500, $result->get_error_message() );
}
if ( ! $result ) {
return new IXR_Error( 500, __( 'Sorry, the post could not be updated.' ) );
}
// Only posts can be sticky.
if ( 'post' === $post_type && isset( $content_struct['sticky'] ) ) {
$data = $newpost;
$data['sticky'] = $content_struct['sticky'];
$data['post_type'] = 'post';
$error = $this->_toggle_sticky( $data, true );
if ( $error ) {
return $error;
}
}
if ( isset( $content_struct['custom_fields'] ) ) {
$this->set_custom_fields( $post_ID, $content_struct['custom_fields'] );
}
if ( isset( $content_struct['wp_post_thumbnail'] ) ) {
// Empty value deletes, non-empty value adds/updates.
if ( empty( $content_struct['wp_post_thumbnail'] ) ) {
delete_post_thumbnail( $post_ID );
} else {
if ( set_post_thumbnail( $post_ID, $content_struct['wp_post_thumbnail'] ) === false ) {
return new IXR_Error( 404, __( 'Invalid attachment ID.' ) );
}
}
unset( $content_struct['wp_post_thumbnail'] );
}
// Handle enclosures.
$thisEnclosure = isset( $content_struct['enclosure'] ) ? $content_struct['enclosure'] : null;
$this->add_enclosure_if_new( $post_ID, $thisEnclosure );
$this->attach_uploads( $ID, $post_content );
// Handle post formats if assigned, validation is handled earlier in this function.
if ( isset( $content_struct['wp_post_format'] ) ) {
set_post_format( $post_ID, $content_struct['wp_post_format'] );
}
/**
* Fires after a post has been successfully updated via the XML-RPC MovableType API.
*
* @since 3.4.0
*
* @param int $post_ID ID of the updated post.
* @param array $args An array of arguments to update the post.
*/
do_action( 'xmlrpc_call_success_mw_editPost', $post_ID, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
return true;
}
/**
* Retrieve post.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Post ID.
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error
*/
public function mw_getPost( $args ) {
$this->escape( $args );
$post_ID = (int) $args[0];
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
$postdata = get_post( $post_ID, ARRAY_A );
if ( ! $postdata ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'metaWeblog.getPost', $args, $this );
if ( '' !== $postdata['post_date'] ) {
$post_date = $this->_convert_date( $postdata['post_date'] );
$post_date_gmt = $this->_convert_date_gmt( $postdata['post_date_gmt'], $postdata['post_date'] );
$post_modified = $this->_convert_date( $postdata['post_modified'] );
$post_modified_gmt = $this->_convert_date_gmt( $postdata['post_modified_gmt'], $postdata['post_modified'] );
$categories = array();
$catids = wp_get_post_categories( $post_ID );
foreach ( $catids as $catid ) {
$categories[] = get_cat_name( $catid );
}
$tagnames = array();
$tags = wp_get_post_tags( $post_ID );
if ( ! empty( $tags ) ) {
foreach ( $tags as $tag ) {
$tagnames[] = $tag->name;
}
$tagnames = implode( ', ', $tagnames );
} else {
$tagnames = '';
}
$post = get_extended( $postdata['post_content'] );
$link = get_permalink( $postdata['ID'] );
// Get the author info.
$author = get_userdata( $postdata['post_author'] );
$allow_comments = ( 'open' === $postdata['comment_status'] ) ? 1 : 0;
$allow_pings = ( 'open' === $postdata['ping_status'] ) ? 1 : 0;
// Consider future posts as published.
if ( 'future' === $postdata['post_status'] ) {
$postdata['post_status'] = 'publish';
}
// Get post format.
$post_format = get_post_format( $post_ID );
if ( empty( $post_format ) ) {
$post_format = 'standard';
}
$sticky = false;
if ( is_sticky( $post_ID ) ) {
$sticky = true;
}
$enclosure = array();
foreach ( (array) get_post_custom( $post_ID ) as $key => $val ) {
if ( 'enclosure' === $key ) {
foreach ( (array) $val as $enc ) {
$encdata = explode( "\n", $enc );
$enclosure['url'] = trim( htmlspecialchars( $encdata[0] ) );
$enclosure['length'] = (int) trim( $encdata[1] );
$enclosure['type'] = trim( $encdata[2] );
break 2;
}
}
}
$resp = array(
'dateCreated' => $post_date,
'userid' => $postdata['post_author'],
'postid' => $postdata['ID'],
'description' => $post['main'],
'title' => $postdata['post_title'],
'link' => $link,
'permaLink' => $link,
// Commented out because no other tool seems to use this.
// 'content' => $entry['post_content'],
'categories' => $categories,
'mt_excerpt' => $postdata['post_excerpt'],
'mt_text_more' => $post['extended'],
'wp_more_text' => $post['more_text'],
'mt_allow_comments' => $allow_comments,
'mt_allow_pings' => $allow_pings,
'mt_keywords' => $tagnames,
'wp_slug' => $postdata['post_name'],
'wp_password' => $postdata['post_password'],
'wp_author_id' => (string) $author->ID,
'wp_author_display_name' => $author->display_name,
'date_created_gmt' => $post_date_gmt,
'post_status' => $postdata['post_status'],
'custom_fields' => $this->get_custom_fields( $post_ID ),
'wp_post_format' => $post_format,
'sticky' => $sticky,
'date_modified' => $post_modified,
'date_modified_gmt' => $post_modified_gmt,
);
if ( ! empty( $enclosure ) ) {
$resp['enclosure'] = $enclosure;
}
$resp['wp_post_thumbnail'] = get_post_thumbnail_id( $postdata['ID'] );
return $resp;
} else {
return new IXR_Error( 404, __( 'Sorry, no such post.' ) );
}
}
/**
* Retrieve list of recent posts.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Optional. Number of posts.
* }
* @return array|IXR_Error
*/
public function mw_getRecentPosts( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
if ( isset( $args[3] ) ) {
$query = array( 'numberposts' => absint( $args[3] ) );
} else {
$query = array();
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit posts.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'metaWeblog.getRecentPosts', $args, $this );
$posts_list = wp_get_recent_posts( $query );
if ( ! $posts_list ) {
return array();
}
$recent_posts = array();
foreach ( $posts_list as $entry ) {
if ( ! current_user_can( 'edit_post', $entry['ID'] ) ) {
continue;
}
$post_date = $this->_convert_date( $entry['post_date'] );
$post_date_gmt = $this->_convert_date_gmt( $entry['post_date_gmt'], $entry['post_date'] );
$post_modified = $this->_convert_date( $entry['post_modified'] );
$post_modified_gmt = $this->_convert_date_gmt( $entry['post_modified_gmt'], $entry['post_modified'] );
$categories = array();
$catids = wp_get_post_categories( $entry['ID'] );
foreach ( $catids as $catid ) {
$categories[] = get_cat_name( $catid );
}
$tagnames = array();
$tags = wp_get_post_tags( $entry['ID'] );
if ( ! empty( $tags ) ) {
foreach ( $tags as $tag ) {
$tagnames[] = $tag->name;
}
$tagnames = implode( ', ', $tagnames );
} else {
$tagnames = '';
}
$post = get_extended( $entry['post_content'] );
$link = get_permalink( $entry['ID'] );
// Get the post author info.
$author = get_userdata( $entry['post_author'] );
$allow_comments = ( 'open' === $entry['comment_status'] ) ? 1 : 0;
$allow_pings = ( 'open' === $entry['ping_status'] ) ? 1 : 0;
// Consider future posts as published.
if ( 'future' === $entry['post_status'] ) {
$entry['post_status'] = 'publish';
}
// Get post format.
$post_format = get_post_format( $entry['ID'] );
if ( empty( $post_format ) ) {
$post_format = 'standard';
}
$recent_posts[] = array(
'dateCreated' => $post_date,
'userid' => $entry['post_author'],
'postid' => (string) $entry['ID'],
'description' => $post['main'],
'title' => $entry['post_title'],
'link' => $link,
'permaLink' => $link,
// Commented out because no other tool seems to use this.
// 'content' => $entry['post_content'],
'categories' => $categories,
'mt_excerpt' => $entry['post_excerpt'],
'mt_text_more' => $post['extended'],
'wp_more_text' => $post['more_text'],
'mt_allow_comments' => $allow_comments,
'mt_allow_pings' => $allow_pings,
'mt_keywords' => $tagnames,
'wp_slug' => $entry['post_name'],
'wp_password' => $entry['post_password'],
'wp_author_id' => (string) $author->ID,
'wp_author_display_name' => $author->display_name,
'date_created_gmt' => $post_date_gmt,
'post_status' => $entry['post_status'],
'custom_fields' => $this->get_custom_fields( $entry['ID'] ),
'wp_post_format' => $post_format,
'date_modified' => $post_modified,
'date_modified_gmt' => $post_modified_gmt,
'sticky' => ( 'post' === $entry['post_type'] && is_sticky( $entry['ID'] ) ),
'wp_post_thumbnail' => get_post_thumbnail_id( $entry['ID'] ),
);
}
return $recent_posts;
}
/**
* Retrieve the list of categories on a given blog.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error
*/
public function mw_getCategories( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view categories.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'metaWeblog.getCategories', $args, $this );
$categories_struct = array();
$cats = get_categories( array( 'get' => 'all' ) );
if ( $cats ) {
foreach ( $cats as $cat ) {
$struct = array();
$struct['categoryId'] = $cat->term_id;
$struct['parentId'] = $cat->parent;
$struct['description'] = $cat->name;
$struct['categoryDescription'] = $cat->description;
$struct['categoryName'] = $cat->name;
$struct['htmlUrl'] = esc_html( get_category_link( $cat->term_id ) );
$struct['rssUrl'] = esc_html( get_category_feed_link( $cat->term_id, 'rss2' ) );
$categories_struct[] = $struct;
}
}
return $categories_struct;
}
/**
* Uploads a file, following your settings.
*
* Adapted from a patch by Johann Richard.
*
* @link http://mycvs.org/archives/2004/06/30/file-upload-to-wordpress-in-ecto/
*
* @since 1.5.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Data.
* }
* @return array|IXR_Error
*/
public function mw_newMediaObject( $args ) {
global $wpdb;
$username = $this->escape( $args[1] );
$password = $this->escape( $args[2] );
$data = $args[3];
$name = sanitize_file_name( $data['name'] );
$type = $data['type'];
$bits = $data['bits'];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'metaWeblog.newMediaObject', $args, $this );
if ( ! current_user_can( 'upload_files' ) ) {
$this->error = new IXR_Error( 401, __( 'Sorry, you are not allowed to upload files.' ) );
return $this->error;
}
if ( is_multisite() && upload_is_user_over_quota( false ) ) {
$this->error = new IXR_Error(
401,
sprintf(
/* translators: %s: Allowed space allocation. */
__( 'Sorry, you have used your space allocation of %s. Please delete some files to upload more files.' ),
size_format( get_space_allowed() * MB_IN_BYTES )
)
);
return $this->error;
}
/**
* Filters whether to preempt the XML-RPC media upload.
*
* Returning a truthy value will effectively short-circuit the media upload,
* returning that value as a 500 error instead.
*
* @since 2.1.0
*
* @param bool $error Whether to pre-empt the media upload. Default false.
*/
$upload_err = apply_filters( 'pre_upload_error', false );
if ( $upload_err ) {
return new IXR_Error( 500, $upload_err );
}
$upload = wp_upload_bits( $name, null, $bits );
if ( ! empty( $upload['error'] ) ) {
/* translators: 1: File name, 2: Error message. */
$errorString = sprintf( __( 'Could not write file %1$s (%2$s).' ), $name, $upload['error'] );
return new IXR_Error( 500, $errorString );
}
// Construct the attachment array.
$post_id = 0;
if ( ! empty( $data['post_id'] ) ) {
$post_id = (int) $data['post_id'];
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
}
$attachment = array(
'post_title' => $name,
'post_content' => '',
'post_type' => 'attachment',
'post_parent' => $post_id,
'post_mime_type' => $type,
'guid' => $upload['url'],
);
// Save the data.
$id = wp_insert_attachment( $attachment, $upload['file'], $post_id );
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );
/**
* Fires after a new attachment has been added via the XML-RPC MovableType API.
*
* @since 3.4.0
*
* @param int $id ID of the new attachment.
* @param array $args An array of arguments to add the attachment.
*/
do_action( 'xmlrpc_call_success_mw_newMediaObject', $id, $args ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.NotLowercase
$struct = $this->_prepare_media_item( get_post( $id ) );
// Deprecated values.
$struct['id'] = $struct['attachment_id'];
$struct['file'] = $struct['title'];
$struct['url'] = $struct['link'];
return $struct;
}
/*
* MovableType API functions.
* Specs on http://www.movabletype.org/docs/mtmanual_programmatic.html
*/
/**
* Retrieve the post titles of recent posts.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* @type int $3 Optional. Number of posts.
* }
* @return array|IXR_Error
*/
public function mt_getRecentPostTitles( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
if ( isset( $args[3] ) ) {
$query = array( 'numberposts' => absint( $args[3] ) );
} else {
$query = array();
}
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.getRecentPostTitles', $args, $this );
$posts_list = wp_get_recent_posts( $query );
if ( ! $posts_list ) {
$this->error = new IXR_Error( 500, __( 'Either there are no posts, or something went wrong.' ) );
return $this->error;
}
$recent_posts = array();
foreach ( $posts_list as $entry ) {
if ( ! current_user_can( 'edit_post', $entry['ID'] ) ) {
continue;
}
$post_date = $this->_convert_date( $entry['post_date'] );
$post_date_gmt = $this->_convert_date_gmt( $entry['post_date_gmt'], $entry['post_date'] );
$recent_posts[] = array(
'dateCreated' => $post_date,
'userid' => $entry['post_author'],
'postid' => (string) $entry['ID'],
'title' => $entry['post_title'],
'post_status' => $entry['post_status'],
'date_created_gmt' => $post_date_gmt,
);
}
return $recent_posts;
}
/**
* Retrieve list of all categories on blog.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Blog ID (unused).
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error
*/
public function mt_getCategoryList( $args ) {
$this->escape( $args );
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! current_user_can( 'edit_posts' ) ) {
return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this site in order to view categories.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.getCategoryList', $args, $this );
$categories_struct = array();
$cats = get_categories(
array(
'hide_empty' => 0,
'hierarchical' => 0,
)
);
if ( $cats ) {
foreach ( $cats as $cat ) {
$struct = array();
$struct['categoryId'] = $cat->term_id;
$struct['categoryName'] = $cat->name;
$categories_struct[] = $struct;
}
}
return $categories_struct;
}
/**
* Retrieve post categories.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Post ID.
* @type string $1 Username.
* @type string $2 Password.
* }
* @return array|IXR_Error
*/
public function mt_getPostCategories( $args ) {
$this->escape( $args );
$post_ID = (int) $args[0];
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
if ( ! get_post( $post_ID ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.getPostCategories', $args, $this );
$categories = array();
$catids = wp_get_post_categories( (int) $post_ID );
// First listed category will be the primary category.
$isPrimary = true;
foreach ( $catids as $catid ) {
$categories[] = array(
'categoryName' => get_cat_name( $catid ),
'categoryId' => (string) $catid,
'isPrimary' => $isPrimary,
);
$isPrimary = false;
}
return $categories;
}
/**
* Sets categories for a post.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Post ID.
* @type string $1 Username.
* @type string $2 Password.
* @type array $3 Categories.
* }
* @return true|IXR_Error True on success.
*/
public function mt_setPostCategories( $args ) {
$this->escape( $args );
$post_ID = (int) $args[0];
$username = $args[1];
$password = $args[2];
$categories = $args[3];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.setPostCategories', $args, $this );
if ( ! get_post( $post_ID ) ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'edit_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to edit this post.' ) );
}
$catids = array();
foreach ( $categories as $cat ) {
$catids[] = $cat['categoryId'];
}
wp_set_post_categories( $post_ID, $catids );
return true;
}
/**
* Retrieve an array of methods supported by this server.
*
* @since 1.5.0
*
* @return array
*/
public function mt_supportedMethods() {
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.supportedMethods', array(), $this );
return array_keys( $this->methods );
}
/**
* Retrieve an empty array because we don't support per-post text filters.
*
* @since 1.5.0
*/
public function mt_supportedTextFilters() {
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.supportedTextFilters', array(), $this );
/**
* Filters the MoveableType text filters list for XML-RPC.
*
* @since 2.2.0
*
* @param array $filters An array of text filters.
*/
return apply_filters( 'xmlrpc_text_filters', array() );
}
/**
* Retrieve trackbacks sent to a given post.
*
* @since 1.5.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $post_ID
* @return array|IXR_Error
*/
public function mt_getTrackbackPings( $post_ID ) {
global $wpdb;
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.getTrackbackPings', $post_ID, $this );
$actual_post = get_post( $post_ID, ARRAY_A );
if ( ! $actual_post ) {
return new IXR_Error( 404, __( 'Sorry, no such post.' ) );
}
$comments = $wpdb->get_results( $wpdb->prepare( "SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = %d", $post_ID ) );
if ( ! $comments ) {
return array();
}
$trackback_pings = array();
foreach ( $comments as $comment ) {
if ( 'trackback' === $comment->comment_type ) {
$content = $comment->comment_content;
$title = substr( $content, 8, ( strpos( $content, '</strong>' ) - 8 ) );
$trackback_pings[] = array(
'pingTitle' => $title,
'pingURL' => $comment->comment_author_url,
'pingIP' => $comment->comment_author_IP,
);
}
}
return $trackback_pings;
}
/**
* Sets a post's publish status to 'publish'.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type int $0 Post ID.
* @type string $1 Username.
* @type string $2 Password.
* }
* @return int|IXR_Error
*/
public function mt_publishPost( $args ) {
$this->escape( $args );
$post_ID = (int) $args[0];
$username = $args[1];
$password = $args[2];
$user = $this->login( $username, $password );
if ( ! $user ) {
return $this->error;
}
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'mt.publishPost', $args, $this );
$postdata = get_post( $post_ID, ARRAY_A );
if ( ! $postdata ) {
return new IXR_Error( 404, __( 'Invalid post ID.' ) );
}
if ( ! current_user_can( 'publish_posts' ) || ! current_user_can( 'edit_post', $post_ID ) ) {
return new IXR_Error( 401, __( 'Sorry, you are not allowed to publish this post.' ) );
}
$postdata['post_status'] = 'publish';
// Retain old categories.
$postdata['post_category'] = wp_get_post_categories( $post_ID );
$this->escape( $postdata );
return wp_update_post( $postdata );
}
/*
* Pingback functions.
* Specs on www.hixie.ch/specs/pingback/pingback
*/
/**
* Retrieves a pingback and registers it.
*
* @since 1.5.0
*
* @param array $args {
* Method arguments. Note: arguments must be ordered as documented.
*
* @type string $0 URL of page linked from.
* @type string $1 URL of page linked to.
* }
* @return string|IXR_Error
*/
public function pingback_ping( $args ) {
global $wpdb;
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'pingback.ping', $args, $this );
$this->escape( $args );
$pagelinkedfrom = str_replace( '&', '&', $args[0] );
$pagelinkedto = str_replace( '&', '&', $args[1] );
$pagelinkedto = str_replace( '&', '&', $pagelinkedto );
/**
* Filters the pingback source URI.
*
* @since 3.6.0
*
* @param string $pagelinkedfrom URI of the page linked from.
* @param string $pagelinkedto URI of the page linked to.
*/
$pagelinkedfrom = apply_filters( 'pingback_ping_source_uri', $pagelinkedfrom, $pagelinkedto );
if ( ! $pagelinkedfrom ) {
return $this->pingback_error( 0, __( 'A valid URL was not provided.' ) );
}
// Check if the page linked to is on our site.
$pos1 = strpos( $pagelinkedto, str_replace( array( 'http://www.', 'http://', 'https://www.', 'https://' ), '', get_option( 'home' ) ) );
if ( ! $pos1 ) {
return $this->pingback_error( 0, __( 'Is there no link to us?' ) );
}
/*
* Let's find which post is linked to.
* FIXME: Does url_to_postid() cover all these cases already?
* If so, then let's use it and drop the old code.
*/
$urltest = parse_url( $pagelinkedto );
$post_ID = url_to_postid( $pagelinkedto );
if ( $post_ID ) {
// $way
} elseif ( isset( $urltest['path'] ) && preg_match( '#p/[0-9]{1,}#', $urltest['path'], $match ) ) {
// The path defines the post_ID (archives/p/XXXX).
$blah = explode( '/', $match[0] );
$post_ID = (int) $blah[1];
} elseif ( isset( $urltest['query'] ) && preg_match( '#p=[0-9]{1,}#', $urltest['query'], $match ) ) {
// The query string defines the post_ID (?p=XXXX).
$blah = explode( '=', $match[0] );
$post_ID = (int) $blah[1];
} elseif ( isset( $urltest['fragment'] ) ) {
// An #anchor is there, it's either...
if ( (int) $urltest['fragment'] ) {
// ...an integer #XXXX (simplest case),
$post_ID = (int) $urltest['fragment'];
} elseif ( preg_match( '/post-[0-9]+/', $urltest['fragment'] ) ) {
// ...a post ID in the form 'post-###',
$post_ID = preg_replace( '/[^0-9]+/', '', $urltest['fragment'] );
} elseif ( is_string( $urltest['fragment'] ) ) {
// ...or a string #title, a little more complicated.
$title = preg_replace( '/[^a-z0-9]/i', '.', $urltest['fragment'] );
$sql = $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title RLIKE %s", $title );
$post_ID = $wpdb->get_var( $sql );
if ( ! $post_ID ) {
// Returning unknown error '0' is better than die()'ing.
return $this->pingback_error( 0, '' );
}
}
} else {
// TODO: Attempt to extract a post ID from the given URL.
return $this->pingback_error( 33, __( 'The specified target URL cannot be used as a target. It either does not exist, or it is not a pingback-enabled resource.' ) );
}
$post_ID = (int) $post_ID;
$post = get_post( $post_ID );
if ( ! $post ) { // Post not found.
return $this->pingback_error( 33, __( 'The specified target URL cannot be used as a target. It either does not exist, or it is not a pingback-enabled resource.' ) );
}
if ( url_to_postid( $pagelinkedfrom ) == $post_ID ) {
return $this->pingback_error( 0, __( 'The source URL and the target URL cannot both point to the same resource.' ) );
}
// Check if pings are on.
if ( ! pings_open( $post ) ) {
return $this->pingback_error( 33, __( 'The specified target URL cannot be used as a target. It either does not exist, or it is not a pingback-enabled resource.' ) );
}
// Let's check that the remote site didn't already pingback this entry.
if ( $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_author_url = %s", $post_ID, $pagelinkedfrom ) ) ) {
return $this->pingback_error( 48, __( 'The pingback has already been registered.' ) );
}
// Very stupid, but gives time to the 'from' server to publish!
sleep( 1 );
$remote_ip = preg_replace( '/[^0-9a-fA-F:., ]/', '', $_SERVER['REMOTE_ADDR'] );
/** This filter is documented in wp-includes/class-wp-http.php */
$user_agent = apply_filters( 'http_headers_useragent', 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ), $pagelinkedfrom );
// Let's check the remote site.
$http_api_args = array(
'timeout' => 10,
'redirection' => 0,
'limit_response_size' => 153600, // 150 KB
'user-agent' => "$user_agent; verifying pingback from $remote_ip",
'headers' => array(
'X-Pingback-Forwarded-For' => $remote_ip,
),
);
$request = wp_safe_remote_get( $pagelinkedfrom, $http_api_args );
$remote_source = wp_remote_retrieve_body( $request );
$remote_source_original = $remote_source;
if ( ! $remote_source ) {
return $this->pingback_error( 16, __( 'The source URL does not exist.' ) );
}
/**
* Filters the pingback remote source.
*
* @since 2.5.0
*
* @param string $remote_source Response source for the page linked from.
* @param string $pagelinkedto URL of the page linked to.
*/
$remote_source = apply_filters( 'pre_remote_source', $remote_source, $pagelinkedto );
// Work around bug in strip_tags():
$remote_source = str_replace( '<!DOC', '<DOC', $remote_source );
$remote_source = preg_replace( '/[\r\n\t ]+/', ' ', $remote_source ); // normalize spaces
$remote_source = preg_replace( '/<\/*(h1|h2|h3|h4|h5|h6|p|th|td|li|dt|dd|pre|caption|input|textarea|button|body)[^>]*>/', "\n\n", $remote_source );
preg_match( '|<title>([^<]*?)</title>|is', $remote_source, $matchtitle );
$title = isset( $matchtitle[1] ) ? $matchtitle[1] : '';
if ( empty( $title ) ) {
return $this->pingback_error( 32, __( 'A title on that page cannot be found.' ) );
}
// Remove all script and style tags including their content.
$remote_source = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $remote_source );
// Just keep the tag we need.
$remote_source = strip_tags( $remote_source, '<a>' );
$p = explode( "\n\n", $remote_source );
$preg_target = preg_quote( $pagelinkedto, '|' );
foreach ( $p as $para ) {
if ( strpos( $para, $pagelinkedto ) !== false ) { // It exists, but is it a link?
preg_match( '|<a[^>]+?' . $preg_target . '[^>]*>([^>]+?)</a>|', $para, $context );
// If the URL isn't in a link context, keep looking.
if ( empty( $context ) ) {
continue;
}
// We're going to use this fake tag to mark the context in a bit.
// The marker is needed in case the link text appears more than once in the paragraph.
$excerpt = preg_replace( '|\</?wpcontext\>|', '', $para );
// prevent really long link text
if ( strlen( $context[1] ) > 100 ) {
$context[1] = substr( $context[1], 0, 100 ) . '…';
}
$marker = '<wpcontext>' . $context[1] . '</wpcontext>'; // Set up our marker.
$excerpt = str_replace( $context[0], $marker, $excerpt ); // Swap out the link for our marker.
$excerpt = strip_tags( $excerpt, '<wpcontext>' ); // Strip all tags but our context marker.
$excerpt = trim( $excerpt );
$preg_marker = preg_quote( $marker, '|' );
$excerpt = preg_replace( "|.*?\s(.{0,100}$preg_marker.{0,100})\s.*|s", '$1', $excerpt );
$excerpt = strip_tags( $excerpt ); // YES, again, to remove the marker wrapper.
break;
}
}
if ( empty( $context ) ) { // Link to target not found.
return $this->pingback_error( 17, __( 'The source URL does not contain a link to the target URL, and so cannot be used as a source.' ) );
}
$pagelinkedfrom = str_replace( '&', '&', $pagelinkedfrom );
$context = '[…] ' . esc_html( $excerpt ) . ' […]';
$pagelinkedfrom = $this->escape( $pagelinkedfrom );
$comment_post_id = (int) $post_ID;
$comment_author = $title;
$comment_author_email = '';
$this->escape( $comment_author );
$comment_author_url = $pagelinkedfrom;
$comment_content = $context;
$this->escape( $comment_content );
$comment_type = 'pingback';
$commentdata = array(
'comment_post_ID' => $comment_post_id,
);
$commentdata += compact(
'comment_author',
'comment_author_url',
'comment_author_email',
'comment_content',
'comment_type',
'remote_source',
'remote_source_original'
);
$comment_ID = wp_new_comment( $commentdata );
if ( is_wp_error( $comment_ID ) ) {
return $this->pingback_error( 0, $comment_ID->get_error_message() );
}
/**
* Fires after a post pingback has been sent.
*
* @since 0.71
*
* @param int $comment_ID Comment ID.
*/
do_action( 'pingback_post', $comment_ID );
/* translators: 1: URL of the page linked from, 2: URL of the page linked to. */
return sprintf( __( 'Pingback from %1$s to %2$s registered. Keep the web talking! :-)' ), $pagelinkedfrom, $pagelinkedto );
}
/**
* Retrieve array of URLs that pingbacked the given URL.
*
* Specs on http://www.aquarionics.com/misc/archives/blogite/0198.html
*
* @since 1.5.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $url
* @return array|IXR_Error
*/
public function pingback_extensions_getPingbacks( $url ) {
global $wpdb;
/** This action is documented in wp-includes/class-wp-xmlrpc-server.php */
do_action( 'xmlrpc_call', 'pingback.extensions.getPingbacks', $url, $this );
$url = $this->escape( $url );
$post_ID = url_to_postid( $url );
if ( ! $post_ID ) {
// We aren't sure that the resource is available and/or pingback enabled.
return $this->pingback_error( 33, __( 'The specified target URL cannot be used as a target. It either does not exist, or it is not a pingback-enabled resource.' ) );
}
$actual_post = get_post( $post_ID, ARRAY_A );
if ( ! $actual_post ) {
// No such post = resource not found.
return $this->pingback_error( 32, __( 'The specified target URL does not exist.' ) );
}
$comments = $wpdb->get_results( $wpdb->prepare( "SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = %d", $post_ID ) );
if ( ! $comments ) {
return array();
}
$pingbacks = array();
foreach ( $comments as $comment ) {
if ( 'pingback' === $comment->comment_type ) {
$pingbacks[] = $comment->comment_author_url;
}
}
return $pingbacks;
}
/**
* Sends a pingback error based on the given error code and message.
*
* @since 3.6.0
*
* @param int $code Error code.
* @param string $message Error message.
* @return IXR_Error Error object.
*/
protected function pingback_error( $code, $message ) {
/**
* Filters the XML-RPC pingback error return.
*
* @since 3.5.1
*
* @param IXR_Error $error An IXR_Error object containing the error code and message.
*/
return apply_filters( 'xmlrpc_pingback_error', new IXR_Error( $code, $message ) );
}
}
```
| 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. |
| programming_docs |
wordpress class WP_Customize_Nav_Menu_Item_Control {} class WP\_Customize\_Nav\_Menu\_Item\_Control {}
================================================
Customize control to represent the name field for a given menu.
* [WP\_Customize\_Control](wp_customize_control)
* [\_\_construct](wp_customize_nav_menu_item_control/__construct) — Constructor.
* [content\_template](wp_customize_nav_menu_item_control/content_template) — JS/Underscore template for the control UI.
* [json](wp_customize_nav_menu_item_control/json) — Return parameters for this control.
* [render\_content](wp_customize_nav_menu_item_control/render_content) — Don't render the control's content - it's rendered with a JS template.
File: `wp-includes/customize/class-wp-customize-nav-menu-item-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-item-control.php/)
```
class WP_Customize_Nav_Menu_Item_Control extends WP_Customize_Control {
/**
* Control type.
*
* @since 4.3.0
* @var string
*/
public $type = 'nav_menu_item';
/**
* The nav menu item setting.
*
* @since 4.3.0
* @var WP_Customize_Nav_Menu_Item_Setting
*/
public $setting;
/**
* Constructor.
*
* @since 4.3.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( $manager, $id, $args = array() ) {
parent::__construct( $manager, $id, $args );
}
/**
* Don't render the control's content - it's rendered with a JS template.
*
* @since 4.3.0
*/
public function render_content() {}
/**
* JS/Underscore template for the control UI.
*
* @since 4.3.0
*/
public function content_template() {
?>
<div class="menu-item-bar">
<div class="menu-item-handle">
<span class="item-type" aria-hidden="true">{{ data.item_type_label }}</span>
<span class="item-title" aria-hidden="true">
<span class="spinner"></span>
<span class="menu-item-title<# if ( ! data.title && ! data.original_title ) { #> no-title<# } #>">{{ data.title || data.original_title || wp.customize.Menus.data.l10n.untitled }}</span>
</span>
<span class="item-controls">
<button type="button" class="button-link item-edit" aria-expanded="false"><span class="screen-reader-text">
<?php
/* translators: 1: Title of a menu item, 2: Type of a menu item. */
printf( __( 'Edit menu item: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.item_type_label }}' );
?>
</span><span class="toggle-indicator" aria-hidden="true"></span></button>
<button type="button" class="button-link item-delete submitdelete deletion"><span class="screen-reader-text">
<?php
/* translators: 1: Title of a menu item, 2: Type of a menu item. */
printf( __( 'Remove Menu Item: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.item_type_label }}' );
?>
</span></button>
</span>
</div>
</div>
<div class="menu-item-settings" id="menu-item-settings-{{ data.menu_item_id }}">
<# if ( 'custom' === data.item_type ) { #>
<p class="field-url description description-thin">
<label for="edit-menu-item-url-{{ data.menu_item_id }}">
<?php _e( 'URL' ); ?><br />
<input class="widefat code edit-menu-item-url" type="text" id="edit-menu-item-url-{{ data.menu_item_id }}" name="menu-item-url" />
</label>
</p>
<# } #>
<p class="description description-thin">
<label for="edit-menu-item-title-{{ data.menu_item_id }}">
<?php _e( 'Navigation Label' ); ?><br />
<input type="text" id="edit-menu-item-title-{{ data.menu_item_id }}" placeholder="{{ data.original_title }}" class="widefat edit-menu-item-title" name="menu-item-title" />
</label>
</p>
<p class="field-link-target description description-thin">
<label for="edit-menu-item-target-{{ data.menu_item_id }}">
<input type="checkbox" id="edit-menu-item-target-{{ data.menu_item_id }}" class="edit-menu-item-target" value="_blank" name="menu-item-target" />
<?php _e( 'Open link in a new tab' ); ?>
</label>
</p>
<p class="field-title-attribute field-attr-title description description-thin">
<label for="edit-menu-item-attr-title-{{ data.menu_item_id }}">
<?php _e( 'Title Attribute' ); ?><br />
<input type="text" id="edit-menu-item-attr-title-{{ data.menu_item_id }}" class="widefat edit-menu-item-attr-title" name="menu-item-attr-title" />
</label>
</p>
<p class="field-css-classes description description-thin">
<label for="edit-menu-item-classes-{{ data.menu_item_id }}">
<?php _e( 'CSS Classes' ); ?><br />
<input type="text" id="edit-menu-item-classes-{{ data.menu_item_id }}" class="widefat code edit-menu-item-classes" name="menu-item-classes" />
</label>
</p>
<p class="field-xfn description description-thin">
<label for="edit-menu-item-xfn-{{ data.menu_item_id }}">
<?php _e( 'Link Relationship (XFN)' ); ?><br />
<input type="text" id="edit-menu-item-xfn-{{ data.menu_item_id }}" class="widefat code edit-menu-item-xfn" name="menu-item-xfn" />
</label>
</p>
<p class="field-description description description-thin">
<label for="edit-menu-item-description-{{ data.menu_item_id }}">
<?php _e( 'Description' ); ?><br />
<textarea id="edit-menu-item-description-{{ data.menu_item_id }}" class="widefat edit-menu-item-description" rows="3" cols="20" name="menu-item-description">{{ data.description }}</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 at the end of the form field template for nav menu items in the customizer.
*
* Additional fields can be rendered here and managed in JavaScript.
*
* @since 5.4.0
*/
do_action( 'wp_nav_menu_item_custom_fields_customize_template' );
?>
<div class="menu-item-actions description-thin submitbox">
<# if ( ( 'post_type' === data.item_type || 'taxonomy' === data.item_type ) && '' !== data.original_title ) { #>
<p class="link-to-original">
<?php
/* translators: Nav menu item original title. %s: Original title. */
printf( __( 'Original: %s' ), '<a class="original-link" href="{{ data.url }}">{{ data.original_title }}</a>' );
?>
</p>
<# } #>
<button type="button" class="button-link button-link-delete item-delete submitdelete deletion"><?php _e( 'Remove' ); ?></button>
<span class="spinner"></span>
</div>
<input type="hidden" name="menu-item-db-id[{{ data.menu_item_id }}]" class="menu-item-data-db-id" value="{{ data.menu_item_id }}" />
<input type="hidden" name="menu-item-parent-id[{{ data.menu_item_id }}]" class="menu-item-data-parent-id" value="{{ data.parent }}" />
</div><!-- .menu-item-settings-->
<ul class="menu-item-transport"></ul>
<?php
}
/**
* Return parameters for this control.
*
* @since 4.3.0
*
* @return array Exported parameters.
*/
public function json() {
$exported = parent::json();
$exported['menu_item_id'] = $this->setting->post_id;
return $exported;
}
}
```
| 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 WP_User_Meta_Session_Tokens::drop_sessions() WP\_User\_Meta\_Session\_Tokens::drop\_sessions()
=================================================
Destroys all sessions for all users.
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/)
```
public static function drop_sessions() {
delete_metadata( 'user', 0, 'session_tokens', false, true );
}
```
| Uses | Description |
| --- | --- |
| [delete\_metadata()](../../functions/delete_metadata) wp-includes/meta.php | Deletes metadata for the specified object. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_User_Meta_Session_Tokens::get_session( string $verifier ): array|null WP\_User\_Meta\_Session\_Tokens::get\_session( string $verifier ): array|null
=============================================================================
Retrieves a session based on its verifier (token hash).
`$verifier` string Required Verifier for the session to retrieve. array|null The session, or null if it does not exist
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/)
```
protected function get_session( $verifier ) {
$sessions = $this->get_sessions();
if ( isset( $sessions[ $verifier ] ) ) {
return $sessions[ $verifier ];
}
return null;
}
```
| Uses | Description |
| --- | --- |
| [WP\_User\_Meta\_Session\_Tokens::get\_sessions()](get_sessions) wp-includes/class-wp-user-meta-session-tokens.php | Retrieves all sessions of the user. |
| Used By | Description |
| --- | --- |
| [WP\_User\_Meta\_Session\_Tokens::destroy\_other\_sessions()](destroy_other_sessions) wp-includes/class-wp-user-meta-session-tokens.php | Destroys all sessions for this user, except the single session with the given verifier. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_User_Meta_Session_Tokens::prepare_session( mixed $session ): array WP\_User\_Meta\_Session\_Tokens::prepare\_session( mixed $session ): array
==========================================================================
Converts an expiration to an array of session information.
`$session` mixed Required Session or expiration. array Session.
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/)
```
protected function prepare_session( $session ) {
if ( is_int( $session ) ) {
return array( 'expiration' => $session );
}
return $session;
}
```
wordpress WP_User_Meta_Session_Tokens::destroy_other_sessions( string $verifier ) WP\_User\_Meta\_Session\_Tokens::destroy\_other\_sessions( string $verifier )
=============================================================================
Destroys all sessions for this user, except the single session with the given verifier.
`$verifier` string Required Verifier of the session to keep. 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/)
```
protected function destroy_other_sessions( $verifier ) {
$session = $this->get_session( $verifier );
$this->update_sessions( array( $verifier => $session ) );
}
```
| Uses | Description |
| --- | --- |
| [WP\_User\_Meta\_Session\_Tokens::get\_session()](get_session) wp-includes/class-wp-user-meta-session-tokens.php | Retrieves a session based on its verifier (token hash). |
| [WP\_User\_Meta\_Session\_Tokens::update\_sessions()](update_sessions) wp-includes/class-wp-user-meta-session-tokens.php | Updates the user’s sessions in the usermeta table. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_User_Meta_Session_Tokens::destroy_all_sessions() WP\_User\_Meta\_Session\_Tokens::destroy\_all\_sessions()
=========================================================
Destroys all session tokens for the user.
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/)
```
protected function destroy_all_sessions() {
$this->update_sessions( array() );
}
```
| Uses | Description |
| --- | --- |
| [WP\_User\_Meta\_Session\_Tokens::update\_sessions()](update_sessions) wp-includes/class-wp-user-meta-session-tokens.php | Updates the user’s sessions in the usermeta table. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_User_Meta_Session_Tokens::update_sessions( array $sessions ) WP\_User\_Meta\_Session\_Tokens::update\_sessions( array $sessions )
====================================================================
Updates the user’s sessions in the usermeta table.
`$sessions` array Required Sessions. 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/)
```
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' );
}
}
```
| Uses | Description |
| --- | --- |
| [update\_user\_meta()](../../functions/update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| [delete\_user\_meta()](../../functions/delete_user_meta) wp-includes/user.php | Removes metadata matching criteria from a user. |
| Used By | Description |
| --- | --- |
| [WP\_User\_Meta\_Session\_Tokens::destroy\_all\_sessions()](destroy_all_sessions) wp-includes/class-wp-user-meta-session-tokens.php | Destroys all session tokens for the user. |
| [WP\_User\_Meta\_Session\_Tokens::update\_session()](update_session) wp-includes/class-wp-user-meta-session-tokens.php | Updates a session based on its verifier (token hash). |
| [WP\_User\_Meta\_Session\_Tokens::destroy\_other\_sessions()](destroy_other_sessions) wp-includes/class-wp-user-meta-session-tokens.php | Destroys all sessions for this user, except the single session with the given verifier. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_User_Meta_Session_Tokens::get_sessions(): array WP\_User\_Meta\_Session\_Tokens::get\_sessions(): array
=======================================================
Retrieves all sessions of the user.
array Sessions of the user.
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/)
```
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' ) );
}
```
| Uses | Description |
| --- | --- |
| [get\_user\_meta()](../../functions/get_user_meta) wp-includes/user.php | Retrieves user meta field for a user. |
| Used By | Description |
| --- | --- |
| [WP\_User\_Meta\_Session\_Tokens::get\_session()](get_session) wp-includes/class-wp-user-meta-session-tokens.php | Retrieves a session based on its verifier (token hash). |
| [WP\_User\_Meta\_Session\_Tokens::update\_session()](update_session) wp-includes/class-wp-user-meta-session-tokens.php | Updates a session based on its verifier (token hash). |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_User_Meta_Session_Tokens::update_session( string $verifier, array $session = null ) WP\_User\_Meta\_Session\_Tokens::update\_session( string $verifier, array $session = null )
===========================================================================================
Updates a session based on its verifier (token hash).
`$verifier` string Required Verifier for the session to update. `$session` array Optional Session. Omitting this argument destroys the session. Default: `null`
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/)
```
protected function update_session( $verifier, $session = null ) {
$sessions = $this->get_sessions();
if ( $session ) {
$sessions[ $verifier ] = $session;
} else {
unset( $sessions[ $verifier ] );
}
$this->update_sessions( $sessions );
}
```
| Uses | Description |
| --- | --- |
| [WP\_User\_Meta\_Session\_Tokens::get\_sessions()](get_sessions) wp-includes/class-wp-user-meta-session-tokens.php | Retrieves all sessions of the user. |
| [WP\_User\_Meta\_Session\_Tokens::update\_sessions()](update_sessions) wp-includes/class-wp-user-meta-session-tokens.php | Updates the user’s sessions in the usermeta table. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::get_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Templates\_Controller::get\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
======================================================================================================
Returns the given template
`$request` [WP\_REST\_Request](../wp_rest_request) Required The request instance. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error)
File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [get\_block\_file\_template()](../../functions/get_block_file_template) wp-includes/block-template-utils.php | Retrieves a unified template object based on a theme file. |
| [WP\_REST\_Templates\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepare a single template output for response |
| [get\_block\_template()](../../functions/get_block_template) wp-includes/block-template-utils.php | Retrieves a single unified template object using its id. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::prepare_item_for_response( WP_Block_Template $item, WP_REST_Request $request ): WP_REST_Response WP\_REST\_Templates\_Controller::prepare\_item\_for\_response( WP\_Block\_Template $item, WP\_REST\_Request $request ): WP\_REST\_Response
==========================================================================================================================================
Prepare a single template output for response
`$item` [WP\_Block\_Template](../wp_block_template) Required Template instance. `$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. [WP\_REST\_Response](../wp_rest_response) Response object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/)
```
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;
}
```
[apply\_filters( 'the\_title', string $post\_title, int $post\_id )](../../hooks/the_title)
Filters the post title.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::prepare\_links()](prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepares links for the request. |
| [WP\_REST\_Templates\_Controller::get\_available\_actions()](get_available_actions) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Get the link relations available for the post and current user. |
| [rest\_is\_field\_included()](../../functions/rest_is_field_included) wp-includes/rest-api.php | Given an array of fields to include in a response, some of which may be `nested.fields`, determine whether the provided field should be included in the response body. |
| [block\_version()](../../functions/block_version) wp-includes/blocks.php | Returns the current version of the block format that the content string is using. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::get\_template\_fallback()](get_template_fallback) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Returns the fallback template for the given slug. |
| [WP\_REST\_Templates\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Returns a list of templates. |
| [WP\_REST\_Templates\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Returns the given template |
| [WP\_REST\_Templates\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Updates a single template. |
| [WP\_REST\_Templates\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Creates a single template. |
| [WP\_REST\_Templates\_Controller::delete\_item()](delete_item) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Deletes a single template. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$template` to `$item` to match parent class for PHP 8 named parameter support. |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Templates_Controller::prepare_links( integer $id ): array WP\_REST\_Templates\_Controller::prepare\_links( integer $id ): array
=====================================================================
Prepares links for the request.
`$id` integer Required ID. array Links for the given post.
File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [rest\_get\_route\_for\_post\_type\_items()](../../functions/rest_get_route_for_post_type_items) wp-includes/rest-api.php | Gets the REST API route for a post type. |
| [rest\_get\_route\_for\_post()](../../functions/rest_get_route_for_post) wp-includes/rest-api.php | Gets the REST API route for a post. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepare a single template output for response |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::get_items( WP_REST_Request $request ): WP_REST_Response WP\_REST\_Templates\_Controller::get\_items( WP\_REST\_Request $request ): WP\_REST\_Response
=============================================================================================
Returns a list of templates.
`$request` [WP\_REST\_Request](../wp_rest_request) Required The request instance. [WP\_REST\_Response](../wp_rest_response)
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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepare a single template output for response |
| [get\_block\_templates()](../../functions/get_block_templates) wp-includes/block-template-utils.php | Retrieves a list of unified template objects based on a query. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::_sanitize_template_id( string $id ): string WP\_REST\_Templates\_Controller::\_sanitize\_template\_id( string $id ): string
===============================================================================
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.
* <https://core.trac.wordpress.org/ticket/54507>
`$id` string Required Template ID. string Sanitized template ID.
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/)
```
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 )
);
}
```
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::create_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Templates\_Controller::create\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=========================================================================================================
Creates a single template.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/)
```
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;
}
```
[do\_action( "rest\_after\_insert\_{$this->post\_type}", WP\_Post $post, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_after_insert_this-post_type)
Fires after a single post is completely created or updated via the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepare a single template output for response |
| [WP\_REST\_Templates\_Controller::prepare\_item\_for\_database()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepares a single template for create or update. |
| [get\_block\_templates()](../../functions/get_block_templates) wp-includes/block-template-utils.php | Retrieves a list of unified template objects based on a query. |
| [get\_block\_template()](../../functions/get_block_template) wp-includes/block-template-utils.php | Retrieves a single unified template object using its id. |
| [wp\_after\_insert\_post()](../../functions/wp_after_insert_post) wp-includes/post.php | Fires actions after a post, its terms and meta data has been saved. |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::get_template_fallback( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Templates\_Controller::get\_template\_fallback( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
====================================================================================================================
Returns the fallback template for the given slug.
`$request` [WP\_REST\_Request](../wp_rest_request) Required The request instance. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error)
File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [get\_template\_hierarchy()](../../functions/get_template_hierarchy) wp-includes/block-template-utils.php | Gets the template hierarchy for the given template slug to be created. |
| [WP\_REST\_Templates\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepare a single template output for response |
| [resolve\_block\_template()](../../functions/resolve_block_template) wp-includes/block-template.php | Returns the correct ‘wp\_template’ to render for the request template type. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::update_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Templates\_Controller::update\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=========================================================================================================
Updates a single template.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/)
```
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 );
}
```
[do\_action( "rest\_after\_insert\_{$this->post\_type}", WP\_Post $post, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_after_insert_this-post_type)
Fires after a single post is completely created or updated via the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepare a single template output for response |
| [WP\_REST\_Templates\_Controller::prepare\_item\_for\_database()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepares a single template for create or update. |
| [get\_block\_template()](../../functions/get_block_template) wp-includes/block-template-utils.php | Retrieves a single unified template object using its id. |
| [wp\_after\_insert\_post()](../../functions/wp_after_insert_post) wp-includes/post.php | Fires actions after a post, its terms and meta data has been saved. |
| [wp\_update\_post()](../../functions/wp_update_post) wp-includes/post.php | Updates a post with new post data. |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::delete_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Templates\_Controller::delete\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
===============================================================================================================
Checks if a given request has access to delete a single template.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has delete access for the item, [WP\_Error](../wp_error) object otherwise.
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/)
```
public function delete_item_permissions_check( $request ) {
return $this->permissions_check( $request );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::permissions\_check()](permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Checks if the user has permissions to make the request. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::prepare_item_for_database( WP_REST_Request $request ): stdClass WP\_REST\_Templates\_Controller::prepare\_item\_for\_database( WP\_REST\_Request $request ): stdClass
=====================================================================================================
Prepares a single template for create or update.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. stdClass Changes to pass to wp\_update\_post.
File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [\_filter\_block\_template\_part\_area()](../../functions/_filter_block_template_part_area) wp-includes/block-template-utils.php | Checks whether the input ‘area’ is a supported value. |
| [get\_block\_template()](../../functions/get_block_template) wp-includes/block-template-utils.php | Retrieves a single unified template object using its id. |
| [WP\_Theme::get\_stylesheet()](../wp_theme/get_stylesheet) wp-includes/class-wp-theme.php | Returns the directory name of the theme’s “stylesheet” files, inside the theme root. |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_userdata()](../../functions/get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Updates a single template. |
| [WP\_REST\_Templates\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Creates a single template. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Templates_Controller::get_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Templates\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=============================================================================================================
Checks if a given request has access to read templates.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/)
```
public function get_items_permissions_check( $request ) {
return $this->permissions_check( $request );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::permissions\_check()](permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Checks if the user has permissions to make the request. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::update_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Templates\_Controller::update\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
===============================================================================================================
Checks if a given request has access to write a single template.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has write access for the item, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/)
```
public function update_item_permissions_check( $request ) {
return $this->permissions_check( $request );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::permissions\_check()](permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Checks if the user has permissions to make the request. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::register_routes() WP\_REST\_Templates\_Controller::register\_routes()
===================================================
Registers the controllers routes.
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/)
```
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' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Retrieves the query params for the posts collection. |
| [register\_rest\_route()](../../functions/register_rest_route) wp-includes/rest-api.php | Registers a REST API route. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Endpoint for fallback template content. |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::get_collection_params(): array WP\_REST\_Templates\_Controller::get\_collection\_params(): array
=================================================================
Retrieves the query params for the posts collection.
array Collection parameters.
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/)
```
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',
),
);
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::register\_routes()](register_routes) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Registers the controllers routes. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Added `'area'` and `'post_type'`. |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::__construct( string $post_type ) WP\_REST\_Templates\_Controller::\_\_construct( string $post\_type )
====================================================================
Constructor.
`$post_type` string Required Post type. 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/)
```
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';
}
```
| Uses | Description |
| --- | --- |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::get_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Templates\_Controller::get\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
============================================================================================================
Checks if a given request has access to read a single template.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access for the item, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/)
```
public function get_item_permissions_check( $request ) {
return $this->permissions_check( $request );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::permissions\_check()](permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Checks if the user has permissions to make the request. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Templates\_Controller::permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=================================================================================================
Checks if the user has permissions to make the request.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::get\_items\_permissions\_check()](get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Checks if a given request has access to read templates. |
| [WP\_REST\_Templates\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Checks if a given request has access to read a single template. |
| [WP\_REST\_Templates\_Controller::update\_item\_permissions\_check()](update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Checks if a given request has access to write a single template. |
| [WP\_REST\_Templates\_Controller::create\_item\_permissions\_check()](create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Checks if a given request has access to create a template. |
| [WP\_REST\_Templates\_Controller::delete\_item\_permissions\_check()](delete_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Checks if a given request has access to delete a single template. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::create_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Templates\_Controller::create\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
===============================================================================================================
Checks if a given request has access to create a template.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has access to create items, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/)
```
public function create_item_permissions_check( $request ) {
return $this->permissions_check( $request );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::permissions\_check()](permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Checks if the user has permissions to make the request. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::delete_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Templates\_Controller::delete\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=========================================================================================================
Deletes a single template.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepare a single template output for response |
| [get\_block\_template()](../../functions/get_block_template) wp-includes/block-template-utils.php | Retrieves a single unified template object using its id. |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [wp\_trash\_post()](../../functions/wp_trash_post) wp-includes/post.php | Moves a post or page to the Trash |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_REST_Templates_Controller::get_item_schema(): array WP\_REST\_Templates\_Controller::get\_item\_schema(): array
===========================================================
Retrieves the block type’ schema, conforming to JSON Schema.
array Item schema data.
File: `wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php/)
```
public function get_item_schema() {
if ( $this->schema ) {
return $this->add_additional_fields_schema( $this->schema );
}
$schema = array(
'$schema' => 'http://json-schema.org/draft-04/schema#',
'title' => $this->post_type,
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'ID of 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 |
| --- | --- |
| [get\_post\_stati()](../../functions/get_post_stati) wp-includes/post.php | Gets a list of post statuses. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Added `'area'`. |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Templates_Controller::get_available_actions(): string[] WP\_REST\_Templates\_Controller::get\_available\_actions(): string[]
====================================================================
Get the link relations available for the post and current user.
string[] List of link relations.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Templates\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepare a single template output for response |
| Version | Description |
| --- | --- |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Introduced. |
wordpress WP_Sitemaps_Users::get_max_num_pages( string $object_subtype = '' ): int WP\_Sitemaps\_Users::get\_max\_num\_pages( string $object\_subtype = '' ): int
==============================================================================
Gets the max number of pages available for the object type.
* [WP\_Sitemaps\_Provider::max\_num\_pages](../wp_sitemaps_provider/max_num_pages)
`$object_subtype` string Optional Not applicable for Users but required for compatibility with the parent provider class. Default: `''`
int Total page count.
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/)
```
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 ) );
}
```
[apply\_filters( 'wp\_sitemaps\_users\_pre\_max\_num\_pages', int|null $max\_num\_pages )](../../hooks/wp_sitemaps_users_pre_max_num_pages)
Filters the max number of pages for a user sitemap before it is generated.
| Uses | Description |
| --- | --- |
| [wp\_sitemaps\_get\_max\_urls()](../../functions/wp_sitemaps_get_max_urls) wp-includes/sitemaps.php | Gets the maximum number of URLs for a sitemap. |
| [WP\_Sitemaps\_Users::get\_users\_query\_args()](get_users_query_args) wp-includes/sitemaps/providers/class-wp-sitemaps-users.php | Returns the query args for retrieving users to list in the sitemap. |
| [WP\_User\_Query::\_\_construct()](../wp_user_query/__construct) wp-includes/class-wp-user-query.php | PHP5 constructor. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps_Users::get_users_query_args(): array WP\_Sitemaps\_Users::get\_users\_query\_args(): array
=====================================================
Returns the query args for retrieving users to list in the sitemap.
array Array of [WP\_User\_Query](../wp_user_query) arguments.
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/)
```
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;
}
```
[apply\_filters( 'wp\_sitemaps\_users\_query\_args', array $args )](../../hooks/wp_sitemaps_users_query_args)
Filters the query arguments for authors with public posts.
| Uses | Description |
| --- | --- |
| [wp\_sitemaps\_get\_max\_urls()](../../functions/wp_sitemaps_get_max_urls) wp-includes/sitemaps.php | Gets the maximum number of URLs for a sitemap. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| Used By | Description |
| --- | --- |
| [WP\_Sitemaps\_Users::get\_url\_list()](get_url_list) wp-includes/sitemaps/providers/class-wp-sitemaps-users.php | Gets a URL list for a user sitemap. |
| [WP\_Sitemaps\_Users::get\_max\_num\_pages()](get_max_num_pages) wp-includes/sitemaps/providers/class-wp-sitemaps-users.php | Gets the max number of pages available for the object type. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps_Users::__construct() WP\_Sitemaps\_Users::\_\_construct()
====================================
[WP\_Sitemaps\_Users](../wp_sitemaps_users) constructor.
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/)
```
public function __construct() {
$this->name = 'users';
$this->object_type = 'user';
}
```
| Used By | Description |
| --- | --- |
| [WP\_Sitemaps::register\_sitemaps()](../wp_sitemaps/register_sitemaps) wp-includes/sitemaps/class-wp-sitemaps.php | Registers and sets up the functionality for all supported sitemaps. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps_Users::get_url_list( int $page_num, string $object_subtype = '' ): array[] WP\_Sitemaps\_Users::get\_url\_list( int $page\_num, string $object\_subtype = '' ): array[]
============================================================================================
Gets a URL list for a user sitemap.
`$page_num` int Required Page of results. `$object_subtype` string Optional Not applicable for Users but required for compatibility with the parent provider class. Default: `''`
array[] Array of URL information for a 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/)
```
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;
}
```
[apply\_filters( 'wp\_sitemaps\_users\_entry', array $sitemap\_entry, WP\_User $user )](../../hooks/wp_sitemaps_users_entry)
Filters the sitemap entry for an individual user.
[apply\_filters( 'wp\_sitemaps\_users\_pre\_url\_list', array[]|null $url\_list, int $page\_num )](../../hooks/wp_sitemaps_users_pre_url_list)
Filters the users URL list before it is generated.
| Uses | Description |
| --- | --- |
| [WP\_Sitemaps\_Users::get\_users\_query\_args()](get_users_query_args) wp-includes/sitemaps/providers/class-wp-sitemaps-users.php | Returns the query args for retrieving users to list in the sitemap. |
| [WP\_User\_Query::\_\_construct()](../wp_user_query/__construct) wp-includes/class-wp-user-query.php | PHP5 constructor. |
| [get\_author\_posts\_url()](../../functions/get_author_posts_url) wp-includes/author-template.php | Retrieves the URL to the author page for the user with the ID provided. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_User::remove_cap( string $cap ) WP\_User::remove\_cap( string $cap )
====================================
Removes capability from user.
`$cap` string Required Capability name. Changing the capabilities of a user is persistent, meaning the removed capability will stay in effect until explicitly granted.
This setting is saved to the database (in table wp\_options, field 'wp\_user\_roles'), so you should run this only once, on theme/plugin activation and/or deactivation.
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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();
}
```
| Uses | Description |
| --- | --- |
| [WP\_User::update\_user\_level\_from\_caps()](update_user_level_from_caps) wp-includes/class-wp-user.php | Updates the maximum user level for the user. |
| [WP\_User::get\_role\_caps()](get_role_caps) wp-includes/class-wp-user.php | Retrieves all of the capabilities of the user’s roles, and merges them with individual user capabilities. |
| [update\_user\_meta()](../../functions/update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_User::translate_level_to_cap( int $level ): string WP\_User::translate\_level\_to\_cap( int $level ): string
=========================================================
Converts numeric level to level capability name.
Prepends ‘level\_’ to level number.
`$level` int Required Level number, 1 to 10. string
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
public function translate_level_to_cap( $level ) {
return 'level_' . $level;
}
```
| Used By | Description |
| --- | --- |
| [WP\_User::has\_cap()](has_cap) wp-includes/class-wp-user.php | Returns whether the user has the specified capability. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_User::to_array(): array WP\_User::to\_array(): array
============================
Returns an array representation.
array Array representation.
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
public function to_array() {
return get_object_vars( $this->data );
}
```
| Version | Description |
| --- | --- |
| [3.5.0](https://developer.wordpress.org/reference/since/3.5.0/) | Introduced. |
wordpress WP_User::exists(): bool WP\_User::exists(): bool
========================
Determines whether the user exists in the database.
bool True if user exists in the database, false if not.
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
public function exists() {
return ! empty( $this->ID );
}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_User::for_blog( int $blog_id = '' ) WP\_User::for\_blog( int $blog\_id = '' )
=========================================
This method has been deprecated. Use [WP\_User::for\_site()](for_site) instead.
Sets the site to operate on. Defaults to the current site.
`$blog_id` int Optional Site ID, defaults to current site. Default: `''`
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
public function for_blog( $blog_id = '' ) {
_deprecated_function( __METHOD__, '4.9.0', 'WP_User::for_site()' );
$this->for_site( $blog_id );
}
```
| Uses | Description |
| --- | --- |
| [WP\_User::for\_site()](for_site) wp-includes/class-wp-user.php | Sets the site to operate on. Defaults to the current site. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Use [WP\_User::for\_site()](for_site) |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress WP_User::init( object $data, int $site_id = '' ) WP\_User::init( object $data, int $site\_id = '' )
==================================================
Sets up object properties, including capabilities.
`$data` object Required User DB row object. `$site_id` int Optional The site ID to initialize for. Default: `''`
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_User::for\_site()](for_site) wp-includes/class-wp-user.php | Sets the site to operate on. Defaults to the current site. |
| Used By | Description |
| --- | --- |
| [WP\_User::\_\_construct()](__construct) wp-includes/class-wp-user.php | Constructor. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_User::update_user_level_from_caps() WP\_User::update\_user\_level\_from\_caps()
===========================================
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.
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [update\_user\_meta()](../../functions/update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| [wpdb::get\_blog\_prefix()](../wpdb/get_blog_prefix) wp-includes/class-wpdb.php | Gets blog prefix. |
| Used By | Description |
| --- | --- |
| [WP\_User::add\_cap()](add_cap) wp-includes/class-wp-user.php | Adds capability and grant or deny access to capability. |
| [WP\_User::remove\_cap()](remove_cap) wp-includes/class-wp-user.php | Removes capability from user. |
| [WP\_User::add\_role()](add_role) wp-includes/class-wp-user.php | Adds role to user. |
| [WP\_User::remove\_role()](remove_role) wp-includes/class-wp-user.php | Removes role from user. |
| [WP\_User::set\_role()](set_role) wp-includes/class-wp-user.php | Sets the role of the user. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_User::add_role( string $role ) WP\_User::add\_role( string $role )
===================================
Adds role to user.
Updates the user’s meta data option with capabilities and roles.
`$role` string Required Role name. File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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 );
}
```
[do\_action( 'add\_user\_role', int $user\_id, string $role )](../../hooks/add_user_role)
Fires immediately after the user has been given a new role.
| Uses | Description |
| --- | --- |
| [WP\_User::update\_user\_level\_from\_caps()](update_user_level_from_caps) wp-includes/class-wp-user.php | Updates the maximum user level for the user. |
| [WP\_User::get\_role\_caps()](get_role_caps) wp-includes/class-wp-user.php | Retrieves all of the capabilities of the user’s roles, and merges them with individual user capabilities. |
| [update\_user\_meta()](../../functions/update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
| programming_docs |
wordpress WP_User::__unset( string $key ) WP\_User::\_\_unset( string $key )
==================================
Magic method for unsetting a certain custom field.
`$key` string Required User meta key to unset. File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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 ] );
}
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_deprecated\_argument()](../../functions/_deprecated_argument) wp-includes/functions.php | Marks a function argument as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_User::has_prop( string $key ): bool WP\_User::has\_prop( string $key ): bool
========================================
Determines whether a property or meta key is set.
Consults the users and usermeta tables.
`$key` string Required Property. bool
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
public function has_prop( $key ) {
return $this->__isset( $key );
}
```
| Uses | Description |
| --- | --- |
| [WP\_User::\_\_isset()](__isset) wp-includes/class-wp-user.php | Magic method for checking the existence of a certain custom field. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_User::get_caps_data(): bool[] WP\_User::get\_caps\_data(): bool[]
===================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Gets the available user capabilities data.
bool[] List of capabilities keyed by the capability name, e.g. array( `'edit_posts'` => true, `'delete_posts'` => false ).
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
private function get_caps_data() {
$caps = get_user_meta( $this->ID, $this->cap_key, true );
if ( ! is_array( $caps ) ) {
return array();
}
return $caps;
}
```
| Uses | Description |
| --- | --- |
| [get\_user\_meta()](../../functions/get_user_meta) wp-includes/user.php | Retrieves user meta field for a user. |
| Used By | Description |
| --- | --- |
| [WP\_User::for\_site()](for_site) wp-includes/class-wp-user.php | Sets the site to operate on. Defaults to the current site. |
| [WP\_User::\_init\_caps()](_init_caps) wp-includes/class-wp-user.php | Sets up capability object properties. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_User::get_role_caps(): bool[] WP\_User::get\_role\_caps(): bool[]
===================================
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.
bool[] Array of key/value pairs where keys represent a capability name and boolean values represent whether the user has that capability.
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [wp\_roles()](../../functions/wp_roles) wp-includes/capabilities.php | Retrieves the global [WP\_Roles](../wp_roles) instance and instantiates it if necessary. |
| [WP\_Roles::get\_role()](../wp_roles/get_role) wp-includes/class-wp-roles.php | Retrieves a role object by name. |
| [switch\_to\_blog()](../../functions/switch_to_blog) wp-includes/ms-blogs.php | Switch the current blog. |
| [restore\_current\_blog()](../../functions/restore_current_blog) wp-includes/ms-blogs.php | Restore the current blog, after calling [switch\_to\_blog()](../../functions/switch_to_blog) . |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [get\_current\_blog\_id()](../../functions/get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| Used By | Description |
| --- | --- |
| [WP\_User::for\_site()](for_site) wp-includes/class-wp-user.php | Sets the site to operate on. Defaults to the current site. |
| [WP\_User::add\_cap()](add_cap) wp-includes/class-wp-user.php | Adds capability and grant or deny access to capability. |
| [WP\_User::remove\_cap()](remove_cap) wp-includes/class-wp-user.php | Removes capability from user. |
| [WP\_User::remove\_all\_caps()](remove_all_caps) wp-includes/class-wp-user.php | Removes all of the capabilities of the user. |
| [WP\_User::\_init\_caps()](_init_caps) wp-includes/class-wp-user.php | Sets up capability object properties. |
| [WP\_User::add\_role()](add_role) wp-includes/class-wp-user.php | Adds role to user. |
| [WP\_User::remove\_role()](remove_role) wp-includes/class-wp-user.php | Removes role from user. |
| [WP\_User::set\_role()](set_role) wp-includes/class-wp-user.php | Sets the role of the user. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_User::add_cap( string $cap, bool $grant = true ) WP\_User::add\_cap( string $cap, bool $grant = true )
=====================================================
Adds capability and grant or deny access to capability.
`$cap` string Required Capability name. `$grant` bool Optional Whether to grant capability to user. Default: `true`
Changing the capabilities of a user is persistent, meaning the added capability will stay in effect until explicitly revoked.
This setting is saved to the database (in table wp\_options, field wp\_user\_roles), so it might be better to run this on theme/plugin activation.
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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();
}
```
| Uses | Description |
| --- | --- |
| [WP\_User::update\_user\_level\_from\_caps()](update_user_level_from_caps) wp-includes/class-wp-user.php | Updates the maximum user level for the user. |
| [WP\_User::get\_role\_caps()](get_role_caps) wp-includes/class-wp-user.php | Retrieves all of the capabilities of the user’s roles, and merges them with individual user capabilities. |
| [update\_user\_meta()](../../functions/update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_User::remove_role( string $role ) WP\_User::remove\_role( string $role )
======================================
Removes role from user.
`$role` string Required Role name. File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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 );
}
```
[do\_action( 'remove\_user\_role', int $user\_id, string $role )](../../hooks/remove_user_role)
Fires immediately after a role as been removed from a user.
| Uses | Description |
| --- | --- |
| [WP\_User::update\_user\_level\_from\_caps()](update_user_level_from_caps) wp-includes/class-wp-user.php | Updates the maximum user level for the user. |
| [WP\_User::get\_role\_caps()](get_role_caps) wp-includes/class-wp-user.php | Retrieves all of the capabilities of the user’s roles, and merges them with individual user capabilities. |
| [update\_user\_meta()](../../functions/update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_User::__call( string $name, array $arguments ): mixed|false WP\_User::\_\_call( string $name, array $arguments ): mixed|false
=================================================================
Makes private/protected methods readable for backward compatibility.
`$name` string Required Method to call. `$arguments` array Required Arguments to pass when calling. mixed|false Return value of the callback, false otherwise.
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
public function __call( $name, $arguments ) {
if ( '_init_caps' === $name ) {
return $this->_init_caps( ...$arguments );
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [WP\_User::\_init\_caps()](_init_caps) wp-includes/class-wp-user.php | Sets up capability object properties. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_User::__set( string $key, mixed $value ) WP\_User::\_\_set( string $key, mixed $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](../wp_user) instance.
`$key` string Required User meta key. `$value` mixed Required User meta value. File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_deprecated\_argument()](../../functions/_deprecated_argument) wp-includes/functions.php | Marks a function argument as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_User::remove_all_caps() WP\_User::remove\_all\_caps()
=============================
Removes all of the capabilities of the user.
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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();
}
```
| Uses | Description |
| --- | --- |
| [WP\_User::get\_role\_caps()](get_role_caps) wp-includes/class-wp-user.php | Retrieves all of the capabilities of the user’s roles, and merges them with individual user capabilities. |
| [delete\_user\_meta()](../../functions/delete_user_meta) wp-includes/user.php | Removes metadata matching criteria from a user. |
| [wpdb::get\_blog\_prefix()](../wpdb/get_blog_prefix) wp-includes/class-wpdb.php | Gets blog prefix. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_User::get_site_id(): int WP\_User::get\_site\_id(): int
==============================
Gets the ID of the site for which the user’s capabilities are currently initialized.
int Site ID.
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
public function get_site_id() {
return $this->site_id;
}
```
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_User::__get( string $key ): mixed WP\_User::\_\_get( string $key ): mixed
=======================================
Magic method for accessing custom fields.
`$key` string Required User meta key to retrieve. mixed Value of the given user meta key (if set). If `$key` is `'id'`, the user ID.
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [get\_user\_meta()](../../functions/get_user_meta) wp-includes/user.php | Retrieves user meta field for a user. |
| [sanitize\_user\_field()](../../functions/sanitize_user_field) wp-includes/user.php | Sanitizes user field based on context. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_deprecated\_argument()](../../functions/_deprecated_argument) wp-includes/functions.php | Marks a function argument as deprecated and inform when it has been used. |
| Used By | Description |
| --- | --- |
| [WP\_User::get()](get) wp-includes/class-wp-user.php | Retrieves the value of a property or meta key. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_User::_init_caps( string $cap_key = '' ) WP\_User::\_init\_caps( string $cap\_key = '' )
===============================================
This method has been deprecated. Use [WP\_User::for\_site()](for_site) instead.
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.
`$cap_key` string Optional capability key Default: `''`
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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();
}
```
| Uses | Description |
| --- | --- |
| [WP\_User::get\_caps\_data()](get_caps_data) wp-includes/class-wp-user.php | Gets the available user capabilities data. |
| [WP\_User::get\_role\_caps()](get_role_caps) wp-includes/class-wp-user.php | Retrieves all of the capabilities of the user’s roles, and merges them with individual user capabilities. |
| [wpdb::get\_blog\_prefix()](../wpdb/get_blog_prefix) wp-includes/class-wpdb.php | Gets blog prefix. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Used By | Description |
| --- | --- |
| [WP\_User::\_\_call()](__call) wp-includes/class-wp-user.php | Makes private/protected methods readable for backward compatibility. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Use [WP\_User::for\_site()](for_site) |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_User::has_cap( string $cap, mixed $args ): bool WP\_User::has\_cap( string $cap, mixed $args ): bool
====================================================
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.
* [map\_meta\_cap()](../../functions/map_meta_cap)
`$cap` string Required Capability name. `$args` mixed Optional further parameters, typically starting with an object ID. 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.
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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;
}
```
[apply\_filters( 'user\_has\_cap', bool[] $allcaps, string[] $caps, array $args, WP\_User $user )](../../hooks/user_has_cap)
Dynamically filter a user’s capabilities.
| Uses | Description |
| --- | --- |
| [WP\_User::translate\_level\_to\_cap()](translate_level_to_cap) wp-includes/class-wp-user.php | Converts numeric level to level capability name. |
| [is\_super\_admin()](../../functions/is_super_admin) wp-includes/capabilities.php | Determines whether user is a site admin. |
| [map\_meta\_cap()](../../functions/map_meta_cap) wp-includes/capabilities.php | Maps a capability to the primitive capabilities required of the given user to satisfy the capability being checked. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [\_deprecated\_argument()](../../functions/_deprecated_argument) wp-includes/functions.php | Marks a function argument as deprecated and inform when it has been used. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Formalized the existing and already documented `...$args` parameter by adding it to the function signature. |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
| programming_docs |
wordpress WP_User::__isset( string $key ): bool WP\_User::\_\_isset( string $key ): bool
========================================
Magic method for checking the existence of a certain custom field.
`$key` string Required User meta key to check if set. bool Whether the given user meta key is set.
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [metadata\_exists()](../../functions/metadata_exists) wp-includes/meta.php | Determines if a meta field with the given key exists for the given object ID. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_deprecated\_argument()](../../functions/_deprecated_argument) wp-includes/functions.php | Marks a function argument as deprecated and inform when it has been used. |
| Used By | Description |
| --- | --- |
| [WP\_User::has\_prop()](has_prop) wp-includes/class-wp-user.php | Determines whether a property or meta key is set. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_User::get_data_by( string $field, string|int $value ): object|false WP\_User::get\_data\_by( string $field, string|int $value ): object|false
=========================================================================
Returns only the main user fields.
`$field` string Required The field to query against: `'id'`, `'ID'`, `'slug'`, `'email'` or `'login'`. `$value` string|int Required The field value. object|false Raw user object.
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [update\_user\_caches()](../../functions/update_user_caches) wp-includes/user.php | Updates all user caches. |
| [sanitize\_user()](../../functions/sanitize_user) wp-includes/formatting.php | Sanitizes a username, stripping out unsafe characters. |
| [wpdb::get\_row()](../wpdb/get_row) wp-includes/class-wpdb.php | Retrieves one row from the database. |
| [wp\_cache\_get()](../../functions/wp_cache_get) wp-includes/cache.php | Retrieves the cache contents from the cache by key and group. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_User::\_\_construct()](__construct) wp-includes/class-wp-user.php | Constructor. |
| [get\_user\_by()](../../functions/get_user_by) wp-includes/pluggable.php | Retrieves user info by a given field. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Added `'ID'` as an alias of `'id'` for the `$field` parameter. |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_User::__construct( int|string|stdClass|WP_User $id, string $name = '', int $site_id = '' ) WP\_User::\_\_construct( int|string|stdClass|WP\_User $id, string $name = '', int $site\_id = '' )
==================================================================================================
Constructor.
Retrieves the userdata and passes it to [WP\_User::init()](init).
`$id` int|string|stdClass|[WP\_User](../wp_user) Required User's ID, a [WP\_User](../wp_user) object, or a user object from the DB. `$name` string Optional User's username Default: `''`
`$site_id` int Optional Site ID, defaults to current site. Default: `''`
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_User::get\_data\_by()](get_data_by) wp-includes/class-wp-user.php | Returns only the main user fields. |
| [WP\_User::init()](init) wp-includes/class-wp-user.php | Sets up object properties, including capabilities. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Comments\_Controller::prepare\_item\_for\_database()](../wp_rest_comments_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Prepares a single comment to be inserted into the database. |
| [wpmu\_delete\_user()](../../functions/wpmu_delete_user) wp-admin/includes/ms.php | Delete a user from the network and remove from all sites. |
| [update\_user\_status()](../../functions/update_user_status) wp-includes/ms-deprecated.php | Update the status of a user in the database. |
| [wp\_install()](../../functions/wp_install) wp-admin/includes/upgrade.php | Installs the site. |
| [wp\_install\_defaults()](../../functions/wp_install_defaults) wp-admin/includes/upgrade.php | Creates the initial content for a newly-installed site. |
| [wp\_new\_blog\_notification()](../../functions/wp_new_blog_notification) wp-admin/includes/upgrade.php | Notifies the site admin that the installation of WordPress is complete. |
| [wp\_revoke\_user()](../../functions/wp_revoke_user) wp-admin/includes/user.php | Remove all capabilities from user. |
| [wp\_delete\_user()](../../functions/wp_delete_user) wp-admin/includes/user.php | Remove user and optionally reassign posts and links to another user. |
| [attachment\_submitbox\_metadata()](../../functions/attachment_submitbox_metadata) wp-admin/includes/media.php | Displays non-editable attachment metadata in the publish meta box. |
| [user\_can()](../../functions/user_can) wp-includes/capabilities.php | Returns whether a particular user has the specified capability. |
| [wp\_set\_current\_user()](../../functions/wp_set_current_user) wp-includes/pluggable.php | Changes the current user by ID or name. |
| [get\_user\_by()](../../functions/get_user_by) wp-includes/pluggable.php | Retrieves user info by a given field. |
| [WP\_User\_Query::query()](../wp_user_query/query) wp-includes/class-wp-user-query.php | Executes the query, with the current variables. |
| [clean\_user\_cache()](../../functions/clean_user_cache) wp-includes/user.php | Cleans all user caches. |
| [wp\_insert\_user()](../../functions/wp_insert_user) wp-includes/user.php | Inserts a user into the database. |
| [wp\_authenticate\_cookie()](../../functions/wp_authenticate_cookie) wp-includes/user.php | Authenticates the user using the WordPress auth cookie. |
| [wp\_prepare\_attachment\_for\_js()](../../functions/wp_prepare_attachment_for_js) wp-includes/media.php | Prepares an attachment post object for JS, where it is expected to be JSON-encoded and fit into an Attachment model. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_User::level_reduction( int $max, string $item ): int WP\_User::level\_reduction( int $max, string $item ): int
=========================================================
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.
`$max` int Required Max level of user. `$item` string Required Level capability name. int Max Level.
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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;
}
}
```
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress WP_User::for_site( int $site_id = '' ) WP\_User::for\_site( int $site\_id = '' )
=========================================
Sets the site to operate on. Defaults to the current site.
`$site_id` int Optional Site ID to initialize user capabilities for. Default is the current site. Default: `''`
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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();
}
```
| Uses | Description |
| --- | --- |
| [WP\_User::get\_caps\_data()](get_caps_data) wp-includes/class-wp-user.php | Gets the available user capabilities data. |
| [WP\_User::get\_role\_caps()](get_role_caps) wp-includes/class-wp-user.php | Retrieves all of the capabilities of the user’s roles, and merges them with individual user capabilities. |
| [wpdb::get\_blog\_prefix()](../wpdb/get_blog_prefix) wp-includes/class-wpdb.php | Gets blog prefix. |
| [get\_current\_blog\_id()](../../functions/get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Used By | Description |
| --- | --- |
| [WP\_User::for\_blog()](for_blog) wp-includes/class-wp-user.php | Sets the site to operate on. Defaults to the current site. |
| [WP\_User::init()](init) wp-includes/class-wp-user.php | Sets up object properties, including capabilities. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_User::get( string $key ): mixed WP\_User::get( string $key ): mixed
===================================
Retrieves the value of a property or meta key.
Retrieves from the users and usermeta table.
`$key` string Required Property mixed
File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
public function get( $key ) {
return $this->__get( $key );
}
```
| Uses | Description |
| --- | --- |
| [WP\_User::\_\_get()](__get) wp-includes/class-wp-user.php | Magic method for accessing custom fields. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
wordpress WP_User::set_role( string $role ) WP\_User::set\_role( string $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.
`$role` string Required Role name. File: `wp-includes/class-wp-user.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-user.php/)
```
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 );
}
```
[do\_action( 'add\_user\_role', int $user\_id, string $role )](../../hooks/add_user_role)
Fires immediately after the user has been given a new role.
[do\_action( 'remove\_user\_role', int $user\_id, string $role )](../../hooks/remove_user_role)
Fires immediately after a role as been removed from a user.
[do\_action( 'set\_user\_role', int $user\_id, string $role, string[] $old\_roles )](../../hooks/set_user_role)
Fires after the user’s role has changed.
| Uses | Description |
| --- | --- |
| [WP\_User::update\_user\_level\_from\_caps()](update_user_level_from_caps) wp-includes/class-wp-user.php | Updates the maximum user level for the user. |
| [WP\_User::get\_role\_caps()](get_role_caps) wp-includes/class-wp-user.php | Retrieves all of the capabilities of the user’s roles, and merges them with individual user capabilities. |
| [update\_user\_meta()](../../functions/update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [2.0.0](https://developer.wordpress.org/reference/since/2.0.0/) | Introduced. |
wordpress IXR_Client::getErrorCode() IXR\_Client::getErrorCode()
===========================
File: `wp-includes/IXR/class-IXR-client.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-client.php/)
```
function getErrorCode()
{
return $this->error->code;
}
```
wordpress IXR_Client::isError() IXR\_Client::isError()
======================
File: `wp-includes/IXR/class-IXR-client.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-client.php/)
```
function isError()
{
return (is_object($this->error));
}
```
wordpress IXR_Client::IXR_Client( $server, $path = false, $port = 80, $timeout = 15 ) IXR\_Client::IXR\_Client( $server, $path = false, $port = 80, $timeout = 15 )
=============================================================================
PHP4 constructor.
File: `wp-includes/IXR/class-IXR-client.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-client.php/)
```
public function IXR_Client( $server, $path = false, $port = 80, $timeout = 15 ) {
self::__construct( $server, $path, $port, $timeout );
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Client::\_\_construct()](__construct) wp-includes/IXR/class-IXR-client.php | PHP5 constructor. |
| Used By | Description |
| --- | --- |
| [IXR\_ClientMulticall::\_\_construct()](../ixr_clientmulticall/__construct) wp-includes/IXR/class-IXR-clientmulticall.php | PHP5 constructor. |
wordpress IXR_Client::getResponse() IXR\_Client::getResponse()
==========================
File: `wp-includes/IXR/class-IXR-client.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-client.php/)
```
function getResponse()
{
// methodResponses can only have one param - return that
return $this->message->params[0];
}
```
wordpress IXR_Client::query( $args ): bool IXR\_Client::query( $args ): bool
=================================
bool
File: `wp-includes/IXR/class-IXR-client.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-client.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Message::\_\_construct()](../ixr_message/__construct) wp-includes/IXR/class-IXR-message.php | PHP5 constructor. |
| [IXR\_Request::\_\_construct()](../ixr_request/__construct) wp-includes/IXR/class-IXR-request.php | PHP5 constructor. |
| [IXR\_Error::\_\_construct()](../ixr_error/__construct) wp-includes/IXR/class-IXR-error.php | PHP5 constructor. |
| Used By | Description |
| --- | --- |
| [IXR\_ClientMulticall::query()](../ixr_clientmulticall/query) wp-includes/IXR/class-IXR-clientmulticall.php | |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Formalized the existing `...$args` parameter by adding it to the function signature. |
| [1.5.0](https://developer.wordpress.org/reference/since/1.5.0/) | Introduced. |
| programming_docs |
wordpress IXR_Client::getErrorMessage() IXR\_Client::getErrorMessage()
==============================
File: `wp-includes/IXR/class-IXR-client.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-client.php/)
```
function getErrorMessage()
{
return $this->error->message;
}
```
wordpress IXR_Client::__construct( $server, $path = false, $port = 80, $timeout = 15 ) IXR\_Client::\_\_construct( $server, $path = false, $port = 80, $timeout = 15 )
===============================================================================
PHP5 constructor.
File: `wp-includes/IXR/class-IXR-client.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-client.php/)
```
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;
}
```
| Used By | Description |
| --- | --- |
| [IXR\_Client::IXR\_Client()](ixr_client) wp-includes/IXR/class-IXR-client.php | PHP4 constructor. |
wordpress WP_Widget_Recent_Posts::form( array $instance ) WP\_Widget\_Recent\_Posts::form( array $instance )
==================================================
Outputs the settings form for the Recent Posts widget.
`$instance` array Required Current settings. 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/)
```
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 |
| --- | --- |
| [checked()](../../functions/checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Recent_Posts::update( array $new_instance, array $old_instance ): array WP\_Widget\_Recent\_Posts::update( array $new\_instance, array $old\_instance ): array
======================================================================================
Handles updating the settings for the current Recent Posts widget instance.
`$new_instance` array Required New settings for this instance as input by the user via [WP\_Widget::form()](../wp_widget/form). `$old_instance` array Required Old settings for this instance. array Updated settings to save.
File: `wp-includes/widgets/class-wp-widget-recent-posts.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-recent-posts.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Recent_Posts::__construct() WP\_Widget\_Recent\_Posts::\_\_construct()
==========================================
Sets up a new 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/)
```
public function __construct() {
$widget_ops = array(
'classname' => 'widget_recent_entries',
'description' => __( 'Your site’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';
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget::\_\_construct()](../wp_widget/__construct) wp-includes/class-wp-widget.php | PHP5 constructor. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Recent_Posts::widget( array $args, array $instance ) WP\_Widget\_Recent\_Posts::widget( array $args, array $instance )
=================================================================
Outputs the content for the current Recent Posts widget instance.
`$args` array Required Display arguments including `'before_title'`, `'after_title'`, `'before_widget'`, and `'after_widget'`. `$instance` array Required Settings for the current Recent 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/)
```
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'];
}
```
[apply\_filters( 'navigation\_widgets\_format', string $format )](../../hooks/navigation_widgets_format)
Filters the HTML format of widgets with navigation links.
[apply\_filters( 'widget\_posts\_args', array $args, array $instance )](../../hooks/widget_posts_args)
Filters the arguments for the Recent Posts widget.
[apply\_filters( 'widget\_title', string $title, array $instance, mixed $id\_base )](../../hooks/widget_title)
Filters the widget title.
| Uses | Description |
| --- | --- |
| [get\_the\_date()](../../functions/get_the_date) wp-includes/general-template.php | Retrieves the date on which the post was written. |
| [WP\_Query::\_\_construct()](../wp_query/__construct) wp-includes/class-wp-query.php | Constructor. |
| [get\_queried\_object\_id()](../../functions/get_queried_object_id) wp-includes/query.php | Retrieves the ID of the currently queried object. |
| [the\_permalink()](../../functions/the_permalink) wp-includes/link-template.php | Displays the permalink for the current post. |
| [get\_the\_title()](../../functions/get_the_title) wp-includes/post-template.php | Retrieves the post title. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Style_Engine_CSS_Rule::add_declarations( array|WP_Style_Engine_CSS_Declarations $declarations ): WP_Style_Engine_CSS_Rule WP\_Style\_Engine\_CSS\_Rule::add\_declarations( array|WP\_Style\_Engine\_CSS\_Declarations $declarations ): WP\_Style\_Engine\_CSS\_Rule
=========================================================================================================================================
Sets the declarations.
`$declarations` array|[WP\_Style\_Engine\_CSS\_Declarations](../wp_style_engine_css_declarations) Required An array of declarations (property => value pairs), or a [WP\_Style\_Engine\_CSS\_Declarations](../wp_style_engine_css_declarations) object. [WP\_Style\_Engine\_CSS\_Rule](../wp_style_engine_css_rule) Returns the object to allow chaining of methods.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Declarations::\_\_construct()](../wp_style_engine_css_declarations/__construct) wp-includes/style-engine/class-wp-style-engine-css-declarations.php | Constructor for this object. |
| Used By | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Rule::\_\_construct()](__construct) wp-includes/style-engine/class-wp-style-engine-css-rule.php | Constructor |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine_CSS_Rule::get_declarations(): WP_Style_Engine_CSS_Declarations WP\_Style\_Engine\_CSS\_Rule::get\_declarations(): WP\_Style\_Engine\_CSS\_Declarations
=======================================================================================
Gets the declarations object.
[WP\_Style\_Engine\_CSS\_Declarations](../wp_style_engine_css_declarations) The declarations object.
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/)
```
public function get_declarations() {
return $this->declarations;
}
```
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine_CSS_Rule::get_css( bool $should_prettify = false, number $indent_count ): string WP\_Style\_Engine\_CSS\_Rule::get\_css( bool $should\_prettify = false, number $indent\_count ): string
=======================================================================================================
Gets the CSS.
`$should_prettify` bool Optional Whether to add spacing, new lines and indents. Default: `false`
`$indent_count` number Required The number of tab indents to apply to the rule. Applies if `prettify` is `true`. string
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/)
```
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}}";
}
```
| Uses | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Rule::get\_selector()](get_selector) wp-includes/style-engine/class-wp-style-engine-css-rule.php | Gets the full selector. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine_CSS_Rule::set_selector( string $selector ): WP_Style_Engine_CSS_Rule WP\_Style\_Engine\_CSS\_Rule::set\_selector( string $selector ): WP\_Style\_Engine\_CSS\_Rule
=============================================================================================
Sets the selector.
`$selector` string Required The CSS selector. [WP\_Style\_Engine\_CSS\_Rule](../wp_style_engine_css_rule) Returns the object to allow chaining of methods.
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/)
```
public function set_selector( $selector ) {
$this->selector = $selector;
return $this;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Rule::\_\_construct()](__construct) wp-includes/style-engine/class-wp-style-engine-css-rule.php | Constructor |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine_CSS_Rule::__construct( string $selector = '', string[]|WP_Style_Engine_CSS_Declarations $declarations = array() ) WP\_Style\_Engine\_CSS\_Rule::\_\_construct( string $selector = '', string[]|WP\_Style\_Engine\_CSS\_Declarations $declarations = array() )
===========================================================================================================================================
Constructor
`$selector` string Optional The CSS selector. Default: `''`
`$declarations` string[]|[WP\_Style\_Engine\_CSS\_Declarations](../wp_style_engine_css_declarations) Optional An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ), or a [WP\_Style\_Engine\_CSS\_Declarations](../wp_style_engine_css_declarations) object. Default: `array()`
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/)
```
public function __construct( $selector = '', $declarations = array() ) {
$this->set_selector( $selector );
$this->add_declarations( $declarations );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Rule::set\_selector()](set_selector) wp-includes/style-engine/class-wp-style-engine-css-rule.php | Sets the selector. |
| [WP\_Style\_Engine\_CSS\_Rule::add\_declarations()](add_declarations) wp-includes/style-engine/class-wp-style-engine-css-rule.php | Sets the declarations. |
| Used By | Description |
| --- | --- |
| [WP\_Style\_Engine\_Processor::combine\_rules\_selectors()](../wp_style_engine_processor/combine_rules_selectors) wp-includes/style-engine/class-wp-style-engine-processor.php | Combines selectors from the rules store when they have the same styles. |
| [WP\_Style\_Engine\_CSS\_Rules\_Store::add\_rule()](../wp_style_engine_css_rules_store/add_rule) wp-includes/style-engine/class-wp-style-engine-css-rules-store.php | Gets a [WP\_Style\_Engine\_CSS\_Rule](../wp_style_engine_css_rule) object by its selector. |
| [WP\_Style\_Engine::compile\_css()](../wp_style_engine/compile_css) wp-includes/style-engine/class-wp-style-engine.php | Returns compiled CSS from css\_declarations. |
| [wp\_style\_engine\_get\_stylesheet\_from\_css\_rules()](../../functions/wp_style_engine_get_stylesheet_from_css_rules) wp-includes/style-engine.php | Returns compiled CSS from a collection of selectors and declarations. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
| programming_docs |
wordpress WP_Style_Engine_CSS_Rule::get_selector(): string WP\_Style\_Engine\_CSS\_Rule::get\_selector(): string
=====================================================
Gets the full selector.
string
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/)
```
public function get_selector() {
return $this->selector;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Rule::get\_css()](get_css) wp-includes/style-engine/class-wp-style-engine-css-rule.php | Gets the CSS. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine::parse_block_styles( array $block_styles, array $options ): array WP\_Style\_Engine::parse\_block\_styles( array $block\_styles, array $options ): array
======================================================================================
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.
`$block_styles` array Required The style object. `$options` array Optional An array of options. Default empty array.
* `convert_vars_to_classnames`boolWhether to skip converting incoming CSS var patterns, e.g., `var:preset|<PRESET_TYPE>|<PRESET_SLUG>`, to var( --wp--preset--\* ) values. Default `false`.
* `selector`stringOptional. 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.
array
* `classnames`stringClassnames separated by a space.
* `declarations`string[]An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ).
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [\_wp\_array\_get()](../../functions/_wp_array_get) wp-includes/functions.php | Accesses an array in depth based on a path of keys. |
| Used By | Description |
| --- | --- |
| [wp\_style\_engine\_get\_styles()](../../functions/wp_style_engine_get_styles) wp-includes/style-engine.php | Global public interface method to generate styles from a single style object, e.g., the value of a block’s attributes.style object or the top level styles in theme.json. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine::get_slug_from_preset_value( string $style_value, string $property_key ): string WP\_Style\_Engine::get\_slug\_from\_preset\_value( string $style\_value, string $property\_key ): string
========================================================================================================
Util: Extracts the slug in kebab case from a preset string, e.g., “heavenly-blue” from ‘var:preset|color|heavenlyBlue’.
`$style_value` string Required A single CSS preset value. `$property_key` string Required The CSS property that is the second element of the preset string. Used for matching. string The slug, or empty string if not found.
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/)
```
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 '';
}
```
| Uses | Description |
| --- | --- |
| [\_wp\_to\_kebab\_case()](../../functions/_wp_to_kebab_case) wp-includes/functions.php | This function is trying to replicate what lodash’s kebabCase (JS library) does in the client. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine::get_individual_property_css_declarations( array $style_value, array $individual_property_definition, array $options = array() ): string[] WP\_Style\_Engine::get\_individual\_property\_css\_declarations( array $style\_value, array $individual\_property\_definition, array $options = array() ): string[]
===================================================================================================================================================================
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};"
`$style_value` array Required A single raw style value from $block\_styles array. `$individual_property_definition` array Required A single style definition from BLOCK\_STYLE\_DEFINITIONS\_METADATA representing an individual property of a CSS property, e.g., `'top'` in `'border-top'`. `$options` array Optional An array of options.
* `convert_vars_to_classnames`boolWhether to skip converting incoming CSS var patterns, e.g., `var:preset|<PRESET_TYPE>|<PRESET_SLUG>`, to var( --wp--preset--\* ) values. Default `false`.
Default: `array()`
string[] An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ).
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [\_wp\_array\_get()](../../functions/_wp_array_get) wp-includes/functions.php | Accesses an array in depth based on a path of keys. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine::get_store( string $store_name ): WP_Style_Engine_CSS_Rules_Store WP\_Style\_Engine::get\_store( string $store\_name ): WP\_Style\_Engine\_CSS\_Rules\_Store
==========================================================================================
Returns a store by store key.
`$store_name` string Required A store key. [WP\_Style\_Engine\_CSS\_Rules\_Store](../wp_style_engine_css_rules_store)
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/)
```
public static function get_store( $store_name ) {
return WP_Style_Engine_CSS_Rules_Store::get_store( $store_name );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Rules\_Store::get\_store()](../wp_style_engine_css_rules_store/get_store) wp-includes/style-engine/class-wp-style-engine-css-rules-store.php | Gets an instance of the store. |
| Used By | Description |
| --- | --- |
| [wp\_style\_engine\_get\_stylesheet\_from\_context()](../../functions/wp_style_engine_get_stylesheet_from_context) wp-includes/style-engine.php | Returns compiled CSS from a store, if found. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine::is_valid_style_value( string $style_value ): bool WP\_Style\_Engine::is\_valid\_style\_value( string $style\_value ): bool
========================================================================
Util: Checks whether an incoming block style value is valid.
`$style_value` string Required A single CSS preset value. bool
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/)
```
protected static function is_valid_style_value( $style_value ) {
return '0' === $style_value || ! empty( $style_value );
}
```
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine::get_css_var_value( string $style_value, string[] $css_vars ): string WP\_Style\_Engine::get\_css\_var\_value( string $style\_value, string[] $css\_vars ): string
============================================================================================
Util: Generates a CSS var string, e.g., var(–wp–preset–color–background) from a preset string such as `var:preset|space|50`.
`$style_value` string Required A single css preset value. `$css_vars` string[] Required An associate array of css var patterns used to generate the var string. string The css var, or an empty string if no match for slug found.
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/)
```
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 '';
}
```
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine::compile_css( string[] $css_declarations, string $css_selector ): string WP\_Style\_Engine::compile\_css( string[] $css\_declarations, string $css\_selector ): string
=============================================================================================
Returns compiled CSS from css\_declarations.
`$css_declarations` string[] Required An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ). `$css_selector` string Required When a selector is passed, the function will return a full CSS rule `$selector { ...rules }`, otherwise a concatenated string of properties and values. string A compiled CSS string.
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/)
```
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();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Rule::\_\_construct()](../wp_style_engine_css_rule/__construct) wp-includes/style-engine/class-wp-style-engine-css-rule.php | Constructor |
| [WP\_Style\_Engine\_CSS\_Declarations::\_\_construct()](../wp_style_engine_css_declarations/__construct) wp-includes/style-engine/class-wp-style-engine-css-declarations.php | Constructor for this object. |
| Used By | Description |
| --- | --- |
| [wp\_style\_engine\_get\_styles()](../../functions/wp_style_engine_get_styles) wp-includes/style-engine.php | Global public interface method to generate styles from a single style object, e.g., the value of a block’s attributes.style object or the top level styles in theme.json. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine::store_css_rule( string $store_name, string $css_selector, string[] $css_declarations ): void. WP\_Style\_Engine::store\_css\_rule( string $store\_name, string $css\_selector, string[] $css\_declarations ): void.
=====================================================================================================================
Stores a CSS rule using the provided CSS selector and CSS declarations.
`$store_name` string Required A valid store key. `$css_selector` string Required When a selector is passed, the function will return a full CSS rule `$selector { ...rules }`, otherwise a concatenated string of properties and values. `$css_declarations` string[] Required An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ). void.
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/)
```
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 );
}
```
| Used By | Description |
| --- | --- |
| [wp\_style\_engine\_get\_styles()](../../functions/wp_style_engine_get_styles) wp-includes/style-engine.php | Global public interface method to generate styles from a single style object, e.g., the value of a block’s attributes.style object or the top level styles in theme.json. |
| [wp\_style\_engine\_get\_stylesheet\_from\_css\_rules()](../../functions/wp_style_engine_get_stylesheet_from_css_rules) wp-includes/style-engine.php | Returns compiled CSS from a collection of selectors and declarations. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine::compile_stylesheet_from_css_rules( WP_Style_Engine_CSS_Rule[] $css_rules, array $options = array() ): string WP\_Style\_Engine::compile\_stylesheet\_from\_css\_rules( WP\_Style\_Engine\_CSS\_Rule[] $css\_rules, array $options = array() ): string
========================================================================================================================================
Returns a compiled stylesheet from stored CSS rules.
`$css_rules` [WP\_Style\_Engine\_CSS\_Rule](../wp_style_engine_css_rule)[] Required An array of [WP\_Style\_Engine\_CSS\_Rule](../wp_style_engine_css_rule) objects from a store or otherwise. `$options` array Optional An array of options.
* `optimize`boolWhether to optimize the CSS output, e.g., combine rules. Default is `false`.
* `prettify`boolWhether to add new lines and indents to output. Default is the test of whether the global constant `SCRIPT_DEBUG` is defined.
Default: `array()`
string A compiled stylesheet from stored CSS rules.
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/)
```
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 );
}
```
| Used By | Description |
| --- | --- |
| [wp\_style\_engine\_get\_stylesheet\_from\_css\_rules()](../../functions/wp_style_engine_get_stylesheet_from_css_rules) wp-includes/style-engine.php | Returns compiled CSS from a collection of selectors and declarations. |
| [wp\_style\_engine\_get\_stylesheet\_from\_context()](../../functions/wp_style_engine_get_stylesheet_from_context) wp-includes/style-engine.php | Returns compiled CSS from a store, if found. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine::get_css_declarations( array $style_value, array $style_definition, array $options = array() ): string[] WP\_Style\_Engine::get\_css\_declarations( array $style\_value, array $style\_definition, array $options = array() ): string[]
==============================================================================================================================
Returns an array of CSS declarations based on valid block style values.
`$style_value` array Required A single raw style value from $block\_styles array. `$style_definition` array Required A single style definition from BLOCK\_STYLE\_DEFINITIONS\_METADATA. `$options` array Optional An array of options.
* `convert_vars_to_classnames`boolWhether to skip converting incoming CSS var patterns, e.g., `var:preset|<PRESET_TYPE>|<PRESET_SLUG>`, to var( --wp--preset--\* ) values. Default `false`.
Default: `array()`
string[] An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ).
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [\_wp\_to\_kebab\_case()](../../functions/_wp_to_kebab_case) wp-includes/functions.php | This function is trying to replicate what lodash’s kebabCase (JS library) does in the client. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
| programming_docs |
wordpress WP_Style_Engine::get_classnames( array $style_value, array $style_definition ): array|string[] WP\_Style\_Engine::get\_classnames( array $style\_value, array $style\_definition ): array|string[]
===================================================================================================
Returns classnames, and generates classname(s) from a CSS preset property pattern, e.g., ‘`var:preset||`‘.
`$style_value` array Required A single raw style value or css preset property from the $block\_styles array. `$style_definition` array Required A single style definition from BLOCK\_STYLE\_DEFINITIONS\_METADATA. array|string[] An array of CSS classnames, or empty array.
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/)
```
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;
}
```
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Importer::get_imported_posts( string $importer_name, string $blog_id ): array WP\_Importer::get\_imported\_posts( string $importer\_name, string $blog\_id ): array
=====================================================================================
Returns array with imported permalinks from WordPress database
`$importer_name` string Required `$blog_id` string Required array
File: `wp-admin/includes/class-wp-importer.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-importer.php/)
```
public function get_imported_posts( $importer_name, $blog_id ) {
global $wpdb;
$hashtable = array();
$limit = 100;
$offset = 0;
// Grab all posts in chunks.
do {
$meta_key = $importer_name . '_' . $blog_id . '_permalink';
$sql = $wpdb->prepare( "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = %s LIMIT %d,%d", $meta_key, $offset, $limit );
$results = $wpdb->get_results( $sql );
// Increment offset.
$offset = ( $limit + $offset );
if ( ! empty( $results ) ) {
foreach ( $results as $r ) {
// Set permalinks into array.
$hashtable[ $r->meta_value ] = (int) $r->post_id;
}
}
} while ( count( $results ) == $limit );
return $hashtable;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_results()](../wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
wordpress WP_Importer::is_user_over_quota(): bool WP\_Importer::is\_user\_over\_quota(): bool
===========================================
Check if user has exceeded disk quota
bool
File: `wp-admin/includes/class-wp-importer.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-importer.php/)
```
public function is_user_over_quota() {
if ( function_exists( 'upload_is_user_over_quota' ) ) {
if ( upload_is_user_over_quota() ) {
return true;
}
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [upload\_is\_user\_over\_quota()](../../functions/upload_is_user_over_quota) wp-admin/includes/ms.php | Check whether a site has used its allotted upload space. |
wordpress WP_Importer::get_imported_comments( string $blog_id ): array WP\_Importer::get\_imported\_comments( string $blog\_id ): array
================================================================
Set array with imported comments from WordPress database
`$blog_id` string Required array
File: `wp-admin/includes/class-wp-importer.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-importer.php/)
```
public function get_imported_comments( $blog_id ) {
global $wpdb;
$hashtable = array();
$limit = 100;
$offset = 0;
// Grab all comments in chunks.
do {
$sql = $wpdb->prepare( "SELECT comment_ID, comment_agent FROM $wpdb->comments LIMIT %d,%d", $offset, $limit );
$results = $wpdb->get_results( $sql );
// Increment offset.
$offset = ( $limit + $offset );
if ( ! empty( $results ) ) {
foreach ( $results as $r ) {
// Explode comment_agent key.
list ( $comment_agent_blog_id, $source_comment_id ) = explode( '-', $r->comment_agent );
$source_comment_id = (int) $source_comment_id;
// Check if this comment came from this blog.
if ( $blog_id == $comment_agent_blog_id ) {
$hashtable[ $source_comment_id ] = (int) $r->comment_ID;
}
}
}
} while ( count( $results ) == $limit );
return $hashtable;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_results()](../wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
wordpress WP_Importer::min_whitespace( string $text ): string WP\_Importer::min\_whitespace( string $text ): string
=====================================================
Replace newlines, tabs, and multiple spaces with a single space.
`$text` string Required string
File: `wp-admin/includes/class-wp-importer.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-importer.php/)
```
public function min_whitespace( $text ) {
return preg_replace( '|[\r\n\t ]+|', ' ', $text );
}
```
wordpress WP_Importer::set_blog( int $blog_id ): int|void WP\_Importer::set\_blog( int $blog\_id ): int|void
==================================================
`$blog_id` int Required int|void
File: `wp-admin/includes/class-wp-importer.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-importer.php/)
```
public function set_blog( $blog_id ) {
if ( is_numeric( $blog_id ) ) {
$blog_id = (int) $blog_id;
} else {
$blog = 'http://' . preg_replace( '#^https?://#', '', $blog_id );
$parsed = parse_url( $blog );
if ( ! $parsed || empty( $parsed['host'] ) ) {
fwrite( STDERR, "Error: can not determine blog_id from $blog_id\n" );
exit;
}
if ( empty( $parsed['path'] ) ) {
$parsed['path'] = '/';
}
$blogs = get_sites(
array(
'domain' => $parsed['host'],
'number' => 1,
'path' => $parsed['path'],
)
);
if ( ! $blogs ) {
fwrite( STDERR, "Error: Could not find blog\n" );
exit;
}
$blog = array_shift( $blogs );
$blog_id = (int) $blog->blog_id;
}
if ( function_exists( 'is_multisite' ) ) {
if ( is_multisite() ) {
switch_to_blog( $blog_id );
}
}
return $blog_id;
}
```
| Uses | Description |
| --- | --- |
| [get\_sites()](../../functions/get_sites) wp-includes/ms-site.php | Retrieves a list of sites matching requested arguments. |
| [switch\_to\_blog()](../../functions/switch_to_blog) wp-includes/ms-blogs.php | Switch the current blog. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
wordpress WP_Importer::set_user( int $user_id ): int|void WP\_Importer::set\_user( int $user\_id ): int|void
==================================================
`$user_id` int Required int|void
File: `wp-admin/includes/class-wp-importer.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-importer.php/)
```
public function set_user( $user_id ) {
if ( is_numeric( $user_id ) ) {
$user_id = (int) $user_id;
} else {
$user_id = (int) username_exists( $user_id );
}
if ( ! $user_id || ! wp_set_current_user( $user_id ) ) {
fwrite( STDERR, "Error: can not find user\n" );
exit;
}
return $user_id;
}
```
| Uses | Description |
| --- | --- |
| [wp\_set\_current\_user()](../../functions/wp_set_current_user) wp-includes/pluggable.php | Changes the current user by ID or name. |
| [username\_exists()](../../functions/username_exists) wp-includes/user.php | Determines whether the given username exists. |
wordpress WP_Importer::cmpr_strlen( string $a, string $b ): int WP\_Importer::cmpr\_strlen( string $a, string $b ): int
=======================================================
Sort by strlen, longest string first
`$a` string Required `$b` string Required int
File: `wp-admin/includes/class-wp-importer.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-importer.php/)
```
public function cmpr_strlen( $a, $b ) {
return strlen( $b ) - strlen( $a );
}
```
wordpress WP_Importer::count_imported_posts( string $importer_name, string $blog_id ): int WP\_Importer::count\_imported\_posts( string $importer\_name, string $blog\_id ): int
=====================================================================================
Return count of imported permalinks from WordPress database
`$importer_name` string Required `$blog_id` string Required int
File: `wp-admin/includes/class-wp-importer.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-importer.php/)
```
public function count_imported_posts( $importer_name, $blog_id ) {
global $wpdb;
$count = 0;
// Get count of permalinks.
$meta_key = $importer_name . '_' . $blog_id . '_permalink';
$sql = $wpdb->prepare( "SELECT COUNT( post_id ) AS cnt FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key );
$result = $wpdb->get_results( $sql );
if ( ! empty( $result ) ) {
$count = (int) $result[0]->cnt;
}
return $count;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_results()](../wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
wordpress WP_Importer::__construct() WP\_Importer::\_\_construct()
=============================
Class Constructor
File: `wp-admin/includes/class-wp-importer.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-importer.php/)
```
public function __construct() {}
```
wordpress WP_Importer::bump_request_timeout( int $val ): int WP\_Importer::bump\_request\_timeout( int $val ): int
=====================================================
Bump up the request timeout for http requests
`$val` int Required int
File: `wp-admin/includes/class-wp-importer.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-importer.php/)
```
public function bump_request_timeout( $val ) {
return 60;
}
```
wordpress WP_Importer::stop_the_insanity() WP\_Importer::stop\_the\_insanity()
===================================
Resets global variables that grow out of control during imports.
File: `wp-admin/includes/class-wp-importer.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-importer.php/)
```
public function stop_the_insanity() {
global $wpdb, $wp_actions;
// Or define( 'WP_IMPORTING', true );
$wpdb->queries = array();
// Reset $wp_actions to keep it from growing out of control.
$wp_actions = array();
}
```
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress WP_Importer::get_page( string $url, string $username = '', string $password = '', bool $head = false ): array WP\_Importer::get\_page( string $url, string $username = '', string $password = '', bool $head = false ): array
===============================================================================================================
GET URL
`$url` string Required `$username` string Optional Default: `''`
`$password` string Optional Default: `''`
`$head` bool Optional Default: `false`
array
File: `wp-admin/includes/class-wp-importer.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-importer.php/)
```
public function get_page( $url, $username = '', $password = '', $head = false ) {
// Increase the timeout.
add_filter( 'http_request_timeout', array( $this, 'bump_request_timeout' ) );
$headers = array();
$args = array();
if ( true === $head ) {
$args['method'] = 'HEAD';
}
if ( ! empty( $username ) && ! empty( $password ) ) {
$headers['Authorization'] = 'Basic ' . base64_encode( "$username:$password" );
}
$args['headers'] = $headers;
return wp_safe_remote_request( $url, $args );
}
```
| Uses | Description |
| --- | --- |
| [wp\_safe\_remote\_request()](../../functions/wp_safe_remote_request) wp-includes/http.php | Retrieve the raw response from a safe HTTP request. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
wordpress WP_Comments_List_Table::single_row( WP_Comment $item ) WP\_Comments\_List\_Table::single\_row( WP\_Comment $item )
===========================================================
`$item` [WP\_Comment](../wp_comment) Required File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function single_row( $item ) {
global $post, $comment;
$comment = $item;
$the_comment_class = wp_get_comment_status( $comment );
if ( ! $the_comment_class ) {
$the_comment_class = '';
}
$the_comment_class = implode( ' ', get_comment_class( $the_comment_class, $comment, $comment->comment_post_ID ) );
if ( $comment->comment_post_ID > 0 ) {
$post = get_post( $comment->comment_post_ID );
}
$this->user_can = current_user_can( 'edit_comment', $comment->comment_ID );
echo "<tr id='comment-$comment->comment_ID' class='$the_comment_class'>";
$this->single_row_columns( $comment );
echo "</tr>\n";
unset( $GLOBALS['post'], $GLOBALS['comment'] );
}
```
| Uses | Description |
| --- | --- |
| [get\_comment\_class()](../../functions/get_comment_class) wp-includes/comment-template.php | Returns the classes for the comment div as an array. |
| [wp\_get\_comment\_status()](../../functions/wp_get_comment_status) wp-includes/comment.php | Retrieves the status of a comment by comment ID. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
wordpress WP_Comments_List_Table::extra_tablenav( string $which ) WP\_Comments\_List\_Table::extra\_tablenav( string $which )
===========================================================
`$which` string Required File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
protected function extra_tablenav( $which ) {
global $comment_status, $comment_type;
static $has_items;
if ( ! isset( $has_items ) ) {
$has_items = $this->has_items();
}
echo '<div class="alignleft actions">';
if ( 'top' === $which ) {
ob_start();
$this->comment_type_dropdown( $comment_type );
/**
* Fires just before the Filter submit button for comment types.
*
* @since 3.5.0
*/
do_action( 'restrict_manage_comments' );
$output = ob_get_clean();
if ( ! empty( $output ) && $this->has_items() ) {
echo $output;
submit_button( __( 'Filter' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) );
}
}
if ( ( 'spam' === $comment_status || 'trash' === $comment_status ) && $has_items
&& current_user_can( 'moderate_comments' )
) {
wp_nonce_field( 'bulk-destroy', '_destroy_nonce' );
$title = ( 'spam' === $comment_status ) ? esc_attr__( 'Empty Spam' ) : esc_attr__( 'Empty Trash' );
submit_button( $title, 'apply', 'delete_all', false );
}
/**
* Fires after the Filter submit button for comment types.
*
* @since 2.5.0
* @since 5.6.0 The `$which` parameter was added.
*
* @param string $comment_status The comment status name. Default 'All'.
* @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
*/
do_action( 'manage_comments_nav', $comment_status, $which );
echo '</div>';
}
```
[do\_action( 'manage\_comments\_nav', string $comment\_status, string $which )](../../hooks/manage_comments_nav)
Fires after the Filter submit button for comment types.
[do\_action( 'restrict\_manage\_comments' )](../../hooks/restrict_manage_comments)
Fires just before the Filter submit button for comment types.
| Uses | Description |
| --- | --- |
| [WP\_Comments\_List\_Table::comment\_type\_dropdown()](comment_type_dropdown) wp-admin/includes/class-wp-comments-list-table.php | Displays a comment type drop-down for filtering on the Comments list table. |
| [submit\_button()](../../functions/submit_button) wp-admin/includes/template.php | Echoes a submit button, with provided text and appropriate class(es). |
| [esc\_attr\_\_()](../../functions/esc_attr__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in an attribute. |
| [wp\_nonce\_field()](../../functions/wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
wordpress WP_Comments_List_Table::current_action(): string|false WP\_Comments\_List\_Table::current\_action(): string|false
==========================================================
string|false
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function current_action() {
if ( isset( $_REQUEST['delete_all'] ) || isset( $_REQUEST['delete_all2'] ) ) {
return 'delete_all';
}
return parent::current_action();
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::current\_action()](../wp_list_table/current_action) wp-admin/includes/class-wp-list-table.php | Gets the current action selected from the bulk actions dropdown. |
wordpress WP_Comments_List_Table::prepare_items() WP\_Comments\_List\_Table::prepare\_items()
===========================================
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function prepare_items() {
global $mode, $post_id, $comment_status, $comment_type, $search;
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' );
}
$comment_status = isset( $_REQUEST['comment_status'] ) ? $_REQUEST['comment_status'] : 'all';
if ( ! in_array( $comment_status, array( 'all', 'mine', 'moderated', 'approved', 'spam', 'trash' ), true ) ) {
$comment_status = 'all';
}
$comment_type = ! empty( $_REQUEST['comment_type'] ) ? $_REQUEST['comment_type'] : '';
$search = ( isset( $_REQUEST['s'] ) ) ? $_REQUEST['s'] : '';
$post_type = ( isset( $_REQUEST['post_type'] ) ) ? sanitize_key( $_REQUEST['post_type'] ) : '';
$user_id = ( isset( $_REQUEST['user_id'] ) ) ? $_REQUEST['user_id'] : '';
$orderby = ( isset( $_REQUEST['orderby'] ) ) ? $_REQUEST['orderby'] : '';
$order = ( isset( $_REQUEST['order'] ) ) ? $_REQUEST['order'] : '';
$comments_per_page = $this->get_per_page( $comment_status );
$doing_ajax = wp_doing_ajax();
if ( isset( $_REQUEST['number'] ) ) {
$number = (int) $_REQUEST['number'];
} else {
$number = $comments_per_page + min( 8, $comments_per_page ); // Grab a few extra.
}
$page = $this->get_pagenum();
if ( isset( $_REQUEST['start'] ) ) {
$start = $_REQUEST['start'];
} else {
$start = ( $page - 1 ) * $comments_per_page;
}
if ( $doing_ajax && isset( $_REQUEST['offset'] ) ) {
$start += $_REQUEST['offset'];
}
$status_map = array(
'mine' => '',
'moderated' => 'hold',
'approved' => 'approve',
'all' => '',
);
$args = array(
'status' => isset( $status_map[ $comment_status ] ) ? $status_map[ $comment_status ] : $comment_status,
'search' => $search,
'user_id' => $user_id,
'offset' => $start,
'number' => $number,
'post_id' => $post_id,
'type' => $comment_type,
'orderby' => $orderby,
'order' => $order,
'post_type' => $post_type,
);
/**
* Filters the arguments for the comment query in the comments list table.
*
* @since 5.1.0
*
* @param array $args An array of get_comments() arguments.
*/
$args = apply_filters( 'comments_list_table_query_args', $args );
$_comments = get_comments( $args );
if ( is_array( $_comments ) ) {
update_comment_cache( $_comments );
$this->items = array_slice( $_comments, 0, $comments_per_page );
$this->extra_items = array_slice( $_comments, $comments_per_page );
$_comment_post_ids = array_unique( wp_list_pluck( $_comments, 'comment_post_ID' ) );
$this->pending_count = get_pending_comments_num( $_comment_post_ids );
}
$total_comments = get_comments(
array_merge(
$args,
array(
'count' => true,
'offset' => 0,
'number' => 0,
)
)
);
$this->set_pagination_args(
array(
'total_items' => $total_comments,
'per_page' => $comments_per_page,
)
);
}
```
[apply\_filters( 'comments\_list\_table\_query\_args', array $args )](../../hooks/comments_list_table_query_args)
Filters the arguments for the comment query in the comments list table.
| Uses | Description |
| --- | --- |
| [wp\_doing\_ajax()](../../functions/wp_doing_ajax) wp-includes/load.php | Determines whether the current request is a WordPress Ajax request. |
| [WP\_Comments\_List\_Table::get\_per\_page()](get_per_page) wp-admin/includes/class-wp-comments-list-table.php | |
| [get\_pending\_comments\_num()](../../functions/get_pending_comments_num) wp-admin/includes/comment.php | Gets the number of pending comments on a post or posts. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [set\_user\_setting()](../../functions/set_user_setting) wp-includes/option.php | Adds or updates user interface setting. |
| [get\_user\_setting()](../../functions/get_user_setting) wp-includes/option.php | Retrieves user interface setting value based on setting name. |
| [update\_comment\_cache()](../../functions/update_comment_cache) wp-includes/comment.php | Updates the comment cache of given comments. |
| [get\_comments()](../../functions/get_comments) wp-includes/comment.php | Retrieves a list of comments. |
| [sanitize\_key()](../../functions/sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| programming_docs |
wordpress WP_Comments_List_Table::column_response( WP_Comment $comment ) WP\_Comments\_List\_Table::column\_response( WP\_Comment $comment )
===================================================================
`$comment` [WP\_Comment](../wp_comment) Required The comment object. File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function column_response( $comment ) {
$post = get_post();
if ( ! $post ) {
return;
}
if ( isset( $this->pending_count[ $post->ID ] ) ) {
$pending_comments = $this->pending_count[ $post->ID ];
} else {
$_pending_count_temp = get_pending_comments_num( array( $post->ID ) );
$pending_comments = $_pending_count_temp[ $post->ID ];
$this->pending_count[ $post->ID ] = $pending_comments;
}
if ( current_user_can( 'edit_post', $post->ID ) ) {
$post_link = "<a href='" . get_edit_post_link( $post->ID ) . "' class='comments-edit-item-link'>";
$post_link .= esc_html( get_the_title( $post->ID ) ) . '</a>';
} else {
$post_link = esc_html( get_the_title( $post->ID ) );
}
echo '<div class="response-links">';
if ( 'attachment' === $post->post_type ) {
$thumb = wp_get_attachment_image( $post->ID, array( 80, 60 ), true );
if ( $thumb ) {
echo $thumb;
}
}
echo $post_link;
$post_type_object = get_post_type_object( $post->post_type );
echo "<a href='" . get_permalink( $post->ID ) . "' class='comments-view-item-link'>" . $post_type_object->labels->view_item . '</a>';
echo '<span class="post-com-count-wrapper post-com-count-', $post->ID, '">';
$this->comments_bubble( $post->ID, $pending_comments );
echo '</span> ';
echo '</div>';
}
```
| Uses | Description |
| --- | --- |
| [get\_pending\_comments\_num()](../../functions/get_pending_comments_num) wp-admin/includes/comment.php | Gets the number of pending comments on a post or posts. |
| [get\_edit\_post\_link()](../../functions/get_edit_post_link) wp-includes/link-template.php | Retrieves the edit post link for post. |
| [get\_the\_title()](../../functions/get_the_title) wp-includes/post-template.php | Retrieves the post title. |
| [wp\_get\_attachment\_image()](../../functions/wp_get_attachment_image) wp-includes/media.php | Gets an HTML img element representing an image attachment. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [get\_permalink()](../../functions/get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
wordpress WP_Comments_List_Table::ajax_user_can(): bool WP\_Comments\_List\_Table::ajax\_user\_can(): bool
==================================================
bool
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function ajax_user_can() {
return current_user_can( 'edit_posts' );
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
wordpress WP_Comments_List_Table::get_per_page( string $comment_status = 'all' ): int WP\_Comments\_List\_Table::get\_per\_page( string $comment\_status = 'all' ): int
=================================================================================
`$comment_status` string Optional Default: `'all'`
int
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function get_per_page( $comment_status = 'all' ) {
$comments_per_page = $this->get_items_per_page( 'edit_comments_per_page' );
/**
* Filters the number of comments listed per page in the comments list table.
*
* @since 2.6.0
*
* @param int $comments_per_page The number of comments to list per page.
* @param string $comment_status The comment status name. Default 'All'.
*/
return apply_filters( 'comments_per_page', $comments_per_page, $comment_status );
}
```
[apply\_filters( 'comments\_per\_page', int $comments\_per\_page, string $comment\_status )](../../hooks/comments_per_page)
Filters the number of comments listed per page in the comments list table.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Comments\_List\_Table::prepare\_items()](prepare_items) wp-admin/includes/class-wp-comments-list-table.php | |
wordpress WP_Comments_List_Table::column_author( WP_Comment $comment ) WP\_Comments\_List\_Table::column\_author( WP\_Comment $comment )
=================================================================
`$comment` [WP\_Comment](../wp_comment) Required The comment object. File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function column_author( $comment ) {
global $comment_status;
$author_url = get_comment_author_url( $comment );
$author_url_display = untrailingslashit( preg_replace( '|^http(s)?://(www\.)?|i', '', $author_url ) );
if ( strlen( $author_url_display ) > 50 ) {
$author_url_display = wp_html_excerpt( $author_url_display, 49, '…' );
}
echo '<strong>';
comment_author( $comment );
echo '</strong><br />';
if ( ! empty( $author_url_display ) ) {
// Print link to author URL, and disallow referrer information (without using target="_blank").
printf(
'<a href="%s" rel="noopener noreferrer">%s</a><br />',
esc_url( $author_url ),
esc_html( $author_url_display )
);
}
if ( $this->user_can ) {
if ( ! empty( $comment->comment_author_email ) ) {
/** This filter is documented in wp-includes/comment-template.php */
$email = apply_filters( 'comment_email', $comment->comment_author_email, $comment );
if ( ! empty( $email ) && '@' !== $email ) {
printf( '<a href="%1$s">%2$s</a><br />', esc_url( 'mailto:' . $email ), esc_html( $email ) );
}
}
$author_ip = get_comment_author_IP( $comment );
if ( $author_ip ) {
$author_ip_url = add_query_arg(
array(
's' => $author_ip,
'mode' => 'detail',
),
admin_url( 'edit-comments.php' )
);
if ( 'spam' === $comment_status ) {
$author_ip_url = add_query_arg( 'comment_status', 'spam', $author_ip_url );
}
printf( '<a href="%1$s">%2$s</a>', esc_url( $author_ip_url ), esc_html( $author_ip ) );
}
}
}
```
[apply\_filters( 'comment\_email', string $comment\_author\_email, WP\_Comment $comment )](../../hooks/comment_email)
Filters the comment author’s email for display.
| Uses | Description |
| --- | --- |
| [wp\_html\_excerpt()](../../functions/wp_html_excerpt) wp-includes/formatting.php | Safely extracts not more than the first $count characters from HTML string. |
| [untrailingslashit()](../../functions/untrailingslashit) wp-includes/formatting.php | Removes trailing forward slashes and backslashes if they exist. |
| [get\_comment\_author\_url()](../../functions/get_comment_author_url) wp-includes/comment-template.php | Retrieves the URL of the author of the current comment, not linked. |
| [comment\_author()](../../functions/comment_author) wp-includes/comment-template.php | Displays the author of the current comment. |
| [get\_comment\_author\_IP()](../../functions/get_comment_author_ip) wp-includes/comment-template.php | Retrieves the IP address of the author of the current comment. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Comments\_List\_Table::column\_comment()](column_comment) wp-admin/includes/class-wp-comments-list-table.php | |
wordpress WP_Comments_List_Table::no_items() WP\_Comments\_List\_Table::no\_items()
======================================
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function no_items() {
global $comment_status;
if ( 'moderated' === $comment_status ) {
_e( 'No comments awaiting moderation.' );
} elseif ( 'trash' === $comment_status ) {
_e( 'No comments found in Trash.' );
} else {
_e( 'No comments found.' );
}
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
wordpress WP_Comments_List_Table::get_default_primary_column_name(): string WP\_Comments\_List\_Table::get\_default\_primary\_column\_name(): string
========================================================================
Gets the name of the default primary column.
string Name of the default primary column, in this case, `'comment'`.
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
protected function get_default_primary_column_name() {
return 'comment';
}
```
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Comments_List_Table::handle_row_actions( WP_Comment $item, string $column_name, string $primary ): string WP\_Comments\_List\_Table::handle\_row\_actions( WP\_Comment $item, string $column\_name, string $primary ): string
===================================================================================================================
Generates and displays row actions links.
`$item` [WP\_Comment](../wp_comment) Required The comment object. `$column_name` string Required Current column name. `$primary` string Required Primary column name. string Row actions output for comments. An empty string if the current column is not the primary column, or if the current user cannot edit the comment.
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
protected function handle_row_actions( $item, $column_name, $primary ) {
global $comment_status;
if ( $primary !== $column_name ) {
return '';
}
if ( ! $this->user_can ) {
return '';
}
// Restores the more descriptive, specific name for use within this method.
$comment = $item;
$the_comment_status = wp_get_comment_status( $comment );
$output = '';
$del_nonce = esc_html( '_wpnonce=' . wp_create_nonce( "delete-comment_$comment->comment_ID" ) );
$approve_nonce = esc_html( '_wpnonce=' . wp_create_nonce( "approve-comment_$comment->comment_ID" ) );
$url = "comment.php?c=$comment->comment_ID";
$approve_url = esc_url( $url . "&action=approvecomment&$approve_nonce" );
$unapprove_url = esc_url( $url . "&action=unapprovecomment&$approve_nonce" );
$spam_url = esc_url( $url . "&action=spamcomment&$del_nonce" );
$unspam_url = esc_url( $url . "&action=unspamcomment&$del_nonce" );
$trash_url = esc_url( $url . "&action=trashcomment&$del_nonce" );
$untrash_url = esc_url( $url . "&action=untrashcomment&$del_nonce" );
$delete_url = esc_url( $url . "&action=deletecomment&$del_nonce" );
// Preorder it: Approve | Reply | Quick Edit | Edit | Spam | Trash.
$actions = array(
'approve' => '',
'unapprove' => '',
'reply' => '',
'quickedit' => '',
'edit' => '',
'spam' => '',
'unspam' => '',
'trash' => '',
'untrash' => '',
'delete' => '',
);
// Not looking at all comments.
if ( $comment_status && 'all' !== $comment_status ) {
if ( 'approved' === $the_comment_status ) {
$actions['unapprove'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="vim-u vim-destructive aria-button-if-js" aria-label="%s">%s</a>',
$unapprove_url,
"delete:the-comment-list:comment-{$comment->comment_ID}:e7e7d3:action=dim-comment&new=unapproved",
esc_attr__( 'Unapprove this comment' ),
__( 'Unapprove' )
);
} elseif ( 'unapproved' === $the_comment_status ) {
$actions['approve'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="vim-a vim-destructive aria-button-if-js" aria-label="%s">%s</a>',
$approve_url,
"delete:the-comment-list:comment-{$comment->comment_ID}:e7e7d3:action=dim-comment&new=approved",
esc_attr__( 'Approve this comment' ),
__( 'Approve' )
);
}
} else {
$actions['approve'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="vim-a aria-button-if-js" aria-label="%s">%s</a>',
$approve_url,
"dim:the-comment-list:comment-{$comment->comment_ID}:unapproved:e7e7d3:e7e7d3:new=approved",
esc_attr__( 'Approve this comment' ),
__( 'Approve' )
);
$actions['unapprove'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="vim-u aria-button-if-js" aria-label="%s">%s</a>',
$unapprove_url,
"dim:the-comment-list:comment-{$comment->comment_ID}:unapproved:e7e7d3:e7e7d3:new=unapproved",
esc_attr__( 'Unapprove this comment' ),
__( 'Unapprove' )
);
}
if ( 'spam' !== $the_comment_status ) {
$actions['spam'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="vim-s vim-destructive aria-button-if-js" aria-label="%s">%s</a>',
$spam_url,
"delete:the-comment-list:comment-{$comment->comment_ID}::spam=1",
esc_attr__( 'Mark this comment as spam' ),
/* translators: "Mark as spam" link. */
_x( 'Spam', 'verb' )
);
} elseif ( 'spam' === $the_comment_status ) {
$actions['unspam'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="vim-z vim-destructive aria-button-if-js" aria-label="%s">%s</a>',
$unspam_url,
"delete:the-comment-list:comment-{$comment->comment_ID}:66cc66:unspam=1",
esc_attr__( 'Restore this comment from the spam' ),
_x( 'Not Spam', 'comment' )
);
}
if ( 'trash' === $the_comment_status ) {
$actions['untrash'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="vim-z vim-destructive aria-button-if-js" aria-label="%s">%s</a>',
$untrash_url,
"delete:the-comment-list:comment-{$comment->comment_ID}:66cc66:untrash=1",
esc_attr__( 'Restore this comment from the Trash' ),
__( 'Restore' )
);
}
if ( 'spam' === $the_comment_status || 'trash' === $the_comment_status || ! EMPTY_TRASH_DAYS ) {
$actions['delete'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="delete vim-d vim-destructive aria-button-if-js" aria-label="%s">%s</a>',
$delete_url,
"delete:the-comment-list:comment-{$comment->comment_ID}::delete=1",
esc_attr__( 'Delete this comment permanently' ),
__( 'Delete Permanently' )
);
} else {
$actions['trash'] = sprintf(
'<a href="%s" data-wp-lists="%s" class="delete vim-d vim-destructive aria-button-if-js" aria-label="%s">%s</a>',
$trash_url,
"delete:the-comment-list:comment-{$comment->comment_ID}::trash=1",
esc_attr__( 'Move this comment to the Trash' ),
_x( 'Trash', 'verb' )
);
}
if ( 'spam' !== $the_comment_status && 'trash' !== $the_comment_status ) {
$actions['edit'] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
"comment.php?action=editcomment&c={$comment->comment_ID}",
esc_attr__( 'Edit this comment' ),
__( 'Edit' )
);
$format = '<button type="button" data-comment-id="%d" data-post-id="%d" data-action="%s" class="%s button-link" aria-expanded="false" aria-label="%s">%s</button>';
$actions['quickedit'] = sprintf(
$format,
$comment->comment_ID,
$comment->comment_post_ID,
'edit',
'vim-q comment-inline',
esc_attr__( 'Quick edit this comment inline' ),
__( 'Quick Edit' )
);
$actions['reply'] = sprintf(
$format,
$comment->comment_ID,
$comment->comment_post_ID,
'replyto',
'vim-r comment-inline',
esc_attr__( 'Reply to this comment' ),
__( 'Reply' )
);
}
/** This filter is documented in wp-admin/includes/dashboard.php */
$actions = apply_filters( 'comment_row_actions', array_filter( $actions ), $comment );
$always_visible = false;
$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;
if ( ( ( 'approve' === $action || 'unapprove' === $action ) && 2 === $i )
|| 1 === $i
) {
$separator = '';
} else {
$separator = ' | ';
}
// Reply and quickedit need a hide-if-no-js span when not added with Ajax.
if ( ( 'reply' === $action || 'quickedit' === $action ) && ! wp_doing_ajax() ) {
$action .= ' hide-if-no-js';
} elseif ( ( 'untrash' === $action && 'trash' === $the_comment_status )
|| ( 'unspam' === $action && 'spam' === $the_comment_status )
) {
if ( '1' === get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true ) ) {
$action .= ' approve';
} else {
$action .= ' unapprove';
}
}
$output .= "<span class='$action'>{$separator}{$link}</span>";
}
$output .= '</div>';
$output .= '<button type="button" class="toggle-row"><span class="screen-reader-text">' . __( 'Show more details' ) . '</span></button>';
return $output;
}
```
[apply\_filters( 'comment\_row\_actions', string[] $actions, WP\_Comment $comment )](../../hooks/comment_row_actions)
Filters the action links displayed for each comment in the ‘Recent Comments’ dashboard widget.
| Uses | Description |
| --- | --- |
| [wp\_doing\_ajax()](../../functions/wp_doing_ajax) wp-includes/load.php | Determines whether the current request is a WordPress Ajax request. |
| [esc\_attr\_\_()](../../functions/esc_attr__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in an attribute. |
| [wp\_create\_nonce()](../../functions/wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| [get\_user\_setting()](../../functions/get_user_setting) wp-includes/option.php | Retrieves user interface setting value based on setting name. |
| [wp\_get\_comment\_status()](../../functions/wp_get_comment_status) wp-includes/comment.php | Retrieves the status of a comment by comment ID. |
| [get\_comment\_meta()](../../functions/get_comment_meta) wp-includes/comment.php | Retrieves comment meta field for a comment. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$comment` to `$item` to match parent class for PHP 8 named parameter support. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
| programming_docs |
wordpress WP_Comments_List_Table::floated_admin_avatar( string $name, int $comment_id ): string WP\_Comments\_List\_Table::floated\_admin\_avatar( string $name, int $comment\_id ): string
===========================================================================================
Adds avatars to comment author names.
`$name` string Required Comment author name. `$comment_id` int Required Comment ID. string Avatar with the user name.
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function floated_admin_avatar( $name, $comment_id ) {
$comment = get_comment( $comment_id );
$avatar = get_avatar( $comment, 32, 'mystery' );
return "$avatar $name";
}
```
| Uses | Description |
| --- | --- |
| [get\_avatar()](../../functions/get_avatar) wp-includes/pluggable.php | Retrieves the avatar `<img>` tag for a user, email address, MD5 hash, comment, or post. |
| [get\_comment()](../../functions/get_comment) wp-includes/comment.php | Retrieves comment data given a comment ID or comment object. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Comments_List_Table::get_views() WP\_Comments\_List\_Table::get\_views()
=======================================
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
protected function get_views() {
global $post_id, $comment_status, $comment_type;
$status_links = array();
$num_comments = ( $post_id ) ? wp_count_comments( $post_id ) : wp_count_comments();
$stati = array(
/* translators: %s: Number of comments. */
'all' => _nx_noop(
'All <span class="count">(%s)</span>',
'All <span class="count">(%s)</span>',
'comments'
), // Singular not used.
/* translators: %s: Number of comments. */
'mine' => _nx_noop(
'Mine <span class="count">(%s)</span>',
'Mine <span class="count">(%s)</span>',
'comments'
),
/* translators: %s: Number of comments. */
'moderated' => _nx_noop(
'Pending <span class="count">(%s)</span>',
'Pending <span class="count">(%s)</span>',
'comments'
),
/* translators: %s: Number of comments. */
'approved' => _nx_noop(
'Approved <span class="count">(%s)</span>',
'Approved <span class="count">(%s)</span>',
'comments'
),
/* translators: %s: Number of comments. */
'spam' => _nx_noop(
'Spam <span class="count">(%s)</span>',
'Spam <span class="count">(%s)</span>',
'comments'
),
/* translators: %s: Number of comments. */
'trash' => _nx_noop(
'Trash <span class="count">(%s)</span>',
'Trash <span class="count">(%s)</span>',
'comments'
),
);
if ( ! EMPTY_TRASH_DAYS ) {
unset( $stati['trash'] );
}
$link = admin_url( 'edit-comments.php' );
if ( ! empty( $comment_type ) && 'all' !== $comment_type ) {
$link = add_query_arg( 'comment_type', $comment_type, $link );
}
foreach ( $stati as $status => $label ) {
if ( 'mine' === $status ) {
$current_user_id = get_current_user_id();
$num_comments->mine = get_comments(
array(
'post_id' => $post_id ? $post_id : 0,
'user_id' => $current_user_id,
'count' => true,
)
);
$link = add_query_arg( 'user_id', $current_user_id, $link );
} else {
$link = remove_query_arg( 'user_id', $link );
}
if ( ! isset( $num_comments->$status ) ) {
$num_comments->$status = 10;
}
$link = add_query_arg( 'comment_status', $status, $link );
if ( $post_id ) {
$link = add_query_arg( 'p', absint( $post_id ), $link );
}
/*
// I toyed with this, but decided against it. Leaving it in here in case anyone thinks it is a good idea. ~ Mark
if ( !empty( $_REQUEST['s'] ) )
$link = add_query_arg( 's', esc_attr( wp_unslash( $_REQUEST['s'] ) ), $link );
*/
$status_links[ $status ] = array(
'url' => esc_url( $link ),
'label' => sprintf(
translate_nooped_plural( $label, $num_comments->$status ),
sprintf(
'<span class="%s-count">%s</span>',
( 'moderated' === $status ) ? 'pending' : $status,
number_format_i18n( $num_comments->$status )
)
),
'current' => $status === $comment_status,
);
}
/**
* Filters the comment status links.
*
* @since 2.5.0
* @since 5.1.0 The 'Mine' link was added.
*
* @param string[] $status_links An associative array of fully-formed comment status links. Includes 'All', 'Mine',
* 'Pending', 'Approved', 'Spam', and 'Trash'.
*/
return apply_filters( 'comment_status_links', $this->get_views_links( $status_links ) );
}
```
[apply\_filters( 'comment\_status\_links', string[] $status\_links )](../../hooks/comment_status_links)
Filters the comment status links.
| Uses | Description |
| --- | --- |
| [\_nx\_noop()](../../functions/_nx_noop) wp-includes/l10n.php | Registers plural strings with gettext context in POT file, but does not translate them. |
| [translate\_nooped\_plural()](../../functions/translate_nooped_plural) wp-includes/l10n.php | Translates and returns the singular or plural form of a string that’s been registered with [\_n\_noop()](../../functions/_n_noop) or [\_nx\_noop()](../../functions/_nx_noop) . |
| [remove\_query\_arg()](../../functions/remove_query_arg) wp-includes/functions.php | Removes an item or items from a query string. |
| [wp\_count\_comments()](../../functions/wp_count_comments) wp-includes/comment.php | Retrieves the total comment counts for the whole site or a single post. |
| [get\_comments()](../../functions/get_comments) wp-includes/comment.php | Retrieves a list of comments. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
wordpress WP_Comments_List_Table::get_sortable_columns(): array WP\_Comments\_List\_Table::get\_sortable\_columns(): array
==========================================================
array
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
protected function get_sortable_columns() {
return array(
'author' => 'comment_author',
'response' => 'comment_post_ID',
'date' => 'comment_date',
);
}
```
wordpress WP_Comments_List_Table::comment_status_dropdown( string $comment_type ) WP\_Comments\_List\_Table::comment\_status\_dropdown( string $comment\_type )
=============================================================================
Displays a comment status drop-down for filtering on the Comments list table.
`$comment_type` string Required The current comment type slug. File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
if ( ! $post_id ) {
/* translators: Column name or table row header. */
$columns['response'] = __( 'In response to' );
}
$columns['date'] = _x( 'Submitted on', 'column name' );
return $columns;
}
/**
* Displays a comment type drop-down for filtering on the Comments list table.
*
* @since 5.5.0
* @since 5.6.0 Renamed from `comment_status_dropdown()` to `comment_type_dropdown()`.
*
* @param string $comment_type The current comment type slug.
*/
protected function comment_type_dropdown( $comment_type ) {
/**
* Filters the comment types shown in the drop-down menu on the Comments list table.
*
* @since 2.7.0
*
* @param string[] $comment_types Array of comment type labels keyed by their name.
*/
$comment_types = apply_filters(
'admin_comment_types_dropdown',
array(
'comment' => __( 'Comments' ),
'pings' => __( 'Pings' ),
)
);
if ( $comment_types && is_array( $comment_types ) ) {
printf( '<label class="screen-reader-text" for="filter-by-comment-type">%s</label>', __( 'Filter by comment type' ) );
echo '<select id="filter-by-comment-type" name="comment_type">';
printf( "\t<option value=''>%s</option>", __( 'All comment types' ) );
```
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Comments_List_Table::column_comment( WP_Comment $comment ) WP\_Comments\_List\_Table::column\_comment( WP\_Comment $comment )
==================================================================
`$comment` [WP\_Comment](../wp_comment) Required The comment object. File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function column_comment( $comment ) {
echo '<div class="comment-author">';
$this->column_author( $comment );
echo '</div>';
if ( $comment->comment_parent ) {
$parent = get_comment( $comment->comment_parent );
if ( $parent ) {
$parent_link = esc_url( get_comment_link( $parent ) );
$name = get_comment_author( $parent );
printf(
/* translators: %s: Comment link. */
__( 'In reply to %s.' ),
'<a href="' . $parent_link . '">' . $name . '</a>'
);
}
}
comment_text( $comment );
if ( $this->user_can ) {
/** This filter is documented in wp-admin/includes/comment.php */
$comment_content = apply_filters( 'comment_edit_pre', $comment->comment_content );
?>
<div id="inline-<?php echo $comment->comment_ID; ?>" class="hidden">
<textarea class="comment" rows="1" cols="1"><?php echo esc_textarea( $comment_content ); ?></textarea>
<div class="author-email"><?php echo esc_html( $comment->comment_author_email ); ?></div>
<div class="author"><?php echo esc_html( $comment->comment_author ); ?></div>
<div class="author-url"><?php echo esc_url( $comment->comment_author_url ); ?></div>
<div class="comment_status"><?php echo $comment->comment_approved; ?></div>
</div>
<?php
}
}
```
[apply\_filters( 'comment\_edit\_pre', string $comment\_content )](../../hooks/comment_edit_pre)
Filters the comment content before editing.
| Uses | Description |
| --- | --- |
| [WP\_Comments\_List\_Table::column\_author()](column_author) wp-admin/includes/class-wp-comments-list-table.php | |
| [esc\_textarea()](../../functions/esc_textarea) wp-includes/formatting.php | Escaping for textarea values. |
| [get\_comment\_link()](../../functions/get_comment_link) wp-includes/comment-template.php | Retrieves the link to a given comment. |
| [comment\_text()](../../functions/comment_text) wp-includes/comment-template.php | Displays the text of the current comment. |
| [get\_comment\_author()](../../functions/get_comment_author) wp-includes/comment-template.php | Retrieves the author of the current comment. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_comment()](../../functions/get_comment) wp-includes/comment.php | Retrieves comment data given a comment ID or comment object. |
wordpress WP_Comments_List_Table::display() WP\_Comments\_List\_Table::display()
====================================
Displays the comments table.
Overrides the parent display() method to render extra comments.
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function display() {
wp_nonce_field( 'fetch-list-' . get_class( $this ), '_ajax_fetch_list_nonce' );
static $has_items;
if ( ! isset( $has_items ) ) {
$has_items = $this->has_items();
if ( $has_items ) {
$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-comment-list" data-wp-lists="list:comment">
<?php $this->display_rows_or_placeholder(); ?>
</tbody>
<tbody id="the-extra-comment-list" data-wp-lists="list:comment" style="display: none;">
<?php
/*
* Back up the items to restore after printing the extra items markup.
* The extra items may be empty, which will prevent the table nav from displaying later.
*/
$items = $this->items;
$this->items = $this->extra_items;
$this->display_rows_or_placeholder();
$this->items = $items;
?>
</tbody>
<tfoot>
<tr>
<?php $this->print_column_headers( false ); ?>
</tr>
</tfoot>
</table>
<?php
$this->display_tablenav( 'bottom' );
}
```
| Uses | Description |
| --- | --- |
| [wp\_nonce\_field()](../../functions/wp_nonce_field) wp-includes/functions.php | Retrieves or display nonce hidden field for forms. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Comments_List_Table::column_cb( WP_Comment $item ) WP\_Comments\_List\_Table::column\_cb( WP\_Comment $item )
==========================================================
`$item` [WP\_Comment](../wp_comment) Required The comment object. File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$comment = $item;
if ( $this->user_can ) {
?>
<label class="screen-reader-text" for="cb-select-<?php echo $comment->comment_ID; ?>"><?php _e( 'Select comment' ); ?></label>
<input id="cb-select-<?php echo $comment->comment_ID; ?>" type="checkbox" name="delete_comments[]" value="<?php echo $comment->comment_ID; ?>" />
<?php
}
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_Comments_List_Table::get_columns(): array WP\_Comments\_List\_Table::get\_columns(): array
================================================
array
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function get_columns() {
global $post_id;
$columns = array();
if ( $this->checkbox ) {
$columns['cb'] = '<input type="checkbox" />';
}
$columns['author'] = __( 'Author' );
$columns['comment'] = _x( 'Comment', 'column name' );
if ( ! $post_id ) {
/* translators: Column name or table row header. */
$columns['response'] = __( 'In response to' );
}
$columns['date'] = _x( 'Submitted on', 'column name' );
return $columns;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
wordpress WP_Comments_List_Table::comment_type_dropdown( string $comment_type ) WP\_Comments\_List\_Table::comment\_type\_dropdown( string $comment\_type )
===========================================================================
Displays a comment type drop-down for filtering on the Comments list table.
`$comment_type` string Required The current comment type slug. File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
protected function comment_type_dropdown( $comment_type ) {
/**
* Filters the comment types shown in the drop-down menu on the Comments list table.
*
* @since 2.7.0
*
* @param string[] $comment_types Array of comment type labels keyed by their name.
*/
$comment_types = apply_filters(
'admin_comment_types_dropdown',
array(
'comment' => __( 'Comments' ),
'pings' => __( 'Pings' ),
)
);
if ( $comment_types && is_array( $comment_types ) ) {
printf( '<label class="screen-reader-text" for="filter-by-comment-type">%s</label>', __( 'Filter by comment type' ) );
echo '<select id="filter-by-comment-type" name="comment_type">';
printf( "\t<option value=''>%s</option>", __( 'All comment types' ) );
foreach ( $comment_types as $type => $label ) {
if ( get_comments(
array(
'number' => 1,
'type' => $type,
)
) ) {
printf(
"\t<option value='%s'%s>%s</option>\n",
esc_attr( $type ),
selected( $comment_type, $type, false ),
esc_html( $label )
);
}
}
echo '</select>';
}
}
```
[apply\_filters( 'admin\_comment\_types\_dropdown', string[] $comment\_types )](../../hooks/admin_comment_types_dropdown)
Filters the comment types shown in the drop-down menu on the Comments list table.
| Uses | Description |
| --- | --- |
| [selected()](../../functions/selected) wp-includes/general-template.php | Outputs the HTML selected attribute. |
| [get\_comments()](../../functions/get_comments) wp-includes/comment.php | Retrieves a list of comments. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Comments\_List\_Table::extra\_tablenav()](extra_tablenav) wp-admin/includes/class-wp-comments-list-table.php | |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Renamed from `comment_status_dropdown()` to `comment_type_dropdown()`. |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Comments_List_Table::get_bulk_actions(): array WP\_Comments\_List\_Table::get\_bulk\_actions(): array
======================================================
array
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
protected function get_bulk_actions() {
global $comment_status;
$actions = array();
if ( in_array( $comment_status, array( 'all', 'approved' ), true ) ) {
$actions['unapprove'] = __( 'Unapprove' );
}
if ( in_array( $comment_status, array( 'all', 'moderated' ), true ) ) {
$actions['approve'] = __( 'Approve' );
}
if ( in_array( $comment_status, array( 'all', 'moderated', 'approved', 'trash' ), true ) ) {
$actions['spam'] = _x( 'Mark as spam', 'comment' );
}
if ( 'trash' === $comment_status ) {
$actions['untrash'] = __( 'Restore' );
} elseif ( 'spam' === $comment_status ) {
$actions['unspam'] = _x( 'Not spam', 'comment' );
}
if ( in_array( $comment_status, array( 'trash', 'spam' ), true ) || ! EMPTY_TRASH_DAYS ) {
$actions['delete'] = __( 'Delete permanently' );
} else {
$actions['trash'] = __( 'Move to Trash' );
}
return $actions;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| programming_docs |
wordpress WP_Comments_List_Table::column_date( WP_Comment $comment ) WP\_Comments\_List\_Table::column\_date( WP\_Comment $comment )
===============================================================
`$comment` [WP\_Comment](../wp_comment) Required The comment object. File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function column_date( $comment ) {
$submitted = sprintf(
/* translators: 1: Comment date, 2: Comment time. */
__( '%1$s at %2$s' ),
/* translators: Comment date format. See https://www.php.net/manual/datetime.format.php */
get_comment_date( __( 'Y/m/d' ), $comment ),
/* translators: Comment time format. See https://www.php.net/manual/datetime.format.php */
get_comment_date( __( 'g:i a' ), $comment )
);
echo '<div class="submitted-on">';
if ( 'approved' === wp_get_comment_status( $comment ) && ! empty( $comment->comment_post_ID ) ) {
printf(
'<a href="%s">%s</a>',
esc_url( get_comment_link( $comment ) ),
$submitted
);
} else {
echo $submitted;
}
echo '</div>';
}
```
| Uses | Description |
| --- | --- |
| [get\_comment\_link()](../../functions/get_comment_link) wp-includes/comment-template.php | Retrieves the link to a given comment. |
| [get\_comment\_date()](../../functions/get_comment_date) wp-includes/comment-template.php | Retrieves the comment date of the current comment. |
| [wp\_get\_comment\_status()](../../functions/wp_get_comment_status) wp-includes/comment.php | Retrieves the status of a comment by comment ID. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
wordpress WP_Comments_List_Table::__construct( array $args = array() ) WP\_Comments\_List\_Table::\_\_construct( array $args = array() )
=================================================================
Constructor.
* [WP\_List\_Table::\_\_construct()](../wp_list_table/__construct): for more information on default arguments.
`$args` array Optional An associative array of arguments. Default: `array()`
File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function __construct( $args = array() ) {
global $post_id;
$post_id = isset( $_REQUEST['p'] ) ? absint( $_REQUEST['p'] ) : 0;
if ( get_option( 'show_avatars' ) ) {
add_filter( 'comment_author', array( $this, 'floated_admin_avatar' ), 10, 2 );
}
parent::__construct(
array(
'plural' => 'comments',
'singular' => 'comment',
'ajax' => true,
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_List\_Table::\_\_construct()](../wp_list_table/__construct) wp-admin/includes/class-wp-list-table.php | Constructor. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Comments_List_Table::column_default( WP_Comment $item, string $column_name ) WP\_Comments\_List\_Table::column\_default( WP\_Comment $item, string $column\_name )
=====================================================================================
`$item` [WP\_Comment](../wp_comment) Required The comment object. `$column_name` string Required The custom column's name. File: `wp-admin/includes/class-wp-comments-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-comments-list-table.php/)
```
public function column_default( $item, $column_name ) {
/**
* Fires when the default column output is displayed for a single row.
*
* @since 2.8.0
*
* @param string $column_name The custom column's name.
* @param string $comment_id The comment ID as a numeric string.
*/
do_action( 'manage_comments_custom_column', $column_name, $item->comment_ID );
}
```
[do\_action( 'manage\_comments\_custom\_column', string $column\_name, string $comment\_id )](../../hooks/manage_comments_custom_column)
Fires when the default column output is displayed for a single row.
| Uses | Description |
| --- | --- |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_Term_Query::parse_order( string $order ): string WP\_Term\_Query::parse\_order( string $order ): string
======================================================
Parse an ‘order’ query variable and cast it to ASC or DESC as necessary.
`$order` string Required The `'order'` query variable. string The sanitized `'order'` query variable.
File: `wp-includes/class-wp-term-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-term-query.php/)
```
protected function parse_order( $order ) {
if ( ! is_string( $order ) || empty( $order ) ) {
return 'DESC';
}
if ( 'ASC' === strtoupper( $order ) ) {
return 'ASC';
} else {
return 'DESC';
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Term\_Query::get\_terms()](get_terms) wp-includes/class-wp-term-query.php | Retrieves the query results. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Term_Query::parse_orderby_meta( string $orderby_raw ): string WP\_Term\_Query::parse\_orderby\_meta( string $orderby\_raw ): string
=====================================================================
Generate the ORDER BY clause for an ‘orderby’ param that is potentially related to a meta query.
`$orderby_raw` string Required Raw `'orderby'` value passed to [WP\_Term\_Query](../wp_term_query). string ORDER BY clause.
File: `wp-includes/class-wp-term-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-term-query.php/)
```
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;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Term\_Query::parse\_orderby()](parse_orderby) wp-includes/class-wp-term-query.php | Parse and sanitize ‘orderby’ keys passed to the term query. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Term_Query::parse_orderby( string $orderby_raw ): string|false WP\_Term\_Query::parse\_orderby( string $orderby\_raw ): string|false
=====================================================================
Parse and sanitize ‘orderby’ keys passed to the term query.
`$orderby_raw` string Required Alias for the field to order by. string|false Value to used in the ORDER clause. False otherwise.
File: `wp-includes/class-wp-term-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-term-query.php/)
```
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;
}
```
[apply\_filters( 'get\_terms\_orderby', string $orderby, array $args, string[] $taxonomies )](../../hooks/get_terms_orderby)
Filters the ORDERBY clause of the terms query.
| Uses | Description |
| --- | --- |
| [WP\_Term\_Query::parse\_orderby\_meta()](parse_orderby_meta) wp-includes/class-wp-term-query.php | Generate the ORDER BY clause for an ‘orderby’ param that is potentially related to a meta query. |
| [wp\_parse\_id\_list()](../../functions/wp_parse_id_list) wp-includes/functions.php | Cleans up an array, comma- or space-separated list of IDs. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Term\_Query::get\_terms()](get_terms) wp-includes/class-wp-term-query.php | Retrieves the query results. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Term_Query::query( string|array $query ): WP_Term[]|int[]|string[]|string WP\_Term\_Query::query( string|array $query ): WP\_Term[]|int[]|string[]|string
===============================================================================
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()](get_terms) for details.
`$query` string|array Required Array or URL query string of parameters. [WP\_Term](../wp_term)[]|int[]|string[]|string Array of terms, or number of terms as numeric string when `'count'` is passed as a query var.
File: `wp-includes/class-wp-term-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-term-query.php/)
```
public function query( $query ) {
$this->query_vars = wp_parse_args( $query );
return $this->get_terms();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Term\_Query::get\_terms()](get_terms) wp-includes/class-wp-term-query.php | Retrieves the query results. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Used By | Description |
| --- | --- |
| [WP\_Term\_Query::\_\_construct()](__construct) wp-includes/class-wp-term-query.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Term_Query::parse_query( string|array $query = '' ) WP\_Term\_Query::parse\_query( string|array $query = '' )
=========================================================
Parse arguments passed to the term query with default query parameters.
`$query` string|array Optional [WP\_Term\_Query](../wp_term_query) arguments. See [WP\_Term\_Query::\_\_construct()](__construct) More Arguments from WP\_Term\_Query::\_\_construct( ... $query ) Array or query string of term query parameters.
* `taxonomy`string|string[]Taxonomy name, or array of taxonomy names, to which results should be limited.
* `object_ids`int|int[]Object ID, or array of object IDs. Results will be limited to terms associated with these objects.
* `orderby`stringField(s) to order terms by. Accepts:
+ Term fields (`'name'`, `'slug'`, `'term_group'`, `'term_id'`, `'id'`, `'description'`, `'parent'`, `'term_order'`). Unless `$object_ids` is not empty, `'term_order'` is treated the same as `'term_id'`.
+ `'count'` to use the number of objects associated with the term.
+ `'include'` to match the `'order'` of the `$include` param.
+ `'slug__in'` to match the `'order'` of the `$slug` param.
+ `'meta_value'`
+ `'meta_value_num'`.
+ The value of `$meta_key`.
+ The array keys of `$meta_query`.
+ `'none'` to omit the ORDER BY clause. Default `'name'`.
* `order`stringWhether to order terms in ascending or descending order.
Accepts `'ASC'` (ascending) or `'DESC'` (descending).
Default `'ASC'`.
* `hide_empty`bool|intWhether to hide terms not assigned to any posts. Accepts `1|true` or `0|false`. Default `1|true`.
* `include`int[]|stringArray or comma/space-separated string of term IDs to include.
Default empty array.
* `exclude`int[]|stringArray or comma/space-separated string of term IDs to exclude.
If `$include` is non-empty, `$exclude` is ignored.
Default empty array.
* `exclude_tree`int[]|stringArray or comma/space-separated string of term IDs to exclude along with all of their descendant terms. If `$include` is non-empty, `$exclude_tree` is ignored. Default empty array.
* `number`int|stringMaximum number of terms to return. Accepts ``''`|0` (all) or any positive number. Default ``''`|0` (all). Note that `$number` may not return accurate results when coupled with `$object_ids`.
See #41796 for details.
* `offset`intThe number by which to offset the terms query.
* `fields`stringTerm fields to query for. Accepts:
+ `'all'` Returns an array of complete term objects (`WP_Term[]`).
+ `'all_with_object_id'` Returns an array of term objects with the `'object_id'` param (`WP_Term[]`). Works only when the `$object_ids` parameter is populated.
+ `'ids'` Returns an array of term IDs (`int[]`).
+ `'tt_ids'` Returns an array of term taxonomy IDs (`int[]`).
+ `'names'` Returns an array of term names (`string[]`).
+ `'slugs'` Returns an array of term slugs (`string[]`).
+ `'count'` Returns the number of matching terms (`int`).
+ `'id=>parent'` Returns an associative array of parent term IDs, keyed by term ID (`int[]`).
+ `'id=>name'` Returns an associative array of term names, keyed by term ID (`string[]`).
+ `'id=>slug'` Returns an associative array of term slugs, keyed by term ID (`string[]`). Default `'all'`.
* `count`boolWhether to return a term count. If true, will take precedence over `$fields`. Default false.
* `name`string|string[]Name or array of names to return term(s) for.
* `slug`string|string[]Slug or array of slugs to return term(s) for.
* `term_taxonomy_id`int|int[]Term taxonomy ID, or array of term taxonomy IDs, to match when querying terms.
* `hierarchical`boolWhether to include terms that have non-empty descendants (even if `$hide_empty` is set to true). Default true.
* `search`stringSearch criteria to match terms. Will be SQL-formatted with wildcards before and after.
* `name__like`stringRetrieve terms with criteria by which a term is LIKE `$name__like`.
* `description__like`stringRetrieve terms where the description is LIKE `$description__like`.
* `pad_counts`boolWhether to pad the quantity of a term's children in the quantity of each term's "count" object variable. Default false.
* `get`stringWhether to return terms regardless of ancestry or whether the terms are empty. Accepts `'all'` or `''` (disabled). Default `''`.
* `child_of`intTerm ID to retrieve child terms of. If multiple taxonomies are passed, `$child_of` is ignored. Default 0.
* `parent`intParent term ID to retrieve direct-child terms of.
* `childless`boolTrue to limit results to terms that have no children.
This parameter has no effect on non-hierarchical taxonomies.
Default false.
* `cache_domain`stringUnique cache key to be produced when this query is stored in an object cache. Default `'core'`.
* `update_term_meta_cache`boolWhether to prime meta caches for matched terms. Default true.
* `meta_key`string|string[]Meta key or keys to filter by.
* `meta_value`string|string[]Meta value or values to filter by.
* `meta_compare`stringMySQL operator used for comparing the meta value.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_compare_key`stringMySQL operator used for comparing the meta key.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_type`stringMySQL data type that the meta\_value column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_type_key`stringMySQL data type that the meta\_key column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_query`arrayAn associative array of [WP\_Meta\_Query](../wp_meta_query) arguments.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values.
Default: `''`
File: `wp-includes/class-wp-term-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-term-query.php/)
```
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 );
}
```
[apply\_filters( 'get\_terms\_defaults', array $defaults, string[] $taxonomies )](../../hooks/get_terms_defaults)
Filters the terms query default arguments.
[do\_action( 'parse\_term\_query', WP\_Term\_Query $query )](../../hooks/parse_term_query)
Fires after term query vars have been parsed.
| Uses | Description |
| --- | --- |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Term\_Query::get\_terms()](get_terms) wp-includes/class-wp-term-query.php | Retrieves the query results. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
| programming_docs |
wordpress WP_Term_Query::get_search_sql( string $search ): string WP\_Term\_Query::get\_search\_sql( string $search ): string
===========================================================
Used internally to generate a SQL string related to the ‘search’ parameter.
`$search` string Required Search string. string Search SQL.
File: `wp-includes/class-wp-term-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-term-query.php/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [wpdb::esc\_like()](../wpdb/esc_like) wp-includes/class-wpdb.php | First half of escaping for `LIKE` special characters `%` and `_` before preparing for SQL. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_Term\_Query::get\_terms()](get_terms) wp-includes/class-wp-term-query.php | Retrieves the query results. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Term_Query::__construct( string|array $query = '' ) WP\_Term\_Query::\_\_construct( string|array $query = '' )
==========================================================
Constructor.
Sets up the term query, based on the query vars passed.
`$query` string|array Optional Array or query string of term query parameters.
* `taxonomy`string|string[]Taxonomy name, or array of taxonomy names, to which results should be limited.
* `object_ids`int|int[]Object ID, or array of object IDs. Results will be limited to terms associated with these objects.
* `orderby`stringField(s) to order terms by. Accepts:
+ Term fields (`'name'`, `'slug'`, `'term_group'`, `'term_id'`, `'id'`, `'description'`, `'parent'`, `'term_order'`). Unless `$object_ids` is not empty, `'term_order'` is treated the same as `'term_id'`.
+ `'count'` to use the number of objects associated with the term.
+ `'include'` to match the `'order'` of the `$include` param.
+ `'slug__in'` to match the `'order'` of the `$slug` param.
+ `'meta_value'`
+ `'meta_value_num'`.
+ The value of `$meta_key`.
+ The array keys of `$meta_query`.
+ `'none'` to omit the ORDER BY clause. Default `'name'`.
* `order`stringWhether to order terms in ascending or descending order.
Accepts `'ASC'` (ascending) or `'DESC'` (descending).
Default `'ASC'`.
* `hide_empty`bool|intWhether to hide terms not assigned to any posts. Accepts `1|true` or `0|false`. Default `1|true`.
* `include`int[]|stringArray or comma/space-separated string of term IDs to include.
Default empty array.
* `exclude`int[]|stringArray or comma/space-separated string of term IDs to exclude.
If `$include` is non-empty, `$exclude` is ignored.
Default empty array.
* `exclude_tree`int[]|stringArray or comma/space-separated string of term IDs to exclude along with all of their descendant terms. If `$include` is non-empty, `$exclude_tree` is ignored. Default empty array.
* `number`int|stringMaximum number of terms to return. Accepts ``''`|0` (all) or any positive number. Default ``''`|0` (all). Note that `$number` may not return accurate results when coupled with `$object_ids`.
See #41796 for details.
* `offset`intThe number by which to offset the terms query.
* `fields`stringTerm fields to query for. Accepts:
+ `'all'` Returns an array of complete term objects (`WP_Term[]`).
+ `'all_with_object_id'` Returns an array of term objects with the `'object_id'` param (`WP_Term[]`). Works only when the `$object_ids` parameter is populated.
+ `'ids'` Returns an array of term IDs (`int[]`).
+ `'tt_ids'` Returns an array of term taxonomy IDs (`int[]`).
+ `'names'` Returns an array of term names (`string[]`).
+ `'slugs'` Returns an array of term slugs (`string[]`).
+ `'count'` Returns the number of matching terms (`int`).
+ `'id=>parent'` Returns an associative array of parent term IDs, keyed by term ID (`int[]`).
+ `'id=>name'` Returns an associative array of term names, keyed by term ID (`string[]`).
+ `'id=>slug'` Returns an associative array of term slugs, keyed by term ID (`string[]`). Default `'all'`.
* `count`boolWhether to return a term count. If true, will take precedence over `$fields`. Default false.
* `name`string|string[]Name or array of names to return term(s) for.
* `slug`string|string[]Slug or array of slugs to return term(s) for.
* `term_taxonomy_id`int|int[]Term taxonomy ID, or array of term taxonomy IDs, to match when querying terms.
* `hierarchical`boolWhether to include terms that have non-empty descendants (even if `$hide_empty` is set to true). Default true.
* `search`stringSearch criteria to match terms. Will be SQL-formatted with wildcards before and after.
* `name__like`stringRetrieve terms with criteria by which a term is LIKE `$name__like`.
* `description__like`stringRetrieve terms where the description is LIKE `$description__like`.
* `pad_counts`boolWhether to pad the quantity of a term's children in the quantity of each term's "count" object variable. Default false.
* `get`stringWhether to return terms regardless of ancestry or whether the terms are empty. Accepts `'all'` or `''` (disabled). Default `''`.
* `child_of`intTerm ID to retrieve child terms of. If multiple taxonomies are passed, `$child_of` is ignored. Default 0.
* `parent`intParent term ID to retrieve direct-child terms of.
* `childless`boolTrue to limit results to terms that have no children.
This parameter has no effect on non-hierarchical taxonomies.
Default false.
* `cache_domain`stringUnique cache key to be produced when this query is stored in an object cache. Default `'core'`.
* `update_term_meta_cache`boolWhether to prime meta caches for matched terms. Default true.
* `meta_key`string|string[]Meta key or keys to filter by.
* `meta_value`string|string[]Meta value or values to filter by.
* `meta_compare`stringMySQL operator used for comparing the meta value.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_compare_key`stringMySQL operator used for comparing the meta key.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_type`stringMySQL data type that the meta\_value column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_type_key`stringMySQL data type that the meta\_key column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_query`arrayAn associative array of [WP\_Meta\_Query](../wp_meta_query) arguments.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values.
Default: `''`
File: `wp-includes/class-wp-term-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-term-query.php/)
```
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 );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Term\_Query::query()](query) wp-includes/class-wp-term-query.php | Sets up the query and retrieves the results. |
| Used By | Description |
| --- | --- |
| [\_wp\_build\_title\_and\_description\_for\_taxonomy\_block\_template()](../../functions/_wp_build_title_and_description_for_taxonomy_block_template) wp-includes/block-template-utils.php | Builds the title and description of a taxonomy-specific template based on the underlying entity referenced. |
| [WP\_REST\_Term\_Search\_Handler::search\_items()](../wp_rest_term_search_handler/search_items) wp-includes/rest-api/search/class-wp-rest-term-search-handler.php | Searches the object type content for a given search request. |
| [WP\_Sitemaps\_Taxonomies::get\_url\_list()](../wp_sitemaps_taxonomies/get_url_list) wp-includes/sitemaps/providers/class-wp-sitemaps-taxonomies.php | Gets a URL list for a taxonomy sitemap. |
| [WP\_Tax\_Query::transform\_query()](../wp_tax_query/transform_query) wp-includes/class-wp-tax-query.php | Transforms a single query, from one field to another. |
| [get\_terms()](../../functions/get_terms) wp-includes/taxonomy.php | Retrieves the terms in a given taxonomy or list of taxonomies. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced the `'meta_type_key'` parameter. |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | Introduced the `'meta_compare_key'` parameter. |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Added `'slug__in'` support for `'orderby'`. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced `'object_ids'` parameter. |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Term_Query::format_terms( WP_Term[] $term_objects, string $_fields ): WP_Term[]|int[]|string[] WP\_Term\_Query::format\_terms( WP\_Term[] $term\_objects, string $\_fields ): WP\_Term[]|int[]|string[]
========================================================================================================
Format response depending on field requested.
`$term_objects` [WP\_Term](../wp_term)[] Required Array of term objects. `$_fields` string Required Field to format. [WP\_Term](../wp_term)[]|int[]|string[] Array of terms / strings / ints depending on field requested.
File: `wp-includes/class-wp-term-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-term-query.php/)
```
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;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Term\_Query::get\_terms()](get_terms) wp-includes/class-wp-term-query.php | Retrieves the query results. |
| Version | Description |
| --- | --- |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Introduced. |
wordpress WP_Term_Query::populate_terms( Object[]|int[] $terms ): WP_Term[] WP\_Term\_Query::populate\_terms( Object[]|int[] $terms ): WP\_Term[]
=====================================================================
Creates an array of term objects from an array of term IDs.
Also discards invalid term objects.
`$terms` Object[]|int[] Required List of objects or term ids. [WP\_Term](../wp_term)[] Array of `WP_Term` objects.
File: `wp-includes/class-wp-term-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-term-query.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [get\_term()](../../functions/get_term) wp-includes/taxonomy.php | Gets all term data from database by term ID. |
| Used By | Description |
| --- | --- |
| [WP\_Term\_Query::get\_terms()](get_terms) wp-includes/class-wp-term-query.php | Retrieves the query results. |
| Version | Description |
| --- | --- |
| [4.9.8](https://developer.wordpress.org/reference/since/4.9.8/) | Introduced. |
wordpress WP_Term_Query::get_terms(): WP_Term[]|int[]|string[]|string WP\_Term\_Query::get\_terms(): WP\_Term[]|int[]|string[]|string
===============================================================
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’
[WP\_Term](../wp_term)[]|int[]|string[]|string Array of terms, or number of terms as numeric string when `'count'` is passed as a query var.
File: `wp-includes/class-wp-term-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-term-query.php/)
```
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;
}
```
[apply\_filters( 'get\_terms\_args', array $args, string[] $taxonomies )](../../hooks/get_terms_args)
Filters the terms query arguments.
[apply\_filters( 'get\_terms\_fields', string[] $selects, array $args, string[] $taxonomies )](../../hooks/get_terms_fields)
Filters the fields to select in the terms query.
[apply\_filters( 'list\_terms\_exclusions', string $exclusions, array $args, string[] $taxonomies )](../../hooks/list_terms_exclusions)
Filters the terms to exclude from the terms query.
[do\_action\_ref\_array( 'pre\_get\_terms', WP\_Term\_Query $query )](../../hooks/pre_get_terms)
Fires before terms are retrieved.
[apply\_filters( 'terms\_clauses', string[] $clauses, string[] $taxonomies, array $args )](../../hooks/terms_clauses)
Filters the terms query SQL clauses.
[apply\_filters\_ref\_array( 'terms\_pre\_query', array|null $terms, WP\_Term\_Query $query )](../../hooks/terms_pre_query)
Filters the terms array before the query takes place.
| Uses | Description |
| --- | --- |
| [WP\_Term\_Query::format\_terms()](format_terms) wp-includes/class-wp-term-query.php | Format response depending on field requested. |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| [apply\_filters\_ref\_array()](../../functions/apply_filters_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook, specifying arguments in an array. |
| [do\_action\_ref\_array()](../../functions/do_action_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook, specifying arguments in an array. |
| [is\_taxonomy\_hierarchical()](../../functions/is_taxonomy_hierarchical) wp-includes/taxonomy.php | Determines whether the taxonomy object is hierarchical. |
| [get\_term\_children()](../../functions/get_term_children) wp-includes/taxonomy.php | Merges all term children into a single array of their IDs. |
| [sanitize\_term\_field()](../../functions/sanitize_term_field) wp-includes/taxonomy.php | Sanitizes the field value in the term based on the context. |
| [get\_terms()](../../functions/get_terms) wp-includes/taxonomy.php | Retrieves the terms in a given taxonomy or list of taxonomies. |
| [\_pad\_term\_counts()](../../functions/_pad_term_counts) wp-includes/taxonomy.php | Adds count of children to parent count. |
| [\_get\_term\_children()](../../functions/_get_term_children) wp-includes/taxonomy.php | Gets the subset of $terms that are descendants of $term\_id. |
| [\_get\_term\_hierarchy()](../../functions/_get_term_hierarchy) wp-includes/taxonomy.php | Retrieves children of taxonomy as term IDs. |
| [WP\_Term\_Query::populate\_terms()](populate_terms) wp-includes/class-wp-term-query.php | Creates an array of term objects from an array of term IDs. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [wp\_parse\_id\_list()](../../functions/wp_parse_id_list) wp-includes/functions.php | Cleans up an array, comma- or space-separated list of IDs. |
| [WP\_Term\_Query::parse\_query()](parse_query) wp-includes/class-wp-term-query.php | Parse arguments passed to the term query with default query parameters. |
| [wp\_cache\_get\_last\_changed()](../../functions/wp_cache_get_last_changed) wp-includes/functions.php | Gets last changed date for the specified cache group. |
| [WP\_Term\_Query::parse\_order()](parse_order) wp-includes/class-wp-term-query.php | Parse an ‘order’ query variable and cast it to ASC or DESC as necessary. |
| [wp\_cache\_add()](../../functions/wp_cache_add) wp-includes/cache.php | Adds data to the cache, if the cache key doesn’t already exist. |
| [WP\_Term\_Query::parse\_orderby()](parse_orderby) wp-includes/class-wp-term-query.php | Parse and sanitize ‘orderby’ keys passed to the term query. |
| [WP\_Term\_Query::get\_search\_sql()](get_search_sql) wp-includes/class-wp-term-query.php | Used internally to generate a SQL string related to the ‘search’ parameter. |
| [\_prime\_term\_caches()](../../functions/_prime_term_caches) wp-includes/taxonomy.php | Adds any terms from the given IDs to the cache that do not already exist in cache. |
| [update\_termmeta\_cache()](../../functions/update_termmeta_cache) wp-includes/taxonomy.php | Updates metadata cache for list of term IDs. |
| [wpdb::esc\_like()](../wpdb/esc_like) wp-includes/class-wpdb.php | First half of escaping for `LIKE` special characters `%` and `_` before preparing for SQL. |
| [wp\_cache\_set()](../../functions/wp_cache_set) wp-includes/cache.php | Saves the data to the cache. |
| [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) wp-includes/class-wp-meta-query.php | Constructor. |
| [get\_term()](../../functions/get_term) wp-includes/taxonomy.php | Gets all term data from database by term ID. |
| [wp\_cache\_get()](../../functions/wp_cache_get) wp-includes/cache.php | Retrieves the cache contents from the cache by key and group. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [wpdb::get\_var()](../wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| [wpdb::get\_results()](../wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_Term\_Query::query()](query) wp-includes/class-wp-term-query.php | Sets up the query and retrieves the results. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::set_changeset_lock( int $changeset_post_id, bool $take_over = false ) WP\_Customize\_Manager::set\_changeset\_lock( int $changeset\_post\_id, bool $take\_over = false )
==================================================================================================
Marks the changeset post as being currently edited by the current user.
`$changeset_post_id` int Required Changeset post ID. `$take_over` bool Optional Whether to take over the changeset. Default: `false`
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 );
}
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::refresh\_changeset\_lock()](refresh_changeset_lock) wp-includes/class-wp-customize-manager.php | Refreshes changeset lock with the current time if current user edited the changeset before. |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [get\_post\_meta()](../../functions/get_post_meta) wp-includes/post.php | Retrieves a post meta field for the given post ID. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::handle\_override\_changeset\_lock\_request()](handle_override_changeset_lock_request) wp-includes/class-wp-customize-manager.php | Removes changeset lock when take over request is sent via Ajax. |
| [WP\_Customize\_Manager::establish\_loaded\_changeset()](establish_loaded_changeset) wp-includes/class-wp-customize-manager.php | Establishes the loaded changeset. |
| [WP\_Customize\_Manager::save()](save) wp-includes/class-wp-customize-manager.php | Handles customize\_save WP Ajax request to save/update a changeset. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Manager::wp_redirect_status( int $status ): int WP\_Customize\_Manager::wp\_redirect\_status( int $status ): int
================================================================
This method has been deprecated.
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.
`$status` int Required Status. int
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function wp_redirect_status( $status ) {
_deprecated_function( __FUNCTION__, '4.7.0' );
if ( $this->is_preview() && ! is_admin() ) {
return 200;
}
return $status;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::is\_preview()](is_preview) wp-includes/class-wp-customize-manager.php | Determines whether it is a theme preview or not. |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | This method has been deprecated. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::get_nonces(): array WP\_Customize\_Manager::get\_nonces(): array
============================================
Gets nonces for the Customizer.
array Nonces.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
[apply\_filters( 'customize\_refresh\_nonces', string[] $nonces, WP\_Customize\_Manager $manager )](../../hooks/customize_refresh_nonces)
Filters nonces for Customizer.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet name of the previewed theme. |
| [wp\_create\_nonce()](../../functions/wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Customize\_Manager::refresh\_nonces()](refresh_nonces) wp-includes/class-wp-customize-manager.php | Refreshes nonces for the current preview. |
| [WP\_Customize\_Manager::customize\_preview\_settings()](customize_preview_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for preview frame. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Manager::export_header_video_settings( array $response, WP_Customize_Selective_Refresh $selective_refresh, array $partials ): array WP\_Customize\_Manager::export\_header\_video\_settings( array $response, WP\_Customize\_Selective\_Refresh $selective\_refresh, array $partials ): array
=========================================================================================================================================================
Exports header video settings to facilitate selective refresh.
`$response` array Required Response. `$selective_refresh` [WP\_Customize\_Selective\_Refresh](../wp_customize_selective_refresh) Required Selective refresh component. `$partials` array Required Array of partials. array
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [get\_header\_video\_settings()](../../functions/get_header_video_settings) wp-includes/theme.php | Retrieves header video settings. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::refresh_nonces() WP\_Customize\_Manager::refresh\_nonces()
=========================================
Refreshes nonces for the current preview.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function refresh_nonces() {
if ( ! $this->is_preview() ) {
wp_send_json_error( 'not_preview' );
}
wp_send_json_success( $this->get_nonces() );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_nonces()](get_nonces) wp-includes/class-wp-customize-manager.php | Gets nonces for the Customizer. |
| [WP\_Customize\_Manager::is\_preview()](is_preview) wp-includes/class-wp-customize-manager.php | Determines whether it is a theme preview or not. |
| [wp\_send\_json\_error()](../../functions/wp_send_json_error) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating failure. |
| [wp\_send\_json\_success()](../../functions/wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_Customize_Manager::set_return_url( string $return_url ) WP\_Customize\_Manager::set\_return\_url( string $return\_url )
===============================================================
Sets URL to link the user to when closing the Customizer.
URL is validated.
`$return_url` string Required URL for return link. File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [wp\_removable\_query\_args()](../../functions/wp_removable_query_args) wp-includes/functions.php | Returns an array of single-use query variable names that can be removed from a URL. |
| [wp\_validate\_redirect()](../../functions/wp_validate_redirect) wp-includes/pluggable.php | Validates a URL for use in a redirect. |
| [sanitize\_url()](../../functions/sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| [remove\_query\_arg()](../../functions/remove_query_arg) wp-includes/functions.php | Removes an item or items from a query string. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Customize_Manager::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.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::dismiss\_user\_auto\_draft\_changesets()](dismiss_user_auto_draft_changesets) wp-includes/class-wp-customize-manager.php | Dismisses all of the current user’s auto-drafts (other than the present one). |
| [WP\_Customize\_Manager::changeset\_post\_id()](changeset_post_id) wp-includes/class-wp-customize-manager.php | Gets the changeset post ID for the loaded changeset. |
| [WP\_Customize\_Manager::is\_preview()](is_preview) wp-includes/class-wp-customize-manager.php | Determines whether it is a theme preview or not. |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [delete\_post\_meta()](../../functions/delete_post_meta) wp-includes/post.php | Deletes a post meta field for the given post ID. |
| [get\_post\_status()](../../functions/get_post_status) wp-includes/post.php | Retrieves the post status based on the post ID. |
| [wp\_get\_post\_autosave()](../../functions/wp_get_post_autosave) wp-includes/revision.php | Retrieves the autosaved data of the specified post. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [is\_user\_logged\_in()](../../functions/is_user_logged_in) wp-includes/pluggable.php | Determines whether the current visitor is a logged in user. |
| [check\_ajax\_referer()](../../functions/check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [wp\_send\_json\_error()](../../functions/wp_send_json_error) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating failure. |
| [wp\_send\_json\_success()](../../functions/wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Manager::wp_die( string|WP_Error $ajax_message, string $message = null ) WP\_Customize\_Manager::wp\_die( string|WP\_Error $ajax\_message, string $message = null )
==========================================================================================
Custom wp\_die wrapper. Returns either the standard message for UI or the Ajax message.
`$ajax_message` string|[WP\_Error](../wp_error) Required Ajax return. `$message` string Optional UI message. Default: `null`
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::doing\_ajax()](doing_ajax) wp-includes/class-wp-customize-manager.php | Returns true if it’s an Ajax request. |
| [wp\_customize\_url()](../../functions/wp_customize_url) wp-includes/theme.php | Returns a URL to load the Customizer. |
| [wp\_print\_scripts()](../../functions/wp_print_scripts) wp-includes/functions.wp-scripts.php | Prints scripts in document head that are in the $handles queue. |
| [wp\_enqueue\_scripts()](../../functions/wp_enqueue_scripts) wp-includes/script-loader.php | Wrapper for do\_action( ‘wp\_enqueue\_scripts’ ). |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::customize\_preview\_init()](customize_preview_init) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings. |
| [WP\_Customize\_Manager::setup\_theme()](setup_theme) wp-includes/class-wp-customize-manager.php | Starts preview and customize theme. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::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
* [add\_dynamic\_settings()](../../functions/add_dynamic_settings)
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function register_dynamic_settings() {
$setting_ids = array_keys( $this->unsanitized_post_values() );
$this->add_dynamic_settings( $setting_ids );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::add\_dynamic\_settings()](add_dynamic_settings) wp-includes/class-wp-customize-manager.php | Registers any dynamically-created settings, such as those from $\_POST[‘customized’] that have no corresponding setting created. |
| [WP\_Customize\_Manager::unsanitized\_post\_values()](unsanitized_post_values) wp-includes/class-wp-customize-manager.php | Gets dirty pre-sanitized setting values in the current customized state. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::customize_preview_settings() WP\_Customize\_Manager::customize\_preview\_settings()
======================================================
Prints JavaScript settings for preview frame.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::autosaved()](autosaved) wp-includes/class-wp-customize-manager.php | Gets whether data from a changeset’s autosaved revision should be loaded if it exists. |
| [wp\_parse\_url()](../../functions/wp_parse_url) wp-includes/http.php | A wrapper for PHP’s parse\_url() function that handles consistency in the return values across PHP versions. |
| [remove\_query\_arg()](../../functions/remove_query_arg) wp-includes/functions.php | Removes an item or items from a query string. |
| [sanitize\_url()](../../functions/sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| [WP\_Customize\_Manager::is\_theme\_active()](is_theme_active) wp-includes/class-wp-customize-manager.php | Checks if the current theme is active. |
| [WP\_Customize\_Manager::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet name of the previewed theme. |
| [restore\_previous\_locale()](../../functions/restore_previous_locale) wp-includes/l10n.php | Restores the translations according to the previous locale. |
| [WP\_Customize\_Manager::unsanitized\_post\_values()](unsanitized_post_values) wp-includes/class-wp-customize-manager.php | Gets dirty pre-sanitized setting values in the current customized state. |
| [WP\_Customize\_Manager::get\_nonces()](get_nonces) wp-includes/class-wp-customize-manager.php | Gets nonces for the Customizer. |
| [WP\_Customize\_Manager::validate\_setting\_values()](validate_setting_values) wp-includes/class-wp-customize-manager.php | Validates setting values. |
| [WP\_Customize\_Manager::changeset\_uuid()](changeset_uuid) wp-includes/class-wp-customize-manager.php | Gets the changeset UUID. |
| [WP\_Customize\_Manager::is\_cross\_domain()](is_cross_domain) wp-includes/class-wp-customize-manager.php | Determines whether the admin and the frontend are on different domains. |
| [WP\_Customize\_Manager::get\_allowed\_urls()](get_allowed_urls) wp-includes/class-wp-customize-manager.php | Gets URLs allowed to be previewed. |
| [get\_user\_locale()](../../functions/get_user_locale) wp-includes/l10n.php | Retrieves the locale of a user. |
| [switch\_to\_locale()](../../functions/switch_to_locale) wp-includes/l10n.php | Switches the translations according to the given locale. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::get_panel( string $id ): WP_Customize_Panel|void WP\_Customize\_Manager::get\_panel( string $id ): WP\_Customize\_Panel|void
===========================================================================
Retrieves a customize panel.
`$id` string Required Panel ID to get. [WP\_Customize\_Panel](../wp_customize_panel)|void Requested panel instance, if set.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function get_panel( $id ) {
if ( isset( $this->panels[ $id ] ) ) {
return $this->panels[ $id ];
}
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Customize_Manager::is_preview(): bool WP\_Customize\_Manager::is\_preview(): bool
===========================================
Determines whether it is a theme preview or not.
bool True if it's a preview, false if not.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function is_preview() {
return (bool) $this->previewing;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::handle\_override\_changeset\_lock\_request()](handle_override_changeset_lock_request) wp-includes/class-wp-customize-manager.php | Removes changeset lock when take over request is sent via Ajax. |
| [WP\_Customize\_Manager::handle\_dismiss\_autosave\_or\_lock\_request()](handle_dismiss_autosave_or_lock_request) wp-includes/class-wp-customize-manager.php | Deletes a given auto-draft changeset or the autosave revision for a given changeset or delete changeset lock. |
| [WP\_Customize\_Manager::handle\_changeset\_trash\_request()](handle_changeset_trash_request) wp-includes/class-wp-customize-manager.php | Handles request to trash a changeset. |
| [WP\_Customize\_Manager::refresh\_nonces()](refresh_nonces) wp-includes/class-wp-customize-manager.php | Refreshes nonces for the current preview. |
| [WP\_Customize\_Manager::save()](save) wp-includes/class-wp-customize-manager.php | Handles customize\_save WP Ajax request to save/update a changeset. |
| [WP\_Customize\_Manager::start\_previewing\_theme()](start_previewing_theme) wp-includes/class-wp-customize-manager.php | If the theme to be previewed isn’t the active theme, add filter callbacks to swap it out at runtime. |
| [WP\_Customize\_Manager::stop\_previewing\_theme()](stop_previewing_theme) wp-includes/class-wp-customize-manager.php | Stops previewing the selected theme. |
| [WP\_Customize\_Manager::wp\_loaded()](wp_loaded) wp-includes/class-wp-customize-manager.php | Registers styles/scripts and initialize the preview of each setting |
| [WP\_Customize\_Manager::wp\_redirect\_status()](wp_redirect_status) wp-includes/class-wp-customize-manager.php | Prevents Ajax requests from following redirects when previewing a theme by issuing a 200 response instead of a 30x. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::handle_override_changeset_lock_request() WP\_Customize\_Manager::handle\_override\_changeset\_lock\_request()
====================================================================
Removes changeset lock when take over request is sent via Ajax.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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' );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::set\_changeset\_lock()](set_changeset_lock) wp-includes/class-wp-customize-manager.php | Marks the changeset post as being currently edited by the current user. |
| [WP\_Customize\_Manager::changeset\_post\_id()](changeset_post_id) wp-includes/class-wp-customize-manager.php | Gets the changeset post ID for the loaded changeset. |
| [WP\_Customize\_Manager::is\_preview()](is_preview) wp-includes/class-wp-customize-manager.php | Determines whether it is a theme preview or not. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [check\_ajax\_referer()](../../functions/check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [wp\_send\_json\_error()](../../functions/wp_send_json_error) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating failure. |
| [wp\_send\_json\_success()](../../functions/wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Manager::render_control_templates() WP\_Customize\_Manager::render\_control\_templates()
====================================================
Renders JS templates for all registered control types.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::branching()](branching) wp-includes/class-wp-customize-manager.php | Whether the changeset branching is allowed. |
| [esc\_html\_e()](../../functions/esc_html_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in HTML output. |
| [esc\_attr\_e()](../../functions/esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::render_panel_templates() WP\_Customize\_Manager::render\_panel\_templates()
==================================================
Renders JS templates for all registered panel types.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function render_panel_templates() {
foreach ( $this->registered_panel_types as $panel_type ) {
$panel = new $panel_type( $this, 'temp', array() );
$panel->print_template();
}
}
```
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Manager::customize_preview_override_404_status() WP\_Customize\_Manager::customize\_preview\_override\_404\_status()
===================================================================
This method has been deprecated.
Prevents sending a 404 status when returning the response for the customize preview, since it causes the jQuery Ajax to fail. Send 200 instead.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function customize_preview_override_404_status() {
_deprecated_function( __METHOD__, '4.7.0' );
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | This method has been deprecated. |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Customize_Manager::add_section( WP_Customize_Section|string $id, array $args = array() ): WP_Customize_Section WP\_Customize\_Manager::add\_section( WP\_Customize\_Section|string $id, array $args = array() ): WP\_Customize\_Section
========================================================================================================================
Adds a customize section.
* [WP\_Customize\_Section::\_\_construct()](../wp_customize_section/__construct)
`$id` [WP\_Customize\_Section](../wp_customize_section)|string Required Customize Section object, or ID. `$args` array Optional Array of properties for the new Section object.
See [WP\_Customize\_Section::\_\_construct()](../wp_customize_section/__construct) for information on accepted arguments. More Arguments from WP\_Customize\_Section::\_\_construct( ... $args ) Array of properties for the new Section object.
* `priority`intPriority of the section, defining the display order of panels and sections. Default 160.
* `panel`stringThe panel this section belongs to (if any).
* `capability`stringCapability required for the section.
Default `'edit_theme_options'`
* `theme_supports`string|string[]Theme features required to support the section.
* `title`stringTitle of the section to show in UI.
* `description`stringDescription to show in the UI.
* `type`stringType of the section.
* `active_callback`callableActive callback.
* `description_hidden`boolHide the description behind a help icon, instead of inline above the first control.
Default false.
Default: `array()`
[WP\_Customize\_Section](../wp_customize_section) The instance of the section that was added.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Section::\_\_construct()](../wp_customize_section/__construct) wp-includes/class-wp-customize-section.php | Constructor. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::register\_controls()](register_controls) wp-includes/class-wp-customize-manager.php | Registers some default controls. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Return added [WP\_Customize\_Section](../wp_customize_section) instance. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::get_allowed_urls(): array WP\_Customize\_Manager::get\_allowed\_urls(): array
===================================================
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.
array Allowed URLs.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
[apply\_filters( 'customize\_allowed\_urls', string[] $allowed\_urls )](../../hooks/customize_allowed_urls)
Filters the list of URLs allowed to be clicked and followed in the Customizer preview.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::is\_cross\_domain()](is_cross_domain) wp-includes/class-wp-customize-manager.php | Determines whether the admin and the frontend are on different domains. |
| [is\_ssl()](../../functions/is_ssl) wp-includes/load.php | Determines if SSL is used. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::add\_state\_query\_params()](add_state_query_params) wp-includes/class-wp-customize-manager.php | Adds customize state query params to a given URL if preview is allowed. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Customize\_Manager::customize\_preview\_settings()](customize_preview_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for preview frame. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::find_changeset_post_id( string $uuid ): int|null WP\_Customize\_Manager::find\_changeset\_post\_id( string $uuid ): int|null
===========================================================================
Finds the changeset post ID for a given changeset UUID.
`$uuid` string Required Changeset UUID. int|null Returns post ID on success and null on failure.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Query::\_\_construct()](../wp_query/__construct) wp-includes/class-wp-query.php | Constructor. |
| [wp\_cache\_set()](../../functions/wp_cache_set) wp-includes/cache.php | Saves the data to the cache. |
| [get\_post\_type()](../../functions/get_post_type) wp-includes/post.php | Retrieves the post type of the current post or of a given post. |
| [get\_post\_stati()](../../functions/get_post_stati) wp-includes/post.php | Gets a list of post statuses. |
| [wp\_cache\_get()](../../functions/wp_cache_get) wp-includes/cache.php | Retrieves the cache contents from the cache by key and group. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::check\_changeset\_lock\_with\_heartbeat()](check_changeset_lock_with_heartbeat) wp-includes/class-wp-customize-manager.php | Checks locked changeset with heartbeat API. |
| [WP\_Customize\_Manager::changeset\_post\_id()](changeset_post_id) wp-includes/class-wp-customize-manager.php | Gets the changeset post ID for the loaded changeset. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::get_stylesheet(): string WP\_Customize\_Manager::get\_stylesheet(): string
=================================================
Retrieves the stylesheet name of the previewed theme.
string Stylesheet name.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function get_stylesheet() {
return $this->theme()->get_stylesheet();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::theme()](theme) wp-includes/class-wp-customize-manager.php | Gets the theme being customized. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::\_publish\_changeset\_values()](_publish_changeset_values) wp-includes/class-wp-customize-manager.php | Publishes the values of a changeset. |
| [WP\_Customize\_Manager::update\_stashed\_theme\_mod\_settings()](update_stashed_theme_mod_settings) wp-includes/class-wp-customize-manager.php | Updates stashed theme mod settings. |
| [WP\_Customize\_Manager::save\_changeset\_post()](save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [WP\_Customize\_Manager::add\_state\_query\_params()](add_state_query_params) wp-includes/class-wp-customize-manager.php | Adds customize state query params to a given URL if preview is allowed. |
| [WP\_Customize\_Manager::import\_theme\_starter\_content()](import_theme_starter_content) wp-includes/class-wp-customize-manager.php | Imports theme starter content into the customized state. |
| [WP\_Customize\_Manager::get\_nonces()](get_nonces) wp-includes/class-wp-customize-manager.php | Gets nonces for the Customizer. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Customize\_Manager::unsanitized\_post\_values()](unsanitized_post_values) wp-includes/class-wp-customize-manager.php | Gets dirty pre-sanitized setting values in the current customized state. |
| [WP\_Customize\_Manager::customize\_preview\_settings()](customize_preview_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for preview frame. |
| [WP\_Customize\_Manager::get\_stylesheet\_root()](get_stylesheet_root) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet root of the previewed theme. |
| [WP\_Customize\_Manager::save()](save) wp-includes/class-wp-customize-manager.php | Handles customize\_save WP Ajax request to save/update a changeset. |
| [WP\_Customize\_Manager::setup\_theme()](setup_theme) wp-includes/class-wp-customize-manager.php | Starts preview and customize theme. |
| [WP\_Customize\_Manager::is\_theme\_active()](is_theme_active) wp-includes/class-wp-customize-manager.php | Checks if the current theme is active. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::register_section_type( string $section ) WP\_Customize\_Manager::register\_section\_type( string $section )
==================================================================
Registers a customize section type.
Registered types are eligible to be rendered via JS and created dynamically.
* [WP\_Customize\_Section](../wp_customize_section)
`$section` string Required Name of a custom section which is a subclass of [WP\_Customize\_Section](../wp_customize_section). File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function register_section_type( $section ) {
$this->registered_section_types[] = $section;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::wp\_loaded()](wp_loaded) wp-includes/class-wp-customize-manager.php | Registers styles/scripts and initialize the preview of each setting |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Manager::stop_previewing_theme() WP\_Customize\_Manager::stop\_previewing\_theme()
=================================================
Stops previewing the selected theme.
Removes filters to change the active theme.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 );
}
```
[do\_action( 'stop\_previewing\_theme', WP\_Customize\_Manager $manager )](../../hooks/stop_previewing_theme)
Fires once the Customizer theme preview has stopped.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::is\_preview()](is_preview) wp-includes/class-wp-customize-manager.php | Determines whether it is a theme preview or not. |
| [WP\_Customize\_Manager::is\_theme\_active()](is_theme_active) wp-includes/class-wp-customize-manager.php | Checks if the current theme is active. |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::save\_changeset\_post()](save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::prepare_starter_content_attachments( array $attachments ): array WP\_Customize\_Manager::prepare\_starter\_content\_attachments( array $attachments ): array
===========================================================================================
Prepares starter content attachments.
Ensure that the attachments are valid and that they have slugs and file name/path.
`$attachments` array Required Attachments. array Prepared attachments.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [get\_stylesheet\_directory()](../../functions/get_stylesheet_directory) wp-includes/theme.php | Retrieves stylesheet directory path for the active theme. |
| [get\_template\_directory()](../../functions/get_template_directory) wp-includes/theme.php | Retrieves template directory path for the active theme. |
| [is\_child\_theme()](../../functions/is_child_theme) wp-includes/theme.php | Whether a child theme is in use. |
| [sanitize\_title()](../../functions/sanitize_title) wp-includes/formatting.php | Sanitizes a string into a slug, which can be used in URLs or HTML attributes. |
| [wp\_check\_filetype()](../../functions/wp_check_filetype) wp-includes/functions.php | Retrieves the file type from the file name. |
| [wp\_basename()](../../functions/wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::import\_theme\_starter\_content()](import_theme_starter_content) wp-includes/class-wp-customize-manager.php | Imports theme starter content into the customized state. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::get_autofocus(): string[] WP\_Customize\_Manager::get\_autofocus(): string[]
==================================================
Gets the autofocused constructs.
string[] Mapping of 'panel', 'section', 'control' to the ID which should be autofocused.
* `control`stringID for control to be autofocused.
* `section`stringID for section to be autofocused.
* `panel`stringID for panel to be autofocused.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function get_autofocus() {
return $this->autofocus;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Customize_Manager::changeset_data(): array WP\_Customize\_Manager::changeset\_data(): array
================================================
Gets changeset data.
array Changeset data.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::autosaved()](autosaved) wp-includes/class-wp-customize-manager.php | Gets whether data from a changeset’s autosaved revision should be loaded if it exists. |
| [WP\_Customize\_Manager::changeset\_post\_id()](changeset_post_id) wp-includes/class-wp-customize-manager.php | Gets the changeset post ID for the loaded changeset. |
| [WP\_Customize\_Manager::get\_changeset\_post\_data()](get_changeset_post_data) wp-includes/class-wp-customize-manager.php | Gets the data stored in a changeset post. |
| [wp\_get\_post\_autosave()](../../functions/wp_get_post_autosave) wp-includes/revision.php | Retrieves the autosaved data of the specified post. |
| [is\_user\_logged\_in()](../../functions/is_user_logged_in) wp-includes/pluggable.php | Determines whether the current visitor is a logged in user. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::unsanitized\_post\_values()](unsanitized_post_values) wp-includes/class-wp-customize-manager.php | Gets dirty pre-sanitized setting values in the current customized state. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/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. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::get_setting( string $id ): WP_Customize_Setting|void WP\_Customize\_Manager::get\_setting( string $id ): WP\_Customize\_Setting|void
===============================================================================
Retrieves a customize setting.
`$id` string Required Customize Setting ID. [WP\_Customize\_Setting](../wp_customize_setting)|void The setting, if set.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function get_setting( $id ) {
if ( isset( $this->settings[ $id ] ) ) {
return $this->settings[ $id ];
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::has\_published\_pages()](has_published_pages) wp-includes/class-wp-customize-manager.php | Returns whether there are published pages. |
| [WP\_Customize\_Manager::\_publish\_changeset\_values()](_publish_changeset_values) wp-includes/class-wp-customize-manager.php | Publishes the values of a changeset. |
| [WP\_Customize\_Manager::save\_changeset\_post()](save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [WP\_Customize\_Manager::validate\_setting\_values()](validate_setting_values) wp-includes/class-wp-customize-manager.php | Validates setting values. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Customize\_Manager::add\_dynamic\_settings()](add_dynamic_settings) wp-includes/class-wp-customize-manager.php | Registers any dynamically-created settings, such as those from $\_POST[‘customized’] that have no corresponding setting created. |
| [WP\_Customize\_Manager::register\_controls()](register_controls) wp-includes/class-wp-customize-manager.php | Registers some default controls. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::remove_preview_signature( callable|null $callback = null ): callable|null WP\_Customize\_Manager::remove\_preview\_signature( callable|null $callback = null ): callable|null
===================================================================================================
This method has been deprecated.
Removes the signature in case we experience a case where the Customizer was not properly executed.
`$callback` callable|null Optional Value passed through for ['wp\_die\_handler'](../../hooks/wp_die_handler) filter.
Default: `null`
callable|null Value passed through for ['wp\_die\_handler'](../../hooks/wp_die_handler) filter.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function remove_preview_signature( $callback = null ) {
_deprecated_function( __METHOD__, '4.7.0' );
return $callback;
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | This method has been deprecated. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::set_autofocus( array $autofocus ) WP\_Customize\_Manager::set\_autofocus( array $autofocus )
==========================================================
Sets the autofocused constructs.
`$autofocus` array Required Mapping of 'panel', 'section', 'control' to the ID which should be autofocused.
* `control`stringID for control to be autofocused.
* `section`stringID for section to be autofocused.
* `panel`stringID for panel to be autofocused.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function set_autofocus( $autofocus ) {
$this->autofocus = array_filter( wp_array_slice_assoc( $autofocus, array( 'panel', 'section', 'control' ) ), 'is_string' );
}
```
| Uses | Description |
| --- | --- |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Customize_Manager::_cmp_priority( WP_Customize_Panel|WP_Customize_Section|WP_Customize_Control $a, WP_Customize_Panel|WP_Customize_Section|WP_Customize_Control $b ): int WP\_Customize\_Manager::\_cmp\_priority( WP\_Customize\_Panel|WP\_Customize\_Section|WP\_Customize\_Control $a, WP\_Customize\_Panel|WP\_Customize\_Section|WP\_Customize\_Control $b ): int
============================================================================================================================================================================================
This method has been deprecated. Use [wp\_list\_sort()](../../functions/wp_list_sort) instead.
Helper function to compare two objects by priority, ensuring sort stability via instance\_number.
`$a` [WP\_Customize\_Panel](../wp_customize_panel)|[WP\_Customize\_Section](../wp_customize_section)|[WP\_Customize\_Control](../wp_customize_control) Required Object A. `$b` [WP\_Customize\_Panel](../wp_customize_panel)|[WP\_Customize\_Section](../wp_customize_section)|[WP\_Customize\_Control](../wp_customize_control) Required Object B. int
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Use [wp\_list\_sort()](../../functions/wp_list_sort) |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::setup_theme() WP\_Customize\_Manager::setup\_theme()
======================================
Starts preview and customize theme.
Check if customize query variable exist. Init filters to filter the active theme.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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();
}
```
| Uses | Description |
| --- | --- |
| [wp\_is\_uuid()](../../functions/wp_is_uuid) wp-includes/functions.php | Validates that a UUID is valid. |
| [send\_origin\_headers()](../../functions/send_origin_headers) wp-includes/http.php | Send Access-Control-Allow-Origin and related headers if the current request is from an allowed origin. |
| [WP\_Customize\_Manager::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet name of the previewed theme. |
| [WP\_Customize\_Manager::wp\_die()](wp_die) wp-includes/class-wp-customize-manager.php | Custom wp\_die wrapper. Returns either the standard message for UI or the Ajax message. |
| [WP\_Customize\_Manager::is\_theme\_active()](is_theme_active) wp-includes/class-wp-customize-manager.php | Checks if the current theme is active. |
| [WP\_Customize\_Manager::theme()](theme) wp-includes/class-wp-customize-manager.php | Gets the theme being customized. |
| [WP\_Customize\_Manager::start\_previewing\_theme()](start_previewing_theme) wp-includes/class-wp-customize-manager.php | If the theme to be previewed isn’t the active theme, add filter callbacks to swap it out at runtime. |
| [WP\_Customize\_Manager::changeset\_post\_id()](changeset_post_id) wp-includes/class-wp-customize-manager.php | Gets the changeset post ID for the loaded changeset. |
| [show\_admin\_bar()](../../functions/show_admin_bar) wp-includes/admin-bar.php | Sets the display status of the admin bar. |
| [auth\_redirect()](../../functions/auth_redirect) wp-includes/pluggable.php | Checks if a user is logged in, if not it redirects them to the login page. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [check\_ajax\_referer()](../../functions/check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [is\_user\_logged\_in()](../../functions/is_user_logged_in) wp-includes/pluggable.php | Determines whether the current visitor is a logged in user. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::grant_edit_post_capability_for_changeset( string[] $caps, string $cap, int $user_id, array $args ): array WP\_Customize\_Manager::grant\_edit\_post\_capability\_for\_changeset( string[] $caps, string $cap, int $user\_id, array $args ): array
=======================================================================================================================================
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.
* [WP\_Customize\_Manager::save\_changeset\_post()](../wp_customize_manager/save_changeset_post)
* [\_wp\_translate\_postdata()](../../functions/_wp_translate_postdata)
`$caps` string[] Required Array of the user's capabilities. `$cap` string Required Capability name. `$user_id` int Required The user ID. `$args` array Required Adds the context to the cap. Typically the object ID. array Capabilities.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [map\_meta\_cap()](../../functions/map_meta_cap) wp-includes/capabilities.php | Maps a capability to the primitive capabilities required of the given user to satisfy the capability being checked. |
| [get\_post\_type()](../../functions/get_post_type) wp-includes/post.php | Retrieves the post type of the current post or of a given post. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::customize_preview_html5() WP\_Customize\_Manager::customize\_preview\_html5()
===================================================
This method has been deprecated. Customizer no longer supports IE8, so all supported browsers recognize HTML5 instead.
Prints a workaround to handle HTML5 tags in IE < 9.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function customize_preview_html5() {
_deprecated_function( __FUNCTION__, '4.7.0' );
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Customizer no longer supports IE8, so all supported browsers recognize HTML5. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::_validate_header_video( WP_Error $validity, mixed $value ): mixed WP\_Customize\_Manager::\_validate\_header\_video( WP\_Error $validity, mixed $value ): mixed
=============================================================================================
Callback for validating the header\_video value.
Ensures that the selected video is less than 8MB and provides an error message.
`$validity` [WP\_Error](../wp_error) Required `$value` mixed Required mixed
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [get\_attached\_file()](../../functions/get_attached_file) wp-includes/post.php | Retrieves attached file path based on attachment ID. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::current_theme( mixed $current_theme ): string WP\_Customize\_Manager::current\_theme( mixed $current\_theme ): string
=======================================================================
Filters the active theme and return the name of the previewed theme.
`$current_theme` mixed Required @internal Parameter is not used string Theme name.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function current_theme( $current_theme ) {
return $this->theme()->display( 'Name' );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::theme()](theme) wp-includes/class-wp-customize-manager.php | Gets the theme being customized. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::after_setup_theme() WP\_Customize\_Manager::after\_setup\_theme()
=============================================
Callback to validate a theme once it is loaded
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::doing\_ajax()](doing_ajax) wp-includes/class-wp-customize-manager.php | Returns true if it’s an Ajax request. |
| [validate\_current\_theme()](../../functions/validate_current_theme) wp-includes/theme.php | Checks that the active theme has the required files. |
| [wp\_redirect()](../../functions/wp_redirect) wp-includes/pluggable.php | Redirects to another page. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::remove_section( string $id ) WP\_Customize\_Manager::remove\_section( string $id )
=====================================================
Removes a customize section.
Note that removing the section doesn’t destroy the [WP\_Customize\_Section](../wp_customize_section) instance or remove its filters.
`$id` string Required Section ID. File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function remove_section( $id ) {
unset( $this->sections[ $id ] );
}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::_sanitize_background_setting( string $value, WP_Customize_Setting $setting ): string|WP_Error WP\_Customize\_Manager::\_sanitize\_background\_setting( string $value, WP\_Customize\_Setting $setting ): string|WP\_Error
===========================================================================================================================
Callback for validating a background setting value.
`$value` string Required Repeat value. `$setting` [WP\_Customize\_Setting](../wp_customize_setting) Required Setting. string|[WP\_Error](../wp_error) Background value or validation error.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_url()](../../functions/sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::get_template_root(): string WP\_Customize\_Manager::get\_template\_root(): string
=====================================================
Retrieves the template root of the previewed theme.
string Theme root.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function get_template_root() {
return get_raw_theme_root( $this->get_template(), true );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_template()](get_template) wp-includes/class-wp-customize-manager.php | Retrieves the template name of the previewed theme. |
| [get\_raw\_theme\_root()](../../functions/get_raw_theme_root) wp-includes/theme.php | Gets the raw theme root relative to the content directory with no filters applied. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::add_dynamic_settings( array $setting_ids ): array WP\_Customize\_Manager::add\_dynamic\_settings( array $setting\_ids ): array
============================================================================
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.
`$setting_ids` array Required The setting IDs to add. array The [WP\_Customize\_Setting](../wp_customize_setting) objects added.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
[apply\_filters( 'customize\_dynamic\_setting\_args', false|array $setting\_args, string $setting\_id )](../../hooks/customize_dynamic_setting_args)
Filters a dynamic setting’s constructor args.
[apply\_filters( 'customize\_dynamic\_setting\_class', string $setting\_class, string $setting\_id, array $setting\_args )](../../hooks/customize_dynamic_setting_class)
Allow non-statically created settings to be constructed with custom [WP\_Customize\_Setting](../wp_customize_setting) subclass.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_setting()](get_setting) wp-includes/class-wp-customize-manager.php | Retrieves a customize setting. |
| [WP\_Customize\_Manager::add\_setting()](add_setting) wp-includes/class-wp-customize-manager.php | Adds a customize setting. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::\_publish\_changeset\_values()](_publish_changeset_values) wp-includes/class-wp-customize-manager.php | Publishes the values of a changeset. |
| [WP\_Customize\_Manager::save\_changeset\_post()](save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [WP\_Customize\_Manager::register\_dynamic\_settings()](register_dynamic_settings) wp-includes/class-wp-customize-manager.php | Adds settings from the POST data that were not added with code, e.g. dynamically-created settings for Widgets |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_Customize_Manager::_publish_changeset_values( int $changeset_post_id ): true|WP_Error WP\_Customize\_Manager::\_publish\_changeset\_values( int $changeset\_post\_id ): true|WP\_Error
================================================================================================
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.
* [\_wp\_customize\_publish\_changeset()](../../functions/_wp_customize_publish_changeset)
`$changeset_post_id` int Required ID for customize\_changeset post. Defaults to the changeset for the current manager instance. true|[WP\_Error](../wp_error) True or error info.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
[do\_action( 'customize\_save', WP\_Customize\_Manager $manager )](../../hooks/customize_save)
Fires once the theme has switched in the Customizer, but before settings have been saved.
[do\_action( 'customize\_save\_after', WP\_Customize\_Manager $manager )](../../hooks/customize_save_after)
Fires after Customize settings have been saved.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::update\_stashed\_theme\_mod\_settings()](update_stashed_theme_mod_settings) wp-includes/class-wp-customize-manager.php | Updates stashed theme mod settings. |
| [WP\_Customize\_Manager::get\_changeset\_post\_data()](get_changeset_post_data) wp-includes/class-wp-customize-manager.php | Gets the data stored in a changeset post. |
| [wp\_generate\_uuid4()](../../functions/wp_generate_uuid4) wp-includes/functions.php | Generates a random UUID (version 4). |
| [WP\_Customize\_Manager::add\_dynamic\_settings()](add_dynamic_settings) wp-includes/class-wp-customize-manager.php | Registers any dynamically-created settings, such as those from $\_POST[‘customized’] that have no corresponding setting created. |
| [WP\_Customize\_Manager::unsanitized\_post\_values()](unsanitized_post_values) wp-includes/class-wp-customize-manager.php | Gets dirty pre-sanitized setting values in the current customized state. |
| [WP\_Customize\_Manager::get\_setting()](get_setting) wp-includes/class-wp-customize-manager.php | Retrieves a customize setting. |
| [WP\_Customize\_Manager::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet name of the previewed theme. |
| [wp\_set\_current\_user()](../../functions/wp_set_current_user) wp-includes/pluggable.php | Changes the current user by ID or name. |
| [did\_action()](../../functions/did_action) wp-includes/plugin.php | Retrieves the number of times an action has been fired during the current request. |
| [clean\_post\_cache()](../../functions/clean_post_cache) wp-includes/post.php | Will clean the post in the cache. |
| [wp\_get\_post\_revisions()](../../functions/wp_get_post_revisions) wp-includes/revision.php | Returns all revisions of specified post. |
| [wpdb::update()](../wpdb/update) wp-includes/class-wpdb.php | Updates a row in the table. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::changeset_post_id(): int|null WP\_Customize\_Manager::changeset\_post\_id(): int|null
=======================================================
Gets the changeset post ID for the loaded changeset.
int|null Post ID on success or null if there is no post yet saved.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::find\_changeset\_post\_id()](find_changeset_post_id) wp-includes/class-wp-customize-manager.php | Finds the changeset post ID for a given changeset UUID. |
| [WP\_Customize\_Manager::changeset\_uuid()](changeset_uuid) wp-includes/class-wp-customize-manager.php | Gets the changeset UUID. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::check\_changeset\_lock\_with\_heartbeat()](check_changeset_lock_with_heartbeat) wp-includes/class-wp-customize-manager.php | Checks locked changeset with heartbeat API. |
| [WP\_Customize\_Manager::handle\_override\_changeset\_lock\_request()](handle_override_changeset_lock_request) wp-includes/class-wp-customize-manager.php | Removes changeset lock when take over request is sent via Ajax. |
| [WP\_Customize\_Manager::handle\_dismiss\_autosave\_or\_lock\_request()](handle_dismiss_autosave_or_lock_request) wp-includes/class-wp-customize-manager.php | Deletes a given auto-draft changeset or the autosave revision for a given changeset or delete changeset lock. |
| [WP\_Customize\_Manager::handle\_changeset\_trash\_request()](handle_changeset_trash_request) wp-includes/class-wp-customize-manager.php | Handles request to trash a changeset. |
| [WP\_Customize\_Manager::dismiss\_user\_auto\_draft\_changesets()](dismiss_user_auto_draft_changesets) wp-includes/class-wp-customize-manager.php | Dismisses all of the current user’s auto-drafts (other than the present one). |
| [WP\_Customize\_Manager::establish\_loaded\_changeset()](establish_loaded_changeset) wp-includes/class-wp-customize-manager.php | Establishes the loaded changeset. |
| [WP\_Customize\_Manager::save\_changeset\_post()](save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [WP\_Customize\_Manager::import\_theme\_starter\_content()](import_theme_starter_content) wp-includes/class-wp-customize-manager.php | Imports theme starter content into the customized state. |
| [WP\_Customize\_Manager::changeset\_data()](changeset_data) wp-includes/class-wp-customize-manager.php | Gets changeset data. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Customize\_Manager::save()](save) wp-includes/class-wp-customize-manager.php | Handles customize\_save WP Ajax request to save/update a changeset. |
| [WP\_Customize\_Manager::setup\_theme()](setup_theme) wp-includes/class-wp-customize-manager.php | Starts preview and customize theme. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::remove_setting( string $id ) WP\_Customize\_Manager::remove\_setting( string $id )
=====================================================
Removes a customize setting.
Note that removing the setting doesn’t destroy the [WP\_Customize\_Setting](../wp_customize_setting) instance or remove its filters.
`$id` string Required Customize Setting ID. File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function remove_setting( $id ) {
unset( $this->settings[ $id ] );
}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::remove_panel( string $id ) WP\_Customize\_Manager::remove\_panel( string $id )
===================================================
Removes a customize panel.
Note that removing the panel doesn’t destroy the [WP\_Customize\_Panel](../wp_customize_panel) instance or remove its filters.
`$id` string Required Panel ID to remove. File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 ] );
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [\_doing\_it\_wrong()](../../functions/_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Customize_Manager::prepare_controls() WP\_Customize\_Manager::prepare\_controls()
===========================================
Prepares panels, sections, and controls.
For each, check if required related components exist, whether the user has the necessary capabilities, and sort by priority.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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
);
}
```
| Uses | Description |
| --- | --- |
| [wp\_list\_sort()](../../functions/wp_list_sort) wp-includes/functions.php | Sorts an array of objects or arrays based on one or more orderby arguments. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::customize\_preview\_init()](customize_preview_init) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::set_preview_url( string $preview_url ) WP\_Customize\_Manager::set\_preview\_url( string $preview\_url )
=================================================================
Sets the initial URL to be previewed.
URL is validated.
`$preview_url` string Required URL to be previewed. File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function set_preview_url( $preview_url ) {
$preview_url = sanitize_url( $preview_url );
$this->preview_url = wp_validate_redirect( $preview_url, home_url( '/' ) );
}
```
| Uses | Description |
| --- | --- |
| [wp\_validate\_redirect()](../../functions/wp_validate_redirect) wp-includes/pluggable.php | Validates a URL for use in a redirect. |
| [sanitize\_url()](../../functions/sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Customize_Manager::_validate_external_header_video( WP_Error $validity, mixed $value ): mixed WP\_Customize\_Manager::\_validate\_external\_header\_video( WP\_Error $validity, mixed $value ): mixed
=======================================================================================================
Callback for validating the external\_header\_video value.
Ensures that the provided URL is supported.
`$validity` [WP\_Error](../wp_error) Required `$value` mixed Required mixed
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_url()](../../functions/sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::get_section( string $id ): WP_Customize_Section|void WP\_Customize\_Manager::get\_section( string $id ): WP\_Customize\_Section|void
===============================================================================
Retrieves a customize section.
`$id` string Required Section ID. [WP\_Customize\_Section](../wp_customize_section)|void The section, if set.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function get_section( $id ) {
if ( isset( $this->sections[ $id ] ) ) {
return $this->sections[ $id ];
}
}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::sections(): array WP\_Customize\_Manager::sections(): array
=========================================
Gets the registered sections.
array
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function sections() {
return $this->sections;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::register_controls() WP\_Customize\_Manager::register\_controls()
============================================
Registers some default controls.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 × 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 × %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’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',
),
)
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Custom\_CSS\_Setting::\_\_construct()](../wp_customize_custom_css_setting/__construct) wp-includes/customize/class-wp-customize-custom-css-setting.php | [WP\_Customize\_Custom\_CSS\_Setting](../wp_customize_custom_css_setting) constructor. |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [WP\_Customize\_Background\_Image\_Control::\_\_construct()](../wp_customize_background_image_control/__construct) wp-includes/customize/class-wp-customize-background-image-control.php | Constructor. |
| [WP\_Customize\_Header\_Image\_Control::\_\_construct()](../wp_customize_header_image_control/__construct) wp-includes/customize/class-wp-customize-header-image-control.php | Constructor. |
| [get\_edit\_profile\_url()](../../functions/get_edit_profile_url) wp-includes/link-template.php | Retrieves the URL to the user’s profile editor. |
| [wp\_get\_current\_user()](../../functions/wp_get_current_user) wp-includes/pluggable.php | Retrieves the current user object. |
| [get\_stylesheet()](../../functions/get_stylesheet) wp-includes/theme.php | Retrieves name of the current stylesheet. |
| [WP\_Customize\_Site\_Icon\_Control::\_\_construct()](../wp_customize_site_icon_control/__construct) wp-includes/customize/class-wp-customize-site-icon-control.php | Constructor. |
| [get\_template\_directory\_uri()](../../functions/get_template_directory_uri) wp-includes/theme.php | Retrieves template directory URI for the active theme. |
| [get\_stylesheet\_directory\_uri()](../../functions/get_stylesheet_directory_uri) wp-includes/theme.php | Retrieves stylesheet directory URI for the active theme. |
| [WP\_Customize\_Manager::theme()](theme) wp-includes/class-wp-customize-manager.php | Gets the theme being customized. |
| [WP\_Customize\_Manager::get\_setting()](get_setting) wp-includes/class-wp-customize-manager.php | Retrieves a customize setting. |
| [WP\_Customize\_Manager::add\_control()](add_control) wp-includes/class-wp-customize-manager.php | Adds a customize control. |
| [WP\_Customize\_Manager::add\_setting()](add_setting) wp-includes/class-wp-customize-manager.php | Adds a customize setting. |
| [WP\_Customize\_Manager::add\_section()](add_section) wp-includes/class-wp-customize-manager.php | Adds a customize section. |
| [WP\_Customize\_Manager::add\_panel()](add_panel) wp-includes/class-wp-customize-manager.php | Adds a customize panel. |
| [WP\_Customize\_Media\_Control::\_\_construct()](../wp_customize_media_control/__construct) wp-includes/customize/class-wp-customize-media-control.php | Constructor. |
| [WP\_Customize\_Color\_Control::\_\_construct()](../wp_customize_color_control/__construct) wp-includes/customize/class-wp-customize-color-control.php | Constructor. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::wp_loaded() WP\_Customize\_Manager::wp\_loaded()
====================================
Registers styles/scripts and initialize the preview of each setting
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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();
}
}
```
[do\_action( 'customize\_register', WP\_Customize\_Manager $manager )](../../hooks/customize_register)
Fires once WordPress has loaded, allowing scripts and styles to be initialized.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::settings\_previewed()](settings_previewed) wp-includes/class-wp-customize-manager.php | Gets whether settings are or will be previewed. |
| [WP\_Customize\_Manager::register\_panel\_type()](register_panel_type) wp-includes/class-wp-customize-manager.php | Registers a customize panel type. |
| [WP\_Customize\_Manager::register\_section\_type()](register_section_type) wp-includes/class-wp-customize-manager.php | Registers a customize section type. |
| [WP\_Customize\_Manager::register\_control\_type()](register_control_type) wp-includes/class-wp-customize-manager.php | Registers a customize control type. |
| [WP\_Customize\_Manager::is\_preview()](is_preview) wp-includes/class-wp-customize-manager.php | Determines whether it is a theme preview or not. |
| [WP\_Customize\_Manager::customize\_preview\_init()](customize_preview_init) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings. |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::changeset_uuid(): string WP\_Customize\_Manager::changeset\_uuid(): string
=================================================
Gets the changeset UUID.
* [WP\_Customize\_Manager::establish\_loaded\_changeset()](../wp_customize_manager/establish_loaded_changeset)
string UUID.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function changeset_uuid() {
if ( empty( $this->_changeset_uuid ) ) {
$this->establish_loaded_changeset();
}
return $this->_changeset_uuid;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::establish\_loaded\_changeset()](establish_loaded_changeset) wp-includes/class-wp-customize-manager.php | Establishes the loaded changeset. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::save\_changeset\_post()](save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [WP\_Customize\_Manager::add\_state\_query\_params()](add_state_query_params) wp-includes/class-wp-customize-manager.php | Adds customize state query params to a given URL if preview is allowed. |
| [WP\_Customize\_Manager::changeset\_post\_id()](changeset_post_id) wp-includes/class-wp-customize-manager.php | Gets the changeset post ID for the loaded changeset. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Customize\_Manager::customize\_preview\_settings()](customize_preview_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for preview frame. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::_sanitize_header_textcolor( string $color ): mixed WP\_Customize\_Manager::\_sanitize\_header\_textcolor( string $color ): mixed
=============================================================================
Callback for validating the header\_textcolor value.
Accepts ‘blank’, and otherwise uses [sanitize\_hex\_color\_no\_hash()](../../functions/sanitize_hex_color_no_hash) .
Returns default text color if hex color is empty.
`$color` string Required mixed
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_hex\_color\_no\_hash()](../../functions/sanitize_hex_color_no_hash) wp-includes/formatting.php | Sanitizes a hex color without a hash. Use [sanitize\_hex\_color()](../../functions/sanitize_hex_color) when possible. |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::add_panel( WP_Customize_Panel|string $id, array $args = array() ): WP_Customize_Panel WP\_Customize\_Manager::add\_panel( WP\_Customize\_Panel|string $id, array $args = array() ): WP\_Customize\_Panel
==================================================================================================================
Adds a customize panel.
* [WP\_Customize\_Panel::\_\_construct()](../wp_customize_panel/__construct)
`$id` [WP\_Customize\_Panel](../wp_customize_panel)|string Required Customize Panel object, or ID. `$args` array Optional Array of properties for the new Panel object.
See [WP\_Customize\_Panel::\_\_construct()](../wp_customize_panel/__construct) for information on accepted arguments. More Arguments from WP\_Customize\_Panel::\_\_construct( ... $args ) Array of properties for the new Panel object.
* `priority`intPriority of the panel, defining the display order of panels and sections. Default 160.
* `capability`stringCapability required for the panel.
Default `edit_theme_options`.
* `theme_supports`mixed[]Theme features required to support the panel.
* `title`stringTitle of the panel to show in UI.
* `description`stringDescription to show in the UI.
* `type`stringType of the panel.
* `active_callback`callableActive callback.
Default: `array()`
[WP\_Customize\_Panel](../wp_customize_panel) The instance of the panel that was added.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Panel::\_\_construct()](../wp_customize_panel/__construct) wp-includes/class-wp-customize-panel.php | Constructor. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::register\_controls()](register_controls) wp-includes/class-wp-customize-manager.php | Registers some default controls. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Return added [WP\_Customize\_Panel](../wp_customize_panel) instance. |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Customize_Manager::get_preview_url(): string WP\_Customize\_Manager::get\_preview\_url(): string
===================================================
Gets the initial URL to be previewed.
string URL being previewed.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function get_preview_url() {
if ( empty( $this->preview_url ) ) {
$preview_url = home_url( '/' );
} else {
$preview_url = $this->preview_url;
}
return $preview_url;
}
```
| Uses | Description |
| --- | --- |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Customize_Manager::add_setting( WP_Customize_Setting|string $id, array $args = array() ): WP_Customize_Setting WP\_Customize\_Manager::add\_setting( WP\_Customize\_Setting|string $id, array $args = array() ): WP\_Customize\_Setting
========================================================================================================================
Adds a customize setting.
* [WP\_Customize\_Setting::\_\_construct()](../wp_customize_setting/__construct)
`$id` [WP\_Customize\_Setting](../wp_customize_setting)|string Required Customize Setting object, or ID. `$args` array Optional Array of properties for the new Setting object.
See [WP\_Customize\_Setting::\_\_construct()](../wp_customize_setting/__construct) for information on accepted arguments. More Arguments from WP\_Customize\_Setting::\_\_construct( ... $args ) Array of properties for the new Setting object.
* `type`stringType of the setting. Default `'theme_mod'`.
* `capability`stringCapability required for the setting. Default `'edit_theme_options'`
* `theme_supports`string|string[]Theme features required to support the panel. Default is none.
* `default`stringDefault value for the setting. Default is empty string.
* `transport`stringOptions 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'`.
* `validate_callback`callableServer-side validation callback for the setting's value.
* `sanitize_callback`callableCallback to filter a Customize setting value in un-slashed form.
* `sanitize_js_callback`callableCallback to convert a Customize PHP setting value to a value that is JSON serializable.
* `dirty`boolWhether or not the setting is initially dirty when created.
Default: `array()`
[WP\_Customize\_Setting](../wp_customize_setting) The instance of the setting that was added.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
[apply\_filters( 'customize\_dynamic\_setting\_args', false|array $setting\_args, string $setting\_id )](../../hooks/customize_dynamic_setting_args)
Filters a dynamic setting’s constructor args.
[apply\_filters( 'customize\_dynamic\_setting\_class', string $setting\_class, string $setting\_id, array $setting\_args )](../../hooks/customize_dynamic_setting_class)
Allow non-statically created settings to be constructed with custom [WP\_Customize\_Setting](../wp_customize_setting) subclass.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::add\_dynamic\_settings()](add_dynamic_settings) wp-includes/class-wp-customize-manager.php | Registers any dynamically-created settings, such as those from $\_POST[‘customized’] that have no corresponding setting created. |
| [WP\_Customize\_Manager::register\_controls()](register_controls) wp-includes/class-wp-customize-manager.php | Registers some default controls. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Return added [WP\_Customize\_Setting](../wp_customize_setting) instance. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::autosaved(): bool WP\_Customize\_Manager::autosaved(): bool
=========================================
Gets whether data from a changeset’s autosaved revision should be loaded if it exists.
* [WP\_Customize\_Manager::changeset\_data()](../wp_customize_manager/changeset_data)
bool Is using autosaved changeset revision.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function autosaved() {
return $this->autosaved;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::changeset\_data()](changeset_data) wp-includes/class-wp-customize-manager.php | Gets changeset data. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Customize\_Manager::customize\_preview\_settings()](customize_preview_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for preview frame. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Manager::update_stashed_theme_mod_settings( array $inactive_theme_mod_settings ): array|false WP\_Customize\_Manager::update\_stashed\_theme\_mod\_settings( array $inactive\_theme\_mod\_settings ): array|false
===================================================================================================================
Updates stashed theme mod settings.
`$inactive_theme_mod_settings` array Required Mapping of stylesheet to arrays of theme mod settings. array|false Returns array of updated stashed theme mods or false if the update failed or there were no changes.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet name of the previewed theme. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::\_publish\_changeset\_values()](_publish_changeset_values) wp-includes/class-wp-customize-manager.php | Publishes the values of a changeset. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::add_state_query_params( string $url ): string WP\_Customize\_Manager::add\_state\_query\_params( string $url ): string
========================================================================
Adds customize state query params to a given URL if preview is allowed.
* [wp\_redirect()](../../functions/wp_redirect)
* [WP\_Customize\_Manager::get\_allowed\_url()](../wp_customize_manager/get_allowed_url)
`$url` string Required URL. string URL.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_allowed\_urls()](get_allowed_urls) wp-includes/class-wp-customize-manager.php | Gets URLs allowed to be previewed. |
| [WP\_Customize\_Manager::changeset\_uuid()](changeset_uuid) wp-includes/class-wp-customize-manager.php | Gets the changeset UUID. |
| [wp\_parse\_url()](../../functions/wp_parse_url) wp-includes/http.php | A wrapper for PHP’s parse\_url() function that handles consistency in the return values across PHP versions. |
| [WP\_Customize\_Manager::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet name of the previewed theme. |
| [WP\_Customize\_Manager::is\_theme\_active()](is_theme_active) wp-includes/class-wp-customize-manager.php | Checks if the current theme is active. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::render_section_templates() WP\_Customize\_Manager::render\_section\_templates()
====================================================
Renders JS templates for all registered section types.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function render_section_templates() {
foreach ( $this->registered_section_types as $section_type ) {
$section = new $section_type( $this, 'temp', array() );
$section->print_template();
}
}
```
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Manager::validate_setting_values( array $setting_values, array $options = array() ): array WP\_Customize\_Manager::validate\_setting\_values( array $setting\_values, array $options = array() ): array
============================================================================================================
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.
* [WP\_REST\_Request::has\_valid\_params()](../wp_rest_request/has_valid_params)
* [WP\_Customize\_Setting::validate()](../wp_customize_setting/validate)
`$setting_values` array Required Mapping of setting IDs to values to validate and sanitize. `$options` array Optional Options.
* `validate_existence`boolWhether a setting's existence will be checked.
* `validate_capability`boolWhether the setting capability will be checked.
Default: `array()`
array Mapping of setting IDs to return value of validate method calls, either `true` or `WP_Error`.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_setting()](get_setting) wp-includes/class-wp-customize-manager.php | Retrieves a customize setting. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::save\_changeset\_post()](save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [WP\_Customize\_Manager::customize\_preview\_settings()](customize_preview_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for preview frame. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Customize_Manager::get_document_title_template(): string WP\_Customize\_Manager::get\_document\_title\_template(): string
================================================================
Gets the template string for the Customizer pane document title.
string The template string for the document title.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::is\_theme\_active()](is_theme_active) wp-includes/class-wp-customize-manager.php | Checks if the current theme is active. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Customize_Manager::check_changeset_lock_with_heartbeat( array $response, array $data, string $screen_id ): array WP\_Customize\_Manager::check\_changeset\_lock\_with\_heartbeat( array $response, array $data, string $screen\_id ): array
==========================================================================================================================
Checks locked changeset with heartbeat API.
`$response` array Required The Heartbeat response. `$data` array Required The $\_POST data sent. `$screen_id` string Required The screen id. array The Heartbeat response.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_lock\_user\_data()](get_lock_user_data) wp-includes/class-wp-customize-manager.php | Gets lock user data. |
| [WP\_Customize\_Manager::refresh\_changeset\_lock()](refresh_changeset_lock) wp-includes/class-wp-customize-manager.php | Refreshes changeset lock with the current time if current user edited the changeset before. |
| [WP\_Customize\_Manager::find\_changeset\_post\_id()](find_changeset_post_id) wp-includes/class-wp-customize-manager.php | Finds the changeset post ID for a given changeset UUID. |
| [WP\_Customize\_Manager::changeset\_post\_id()](changeset_post_id) wp-includes/class-wp-customize-manager.php | Gets the changeset post ID for the loaded changeset. |
| [wp\_check\_post\_lock()](../../functions/wp_check_post_lock) wp-admin/includes/post.php | Determines whether the post is currently being edited by another user. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Manager::dismiss_user_auto_draft_changesets(): int WP\_Customize\_Manager::dismiss\_user\_auto\_draft\_changesets(): int
=====================================================================
Dismisses all of the current user’s auto-drafts (other than the present one).
int The number of auto-drafts that were dismissed.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_changeset\_posts()](get_changeset_posts) wp-includes/class-wp-customize-manager.php | Gets changeset posts. |
| [WP\_Customize\_Manager::changeset\_post\_id()](changeset_post_id) wp-includes/class-wp-customize-manager.php | Gets the changeset post ID for the loaded changeset. |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::handle\_dismiss\_autosave\_or\_lock\_request()](handle_dismiss_autosave_or_lock_request) wp-includes/class-wp-customize-manager.php | Deletes a given auto-draft changeset or the autosave revision for a given changeset or delete changeset lock. |
| [WP\_Customize\_Manager::save()](save) wp-includes/class-wp-customize-manager.php | Handles customize\_save WP Ajax request to save/update a changeset. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Manager::customize_preview_signature() WP\_Customize\_Manager::customize\_preview\_signature()
=======================================================
This method has been deprecated.
Prints a signature so we can ensure the Customizer was properly executed.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function customize_preview_signature() {
_deprecated_function( __METHOD__, '4.7.0' );
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | This method has been deprecated. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::containers(): array WP\_Customize\_Manager::containers(): array
===========================================
Gets the registered containers.
array
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function containers() {
return $this->containers;
}
```
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Customize_Manager::doing_ajax( string|null $action = null ): bool WP\_Customize\_Manager::doing\_ajax( string|null $action = null ): bool
=======================================================================
Returns true if it’s an Ajax request.
`$action` string|null Optional Whether the supplied Ajax action is being run. Default: `null`
bool True if it's an Ajax request, false otherwise.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_doing\_ajax()](../../functions/wp_doing_ajax) wp-includes/load.php | Determines whether the current request is a WordPress Ajax request. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::wp\_die()](wp_die) wp-includes/class-wp-customize-manager.php | Custom wp\_die wrapper. Returns either the standard message for UI or the Ajax message. |
| [WP\_Customize\_Manager::wp\_die\_handler()](wp_die_handler) wp-includes/class-wp-customize-manager.php | Returns the Ajax [wp\_die()](../../functions/wp_die) handler if it’s a customized request. |
| [WP\_Customize\_Manager::after\_setup\_theme()](after_setup_theme) wp-includes/class-wp-customize-manager.php | Callback to validate a theme once it is loaded |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Added `$action` param. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::add_control( WP_Customize_Control|string $id, array $args = array() ): WP_Customize_Control WP\_Customize\_Manager::add\_control( WP\_Customize\_Control|string $id, array $args = array() ): WP\_Customize\_Control
========================================================================================================================
Adds a customize control.
* [WP\_Customize\_Control::\_\_construct()](../wp_customize_control/__construct)
`$id` [WP\_Customize\_Control](../wp_customize_control)|string Required Customize Control object, or ID. `$args` array Optional Array of properties for the new Control object.
See [WP\_Customize\_Control::\_\_construct()](../wp_customize_control/__construct) for information on accepted arguments. More Arguments from WP\_Customize\_Control::\_\_construct( ... $args ) Array of properties for the new Control object.
* `instance_number`intOrder in which this instance was created in relation to other instances.
* `manager`[WP\_Customize\_Manager](../wp_customize_manager)Customizer bootstrap instance.
* `id`stringControl ID.
* `settings`arrayAll settings tied to the control. If undefined, `$id` will be used.
* `setting`stringThe primary setting for the control (if there is one).
Default `'default'`.
* `capability`stringCapability required to use this control. Normally this is empty and the capability is derived from `$settings`.
* `priority`intOrder priority to load the control. Default 10.
* `section`stringSection the control belongs to.
* `label`stringLabel for the control.
* `description`stringDescription for the control.
* `choices`arrayList of choices for `'radio'` or `'select'` type controls, where values are the keys, and labels are the values.
* `input_attrs`arrayList of custom input attributes for control output, where attribute names are the keys and values are the values. Not used for `'checkbox'`, `'radio'`, `'select'`, `'textarea'`, or `'dropdown-pages'` control types.
* `allow_addition`boolShow UI for adding new content, currently only used for the dropdown-pages control. Default false.
* `json`arrayDeprecated. Use [WP\_Customize\_Control::json()](../wp_customize_control/json) instead.
* `type`stringControl type. Core controls include `'text'`, `'checkbox'`, `'textarea'`, `'radio'`, `'select'`, and `'dropdown-pages'`. Additional input types such as `'email'`, `'url'`, `'number'`, `'hidden'`, and `'date'` are supported implicitly. Default `'text'`.
* `active_callback`callableActive callback.
Default: `array()`
[WP\_Customize\_Control](../wp_customize_control) The instance of the control that was added.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control::\_\_construct()](../wp_customize_control/__construct) wp-includes/class-wp-customize-control.php | Constructor. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::register\_controls()](register_controls) wp-includes/class-wp-customize-manager.php | Registers some default controls. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Return added [WP\_Customize\_Control](../wp_customize_control) instance. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::trash_changeset_post( int|WP_Post $post ): mixed WP\_Customize\_Manager::trash\_changeset\_post( int|WP\_Post $post ): mixed
===========================================================================
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.
* [wp\_trash\_post()](../../functions/wp_trash_post)
`$post` int|[WP\_Post](../wp_post) Required The changeset post. mixed A [WP\_Post](../wp_post) object for the trashed post or an empty value on failure.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
[do\_action( 'edit\_post', int $post\_ID, WP\_Post $post )](../../hooks/edit_post)
Fires once an existing post has been updated.
[do\_action( "edit\_post\_{$post->post\_type}", int $post\_ID, WP\_Post $post )](../../hooks/edit_post_post-post_type)
Fires once an existing post has been updated.
[apply\_filters( 'pre\_trash\_post', bool|null $trash, WP\_Post $post )](../../hooks/pre_trash_post)
Filters whether a post trashing should take place.
[do\_action( 'save\_post', int $post\_ID, WP\_Post $post, bool $update )](../../hooks/save_post)
Fires once a post has been saved.
[do\_action( "save\_post\_{$post->post\_type}", int $post\_ID, WP\_Post $post, bool $update )](../../hooks/save_post_post-post_type)
Fires once a post has been saved.
[do\_action( 'trashed\_post', int $post\_id )](../../hooks/trashed_post)
Fires after a post is sent to the Trash.
[do\_action( 'wp\_insert\_post', int $post\_ID, WP\_Post $post, bool $update )](../../hooks/wp_insert_post)
Fires once a post has been saved.
[do\_action( 'wp\_trash\_post', int $post\_id )](../../hooks/wp_trash_post)
Fires before a post is sent to the Trash.
| Uses | Description |
| --- | --- |
| [wp\_after\_insert\_post()](../../functions/wp_after_insert_post) wp-includes/post.php | Fires actions after a post, its terms and meta data has been saved. |
| [clean\_post\_cache()](../../functions/clean_post_cache) wp-includes/post.php | Will clean the post in the cache. |
| [wp\_transition\_post\_status()](../../functions/wp_transition_post_status) wp-includes/post.php | Fires actions related to the transitioning of a post’s status. |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [wp\_trash\_post\_comments()](../../functions/wp_trash_post_comments) wp-includes/post.php | Moves comments for a post to the Trash. |
| [add\_post\_meta()](../../functions/add_post_meta) wp-includes/post.php | Adds a meta field to the given post. |
| [get\_post\_status()](../../functions/get_post_status) wp-includes/post.php | Retrieves the post status based on the post ID. |
| [wpdb::update()](../wpdb/update) wp-includes/class-wpdb.php | Updates a row in the table. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::handle\_changeset\_trash\_request()](handle_changeset_trash_request) wp-includes/class-wp-customize-manager.php | Handles request to trash a changeset. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::get_return_url(): string WP\_Customize\_Manager::get\_return\_url(): string
==================================================
Gets URL to link the user to when closing the Customizer.
string URL for link to close Customizer.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_referer()](../../functions/wp_get_referer) wp-includes/functions.php | Retrieves referer from ‘\_wp\_http\_referer’ or HTTP referer. |
| [wp\_basename()](../../functions/wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Customize_Manager::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.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 );
}
```
[do\_action( 'start\_previewing\_theme', WP\_Customize\_Manager $manager )](../../hooks/start_previewing_theme)
Fires once the Customizer theme preview has started.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::is\_preview()](is_preview) wp-includes/class-wp-customize-manager.php | Determines whether it is a theme preview or not. |
| [WP\_Customize\_Manager::is\_theme\_active()](is_theme_active) wp-includes/class-wp-customize-manager.php | Checks if the current theme is active. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::save\_changeset\_post()](save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [WP\_Customize\_Manager::setup\_theme()](setup_theme) wp-includes/class-wp-customize-manager.php | Starts preview and customize theme. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::branching(): bool WP\_Customize\_Manager::branching(): bool
=========================================
Whether the changeset branching is allowed.
* [WP\_Customize\_Manager::establish\_loaded\_changeset()](../wp_customize_manager/establish_loaded_changeset)
bool Is changeset branching.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
[apply\_filters( 'customize\_changeset\_branching', bool $allow\_branching, WP\_Customize\_Manager $wp\_customize )](../../hooks/customize_changeset_branching)
Filters whether or not changeset branching is allowed.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::establish\_loaded\_changeset()](establish_loaded_changeset) wp-includes/class-wp-customize-manager.php | Establishes the loaded changeset. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Customize\_Manager::render\_control\_templates()](render_control_templates) wp-includes/class-wp-customize-manager.php | Renders JS templates for all registered control types. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Manager::post_value( WP_Customize_Setting $setting, mixed $default_value = null ): string|mixed WP\_Customize\_Manager::post\_value( WP\_Customize\_Setting $setting, mixed $default\_value = null ): string|mixed
==================================================================================================================
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.
* [WP\_REST\_Server::dispatch()](../wp_rest_server/dispatch)
* [WP\_REST\_Request::sanitize\_params()](../wp_rest_request/sanitize_params)
* [WP\_REST\_Request::has\_valid\_params()](../wp_rest_request/has_valid_params)
`$setting` [WP\_Customize\_Setting](../wp_customize_setting) Required A [WP\_Customize\_Setting](../wp_customize_setting) derived object. `$default_value` mixed Optional Value returned if `$setting` has no post value (added in 4.2.0) or the post value is invalid (added in 4.6.0). Default: `null`
string|mixed Sanitized value or the `$default_value` provided.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::unsanitized\_post\_values()](unsanitized_post_values) wp-includes/class-wp-customize-manager.php | Gets dirty pre-sanitized setting values in the current customized state. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | `$default_value` is now returned early when the setting post value is invalid. |
| [4.1.1](https://developer.wordpress.org/reference/since/4.1.1/) | Introduced the `$default_value` parameter. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::get_stylesheet_root(): string WP\_Customize\_Manager::get\_stylesheet\_root(): string
=======================================================
Retrieves the stylesheet root of the previewed theme.
string Theme root.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function get_stylesheet_root() {
return get_raw_theme_root( $this->get_stylesheet(), true );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet name of the previewed theme. |
| [get\_raw\_theme\_root()](../../functions/get_raw_theme_root) wp-includes/theme.php | Gets the raw theme root relative to the content directory with no filters applied. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::save() WP\_Customize\_Manager::save()
==============================
Handles customize\_save WP Ajax request to save/update a changeset.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 );
}
}
```
[apply\_filters( 'customize\_save\_response', array $response, WP\_Customize\_Manager $manager )](../../hooks/customize_save_response)
Filters response data for a successful customize\_save Ajax request.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_lock\_user\_data()](get_lock_user_data) wp-includes/class-wp-customize-manager.php | Gets lock user data. |
| [WP\_Customize\_Manager::is\_preview()](is_preview) wp-includes/class-wp-customize-manager.php | Determines whether it is a theme preview or not. |
| [get\_post\_status\_object()](../../functions/get_post_status_object) wp-includes/post.php | Retrieves a post status object by name. |
| [wp\_checkdate()](../../functions/wp_checkdate) wp-includes/functions.php | Tests if the supplied date is valid for the Gregorian calendar. |
| [get\_gmt\_from\_date()](../../functions/get_gmt_from_date) wp-includes/formatting.php | Given a date in the timezone of the site, returns that date in UTC. |
| [WP\_Customize\_Manager::set\_changeset\_lock()](set_changeset_lock) wp-includes/class-wp-customize-manager.php | Marks the changeset post as being currently edited by the current user. |
| [WP\_Customize\_Manager::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet name of the previewed theme. |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [WP\_Customize\_Manager::save\_changeset\_post()](save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [wp\_generate\_uuid4()](../../functions/wp_generate_uuid4) wp-includes/functions.php | Generates a random UUID (version 4). |
| [WP\_Customize\_Manager::changeset\_post\_id()](changeset_post_id) wp-includes/class-wp-customize-manager.php | Gets the changeset post ID for the loaded changeset. |
| [WP\_Customize\_Manager::dismiss\_user\_auto\_draft\_changesets()](dismiss_user_auto_draft_changesets) wp-includes/class-wp-customize-manager.php | Dismisses all of the current user’s auto-drafts (other than the present one). |
| [wp\_check\_post\_lock()](../../functions/wp_check_post_lock) wp-admin/includes/post.php | Determines whether the post is currently being edited by another user. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [wp\_send\_json\_success()](../../functions/wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| [wp\_send\_json\_error()](../../functions/wp_send_json_error) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating failure. |
| [check\_ajax\_referer()](../../functions/check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [is\_user\_logged\_in()](../../functions/is_user_logged_in) wp-includes/pluggable.php | Determines whether the current visitor is a logged in user. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | The semantics of this method have changed to update a changeset, optionally to also change the status and other attributes. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::unsanitized_post_values( array $args = array() ): array WP\_Customize\_Manager::unsanitized\_post\_values( array $args = array() ): 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.
`$args` array Optional Args.
* `exclude_changeset`boolWhether the changeset values should also be excluded. Defaults to false.
* `exclude_post_data`boolWhether the post input values should also be excluded. Defaults to false when lacking the customize capability.
Default: `array()`
array
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::changeset\_data()](changeset_data) wp-includes/class-wp-customize-manager.php | Gets changeset data. |
| [WP\_Customize\_Manager::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet name of the previewed theme. |
| [WP\_Customize\_Manager::is\_theme\_active()](is_theme_active) wp-includes/class-wp-customize-manager.php | Checks if the current theme is active. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::\_publish\_changeset\_values()](_publish_changeset_values) wp-includes/class-wp-customize-manager.php | Publishes the values of a changeset. |
| [WP\_Customize\_Manager::save\_changeset\_post()](save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Customize\_Manager::register\_dynamic\_settings()](register_dynamic_settings) wp-includes/class-wp-customize-manager.php | Adds settings from the POST data that were not added with code, e.g. dynamically-created settings for Widgets |
| [WP\_Customize\_Manager::set\_post\_value()](set_post_value) wp-includes/class-wp-customize-manager.php | Overrides a setting’s value in the current customized state. |
| [WP\_Customize\_Manager::customize\_preview\_settings()](customize_preview_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for preview frame. |
| [WP\_Customize\_Manager::post\_value()](post_value) wp-includes/class-wp-customize-manager.php | Returns the sanitized value for a given setting from the current customized state. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Added `$args` parameter and merging with changeset values and stashed theme mods. |
| [4.1.1](https://developer.wordpress.org/reference/since/4.1.1/) | Introduced. |
wordpress WP_Customize_Manager::customize_preview_init() WP\_Customize\_Manager::customize\_preview\_init()
==================================================
Prints JavaScript settings.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 );
}
```
[do\_action( 'customize\_preview\_init', WP\_Customize\_Manager $manager )](../../hooks/customize_preview_init)
Fires once the Customizer preview has initialized and JavaScript settings have been printed.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::prepare\_controls()](prepare_controls) wp-includes/class-wp-customize-manager.php | Prepares panels, sections, and controls. |
| [WP\_Customize\_Manager::wp\_die()](wp_die) wp-includes/class-wp-customize-manager.php | Custom wp\_die wrapper. Returns either the standard message for UI or the Ajax message. |
| [wp\_enqueue\_script()](../../functions/wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| [nocache\_headers()](../../functions/nocache_headers) wp-includes/functions.php | Sets the headers to prevent caching for the different browsers. |
| [wp\_enqueue\_style()](../../functions/wp_enqueue_style) wp-includes/functions.wp-styles.php | Enqueue a CSS stylesheet. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::wp\_loaded()](wp_loaded) wp-includes/class-wp-customize-manager.php | Registers styles/scripts and initialize the preview of each setting |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::remove_control( string $id ) WP\_Customize\_Manager::remove\_control( string $id )
=====================================================
Removes a customize control.
Note that removing the control doesn’t destroy the [WP\_Customize\_Control](../wp_customize_control) instance or remove its filters.
`$id` string Required ID of the control. File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function remove_control( $id ) {
unset( $this->controls[ $id ] );
}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::panels(): array WP\_Customize\_Manager::panels(): array
=======================================
Gets the registered panels.
array Panels.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function panels() {
return $this->panels;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Customize_Manager::get_lock_user_data( int $user_id ): array|null WP\_Customize\_Manager::get\_lock\_user\_data( int $user\_id ): array|null
==========================================================================
Gets lock user data.
`$user_id` int Required User ID. array|null User data formatted for client.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 ) ),
);
}
```
| Uses | Description |
| --- | --- |
| [get\_avatar\_url()](../../functions/get_avatar_url) wp-includes/link-template.php | Retrieves the avatar URL. |
| [get\_userdata()](../../functions/get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::check\_changeset\_lock\_with\_heartbeat()](check_changeset_lock_with_heartbeat) wp-includes/class-wp-customize-manager.php | Checks locked changeset with heartbeat API. |
| [WP\_Customize\_Manager::handle\_changeset\_trash\_request()](handle_changeset_trash_request) wp-includes/class-wp-customize-manager.php | Handles request to trash a changeset. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Customize\_Manager::save()](save) wp-includes/class-wp-customize-manager.php | Handles customize\_save WP Ajax request to save/update a changeset. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Manager::settings_previewed(): bool WP\_Customize\_Manager::settings\_previewed(): bool
===================================================
Gets whether settings are or will be previewed.
* [WP\_Customize\_Setting::preview()](../wp_customize_setting/preview)
bool
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function settings_previewed() {
return $this->settings_previewed;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::wp\_loaded()](wp_loaded) wp-includes/class-wp-customize-manager.php | Registers styles/scripts and initialize the preview of each setting |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Manager::handle_changeset_trash_request() WP\_Customize\_Manager::handle\_changeset\_trash\_request()
===========================================================
Handles request to trash a changeset.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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.' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_lock\_user\_data()](get_lock_user_data) wp-includes/class-wp-customize-manager.php | Gets lock user data. |
| [WP\_Customize\_Manager::trash\_changeset\_post()](trash_changeset_post) wp-includes/class-wp-customize-manager.php | Trashes or deletes a changeset post. |
| [WP\_Customize\_Manager::changeset\_post\_id()](changeset_post_id) wp-includes/class-wp-customize-manager.php | Gets the changeset post ID for the loaded changeset. |
| [wp\_check\_post\_lock()](../../functions/wp_check_post_lock) wp-admin/includes/post.php | Determines whether the post is currently being edited by another user. |
| [WP\_Customize\_Manager::is\_preview()](is_preview) wp-includes/class-wp-customize-manager.php | Determines whether it is a theme preview or not. |
| [get\_post\_status()](../../functions/get_post_status) wp-includes/post.php | Retrieves the post status based on the post ID. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_user\_logged\_in()](../../functions/is_user_logged_in) wp-includes/pluggable.php | Determines whether the current visitor is a logged in user. |
| [check\_ajax\_referer()](../../functions/check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [wp\_send\_json\_error()](../../functions/wp_send_json_error) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating failure. |
| [wp\_send\_json\_success()](../../functions/wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Manager::customize_preview_loading_style() WP\_Customize\_Manager::customize\_preview\_loading\_style()
============================================================
Prints CSS for loading indicators for the Customizer preview.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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
}
```
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::_sanitize_external_header_video( string $value ): string WP\_Customize\_Manager::\_sanitize\_external\_header\_video( string $value ): string
====================================================================================
Callback for sanitizing the external\_header\_video value.
`$value` string Required URL. string Sanitized URL.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function _sanitize_external_header_video( $value ) {
return sanitize_url( trim( $value ) );
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_url()](../../functions/sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| Version | Description |
| --- | --- |
| [4.7.1](https://developer.wordpress.org/reference/since/4.7.1/) | Introduced. |
wordpress WP_Customize_Manager::set_post_value( string $setting_id, mixed $value ) WP\_Customize\_Manager::set\_post\_value( string $setting\_id, mixed $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']`.
`$setting_id` string Required ID for the [WP\_Customize\_Setting](../wp_customize_setting) instance. `$value` mixed Required Post value. File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 );
}
```
[do\_action( 'customize\_post\_value\_set', string $setting\_id, mixed $value, WP\_Customize\_Manager $manager )](../../hooks/customize_post_value_set)
Announces when any setting’s unsanitized post value has been set.
[do\_action( "customize\_post\_value\_set\_{$setting\_id}", mixed $value, WP\_Customize\_Manager $manager )](../../hooks/customize_post_value_set_setting_id)
Announces when a specific setting’s unsanitized post value has been set.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::unsanitized\_post\_values()](unsanitized_post_values) wp-includes/class-wp-customize-manager.php | Gets dirty pre-sanitized setting values in the current customized state. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::save\_changeset\_post()](save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [WP\_Customize\_Manager::import\_theme\_starter\_content()](import_theme_starter_content) wp-includes/class-wp-customize-manager.php | Imports theme starter content into the customized state. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_Customize_Manager::enqueue_control_scripts() WP\_Customize\_Manager::enqueue\_control\_scripts()
===================================================
Enqueues scripts for customize controls.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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(),
)
);
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_enqueue\_script()](../../functions/wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| [wp\_localize\_script()](../../functions/wp_localize_script) wp-includes/functions.wp-scripts.php | Localize a script. |
| [wp\_get\_update\_data()](../../functions/wp_get_update_data) wp-includes/update.php | Collects counts and UI strings for available updates. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::wp_die_handler(): callable WP\_Customize\_Manager::wp\_die\_handler(): callable
====================================================
This method has been deprecated.
Returns the Ajax [wp\_die()](../../functions/wp_die) handler if it’s a customized request.
callable Die handler.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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';
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::doing\_ajax()](doing_ajax) wp-includes/class-wp-customize-manager.php | Returns true if it’s an Ajax request. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | This method has been deprecated. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::customize_pane_settings() WP\_Customize\_Manager::customize\_pane\_settings()
===================================================
Prints JavaScript settings for parent window.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_lock\_user\_data()](get_lock_user_data) wp-includes/class-wp-customize-manager.php | Gets lock user data. |
| [wp\_check\_post\_lock()](../../functions/wp_check_post_lock) wp-admin/includes/post.php | Determines whether the post is currently being edited by another user. |
| [self\_admin\_url()](../../functions/self_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for either the current site or the network depending on context. |
| [current\_time()](../../functions/current_time) wp-includes/functions.php | Retrieves the current time based on specified type. |
| [wp\_is\_mobile()](../../functions/wp_is_mobile) wp-includes/vars.php | Test if the current browser runs on a mobile device (smart phone, tablet, etc.) |
| [sanitize\_url()](../../functions/sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| [wp\_login\_url()](../../functions/wp_login_url) wp-includes/general-template.php | Retrieves the login URL. |
| [get\_the\_time()](../../functions/get_the_time) wp-includes/general-template.php | Retrieves the time at which the post was written. |
| [WP\_Customize\_Manager::controls()](controls) wp-includes/class-wp-customize-manager.php | Gets the registered controls. |
| [WP\_Customize\_Manager::settings()](settings) wp-includes/class-wp-customize-manager.php | Gets the registered settings. |
| [WP\_Customize\_Manager::sections()](sections) wp-includes/class-wp-customize-manager.php | Gets the registered sections. |
| [WP\_Customize\_Manager::is\_theme\_active()](is_theme_active) wp-includes/class-wp-customize-manager.php | Checks if the current theme is active. |
| [WP\_Customize\_Manager::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet name of the previewed theme. |
| [WP\_Customize\_Manager::get\_changeset\_posts()](get_changeset_posts) wp-includes/class-wp-customize-manager.php | Gets changeset posts. |
| [request\_filesystem\_credentials()](../../functions/request_filesystem_credentials) wp-admin/includes/file.php | Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem. |
| [get\_filesystem\_method()](../../functions/get_filesystem_method) wp-admin/includes/file.php | Determines which method to use for reading, writing, modifying, or deleting files on the filesystem. |
| [WP\_Customize\_Manager::get\_setting()](get_setting) wp-includes/class-wp-customize-manager.php | Retrieves a customize setting. |
| [WP\_Customize\_Manager::panels()](panels) wp-includes/class-wp-customize-manager.php | Gets the registered panels. |
| [WP\_Customize\_Manager::get\_previewable\_devices()](get_previewable_devices) wp-includes/class-wp-customize-manager.php | Returns a list of devices to allow previewing. |
| [WP\_Customize\_Manager::branching()](branching) wp-includes/class-wp-customize-manager.php | Whether the changeset branching is allowed. |
| [WP\_Customize\_Manager::autosaved()](autosaved) wp-includes/class-wp-customize-manager.php | Gets whether data from a changeset’s autosaved revision should be loaded if it exists. |
| [WP\_Customize\_Manager::get\_allowed\_urls()](get_allowed_urls) wp-includes/class-wp-customize-manager.php | Gets URLs allowed to be previewed. |
| [WP\_Customize\_Manager::is\_cross\_domain()](is_cross_domain) wp-includes/class-wp-customize-manager.php | Determines whether the admin and the frontend are on different domains. |
| [WP\_Customize\_Manager::changeset\_post\_id()](changeset_post_id) wp-includes/class-wp-customize-manager.php | Gets the changeset post ID for the loaded changeset. |
| [WP\_Customize\_Manager::get\_nonces()](get_nonces) wp-includes/class-wp-customize-manager.php | Gets nonces for the Customizer. |
| [WP\_Customize\_Manager::changeset\_uuid()](changeset_uuid) wp-includes/class-wp-customize-manager.php | Gets the changeset UUID. |
| [WP\_Customize\_Manager::get\_preview\_url()](get_preview_url) wp-includes/class-wp-customize-manager.php | Gets the initial URL to be previewed. |
| [WP\_Customize\_Manager::is\_ios()](is_ios) wp-includes/class-wp-customize-manager.php | Determines whether the user agent is iOS. |
| [WP\_Customize\_Manager::unsanitized\_post\_values()](unsanitized_post_values) wp-includes/class-wp-customize-manager.php | Gets dirty pre-sanitized setting values in the current customized state. |
| [WP\_Customize\_Manager::get\_document\_title\_template()](get_document_title_template) wp-includes/class-wp-customize-manager.php | Gets the template string for the Customizer pane document title. |
| [WP\_Customize\_Manager::get\_return\_url()](get_return_url) wp-includes/class-wp-customize-manager.php | Gets URL to link the user to when closing the Customizer. |
| [wp\_get\_post\_autosave()](../../functions/wp_get_post_autosave) wp-includes/revision.php | Retrieves the autosaved data of the specified post. |
| [WP\_Customize\_Manager::get\_autofocus()](get_autofocus) wp-includes/class-wp-customize-manager.php | Gets the autofocused constructs. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [is\_user\_logged\_in()](../../functions/is_user_logged_in) wp-includes/pluggable.php | Determines whether the current visitor is a logged in user. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::get_template(): string WP\_Customize\_Manager::get\_template(): string
===============================================
Retrieves the template name of the previewed theme.
string Template name.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function get_template() {
return $this->theme()->get_template();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::theme()](theme) wp-includes/class-wp-customize-manager.php | Gets the theme being customized. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_template\_root()](get_template_root) wp-includes/class-wp-customize-manager.php | Retrieves the template root of the previewed theme. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::import_theme_starter_content( array $starter_content = array() ) WP\_Customize\_Manager::import\_theme\_starter\_content( array $starter\_content = array() )
============================================================================================
Imports theme starter content into the customized state.
`$starter_content` array Optional Starter content. Defaults to `get_theme_starter_content()`. Default: `array()`
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 );
}
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::prepare\_starter\_content\_attachments()](prepare_starter_content_attachments) wp-includes/class-wp-customize-manager.php | Prepares starter content attachments. |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| [get\_attached\_file()](../../functions/get_attached_file) wp-includes/post.php | Retrieves attached file path based on attachment ID. |
| [get\_post\_stati()](../../functions/get_post_stati) wp-includes/post.php | Gets a list of post statuses. |
| [get\_post\_status()](../../functions/get_post_status) wp-includes/post.php | Retrieves the post status based on the post ID. |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| [wp\_get\_attachment\_url()](../../functions/wp_get_attachment_url) wp-includes/post.php | Retrieves the URL for an attachment. |
| [wp\_get\_attachment\_metadata()](../../functions/wp_get_attachment_metadata) wp-includes/post.php | Retrieves attachment metadata for attachment ID. |
| [wp\_update\_attachment\_metadata()](../../functions/wp_update_attachment_metadata) wp-includes/post.php | Updates metadata for an attachment. |
| [did\_action()](../../functions/did_action) wp-includes/plugin.php | Retrieves the number of times an action has been fired during the current request. |
| [maybe\_unserialize()](../../functions/maybe_unserialize) wp-includes/functions.php | Unserializes data only if it was serialized. |
| [is\_serialized()](../../functions/is_serialized) wp-includes/functions.php | Checks value to find if it was serialized. |
| [WP\_Customize\_Manager::\_save\_starter\_content\_changeset()](_save_starter_content_changeset) wp-includes/class-wp-customize-manager.php | Saves starter content changeset. |
| [maybe\_serialize()](../../functions/maybe_serialize) wp-includes/functions.php | Serializes data, if needed. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [WP\_Query::\_\_construct()](../wp_query/__construct) wp-includes/class-wp-query.php | Constructor. |
| [WP\_Customize\_Manager::changeset\_post\_id()](changeset_post_id) wp-includes/class-wp-customize-manager.php | Gets the changeset post ID for the loaded changeset. |
| [WP\_Customize\_Manager::get\_changeset\_post\_data()](get_changeset_post_data) wp-includes/class-wp-customize-manager.php | Gets the data stored in a changeset post. |
| [get\_theme\_starter\_content()](../../functions/get_theme_starter_content) wp-includes/theme.php | Expands a theme’s starter content configuration using core-provided data. |
| [WP\_Customize\_Manager::set\_post\_value()](set_post_value) wp-includes/class-wp-customize-manager.php | Overrides a setting’s value in the current customized state. |
| [wp\_generate\_attachment\_metadata()](../../functions/wp_generate_attachment_metadata) wp-admin/includes/image.php | Generates attachment meta data and create image sub-sizes for images. |
| [media\_handle\_sideload()](../../functions/media_handle_sideload) wp-admin/includes/media.php | Handles a side-loaded file in the same way as an uploaded file is handled by [media\_handle\_upload()](../../functions/media_handle_upload) . |
| [wp\_tempnam()](../../functions/wp_tempnam) wp-admin/includes/file.php | Returns a filename of a temporary unique file. |
| [WP\_Customize\_Manager::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet name of the previewed theme. |
| [sanitize\_title()](../../functions/sanitize_title) wp-includes/formatting.php | Sanitizes a string into a slug, which can be used in URLs or HTML attributes. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [get\_post\_meta()](../../functions/get_post_meta) wp-includes/post.php | Retrieves a post meta field for the given post ID. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| [wp\_basename()](../../functions/wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::customize_preview_base() WP\_Customize\_Manager::customize\_preview\_base()
==================================================
This method has been deprecated.
Prints base element for preview frame.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function customize_preview_base() {
_deprecated_function( __METHOD__, '4.7.0' );
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | This method has been deprecated. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::get_messenger_channel(): string WP\_Customize\_Manager::get\_messenger\_channel(): string
=========================================================
Gets messenger channel.
string Messenger channel.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function get_messenger_channel() {
return $this->messenger_channel;
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::get_allowed_urls(): array WP\_Customize\_Manager::get\_allowed\_urls(): array
===================================================
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.
array Allowed URLs.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
[apply\_filters( 'customize\_allowed\_urls', string[] $allowed\_urls )](../../hooks/customize_allowed_urls)
Filters the list of URLs allowed to be clicked and followed in the Customizer preview.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::is\_cross\_domain()](../wp_customize_manager/is_cross_domain) wp-includes/class-wp-customize-manager.php | Determines whether the admin and the frontend are on different domains. |
| [is\_ssl()](../../functions/is_ssl) wp-includes/load.php | Determines if SSL is used. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::add\_state\_query\_params()](../wp_customize_manager/add_state_query_params) wp-includes/class-wp-customize-manager.php | Adds customize state query params to a given URL if preview is allowed. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](../wp_customize_manager/customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Customize\_Manager::customize\_preview\_settings()](../wp_customize_manager/customize_preview_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for preview frame. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::__construct( array $args = array() ) WP\_Customize\_Manager::\_\_construct( array $args = array() )
==============================================================
Constructor.
`$args` array Optional Args.
* `changeset_uuid`null|string|falseChangeset 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.
* `theme`stringTheme to be previewed (for theme switch). Defaults to customize\_theme or theme query params.
* `messenger_channel`stringMessenger channel. Defaults to customize\_messenger\_channel query param.
* `settings_previewed`boolIf settings should be previewed. Defaults to true.
* `branching`boolIf changeset branching is allowed; otherwise, changesets are linear. Defaults to true.
* `autosaved`boolIf data from a changeset's autosaved revision should be loaded if it exists. Defaults to false.
Default: `array()`
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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' );
}
}
```
[apply\_filters( 'customize\_loaded\_components', string[] $components, WP\_Customize\_Manager $manager )](../../hooks/customize_loaded_components)
Filters the core Customizer components to load.
| Uses | Description |
| --- | --- |
| [wp\_generate\_uuid4()](../../functions/wp_generate_uuid4) wp-includes/functions.php | Generates a random UUID (version 4). |
| [WP\_Customize\_Selective\_Refresh::\_\_construct()](../wp_customize_selective_refresh/__construct) wp-includes/customize/class-wp-customize-selective-refresh.php | Plugin bootstrap for Partial Refresh functionality. |
| [WP\_Customize\_Nav\_Menus::\_\_construct()](../wp_customize_nav_menus/__construct) wp-includes/class-wp-customize-nav-menus.php | Constructor. |
| [get\_stylesheet()](../../functions/get_stylesheet) wp-includes/theme.php | Retrieves name of the current stylesheet. |
| [validate\_file()](../../functions/validate_file) wp-includes/functions.php | Validates a file name and path against an allowed set of rules. |
| [remove\_action()](../../functions/remove_action) wp-includes/plugin.php | Removes a callback function from an action hook. |
| [WP\_Customize\_Widgets::\_\_construct()](../wp_customize_widgets/__construct) wp-includes/class-wp-customize-widgets.php | Initial loader. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [sanitize\_key()](../../functions/sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Used By | Description |
| --- | --- |
| [\_wp\_customize\_publish\_changeset()](../../functions/_wp_customize_publish_changeset) wp-includes/theme.php | Publishes a snapshot’s changes. |
| [\_wp\_customize\_include()](../../functions/_wp_customize_include) wp-includes/theme.php | Includes and instantiates the [WP\_Customize\_Manager](../wp_customize_manager) class. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Added `$args` parameter. |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::_save_starter_content_changeset() WP\_Customize\_Manager::\_save\_starter\_content\_changeset()
=============================================================
Saves starter content changeset.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::save\_changeset\_post()](save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::import\_theme\_starter\_content()](import_theme_starter_content) wp-includes/class-wp-customize-manager.php | Imports theme starter content into the customized state. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::get_control( string $id ): WP_Customize_Control|void WP\_Customize\_Manager::get\_control( string $id ): WP\_Customize\_Control|void
===============================================================================
Retrieves a customize control.
`$id` string Required ID of the control. [WP\_Customize\_Control](../wp_customize_control)|void The control object, if set.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function get_control( $id ) {
if ( isset( $this->controls[ $id ] ) ) {
return $this->controls[ $id ];
}
}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::get_changeset_post_data( int $post_id ): array|WP_Error WP\_Customize\_Manager::get\_changeset\_post\_data( int $post\_id ): array|WP\_Error
====================================================================================
Gets the data stored in a changeset post.
`$post_id` int Required Changeset post ID. array|[WP\_Error](../wp_error) Changeset data or [WP\_Error](../wp_error) on error.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [get\_post\_type()](../../functions/get_post_type) wp-includes/post.php | Retrieves the post type of the current post or of a given post. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::\_publish\_changeset\_values()](_publish_changeset_values) wp-includes/class-wp-customize-manager.php | Publishes the values of a changeset. |
| [WP\_Customize\_Manager::save\_changeset\_post()](save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [WP\_Customize\_Manager::import\_theme\_starter\_content()](import_theme_starter_content) wp-includes/class-wp-customize-manager.php | Imports theme starter content into the customized state. |
| [WP\_Customize\_Manager::changeset\_data()](changeset_data) wp-includes/class-wp-customize-manager.php | Gets changeset data. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::is_cross_domain(): bool WP\_Customize\_Manager::is\_cross\_domain(): bool
=================================================
Determines whether the admin and the frontend are on different domains.
bool Whether cross-domain.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [wp\_parse\_url()](../../functions/wp_parse_url) wp-includes/http.php | A wrapper for PHP’s parse\_url() function that handles consistency in the return values across PHP versions. |
| [admin\_url()](../../functions/admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the current site. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_allowed\_urls()](get_allowed_urls) wp-includes/class-wp-customize-manager.php | Gets URLs allowed to be previewed. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Customize\_Manager::customize\_preview\_settings()](customize_preview_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for preview frame. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::is_ios(): bool WP\_Customize\_Manager::is\_ios(): bool
=======================================
Determines whether the user agent is iOS.
bool Whether the user agent is iOS.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function is_ios() {
return wp_is_mobile() && preg_match( '/iPad|iPod|iPhone/', $_SERVER['HTTP_USER_AGENT'] );
}
```
| Uses | Description |
| --- | --- |
| [wp\_is\_mobile()](../../functions/wp_is_mobile) wp-includes/vars.php | Test if the current browser runs on a mobile device (smart phone, tablet, etc.) |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Customize_Manager::filter_iframe_security_headers( array $headers ): array WP\_Customize\_Manager::filter\_iframe\_security\_headers( array $headers ): array
==================================================================================
Filters the X-Frame-Options and Content-Security-Policy headers to ensure frontend can load in customizer.
`$headers` array Required Headers. array Headers.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function filter_iframe_security_headers( $headers ) {
$headers['X-Frame-Options'] = 'SAMEORIGIN';
$headers['Content-Security-Policy'] = "frame-ancestors 'self'";
return $headers;
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::is_theme_active(): bool WP\_Customize\_Manager::is\_theme\_active(): bool
=================================================
Checks if the current theme is active.
bool
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function is_theme_active() {
return $this->get_stylesheet() === $this->original_stylesheet;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet name of the previewed theme. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::establish\_loaded\_changeset()](establish_loaded_changeset) wp-includes/class-wp-customize-manager.php | Establishes the loaded changeset. |
| [WP\_Customize\_Manager::save\_changeset\_post()](save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [WP\_Customize\_Manager::add\_state\_query\_params()](add_state_query_params) wp-includes/class-wp-customize-manager.php | Adds customize state query params to a given URL if preview is allowed. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| [WP\_Customize\_Manager::get\_document\_title\_template()](get_document_title_template) wp-includes/class-wp-customize-manager.php | Gets the template string for the Customizer pane document title. |
| [WP\_Customize\_Manager::unsanitized\_post\_values()](unsanitized_post_values) wp-includes/class-wp-customize-manager.php | Gets dirty pre-sanitized setting values in the current customized state. |
| [WP\_Customize\_Manager::customize\_preview\_settings()](customize_preview_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for preview frame. |
| [WP\_Customize\_Manager::setup\_theme()](setup_theme) wp-includes/class-wp-customize-manager.php | Starts preview and customize theme. |
| [WP\_Customize\_Manager::start\_previewing\_theme()](start_previewing_theme) wp-includes/class-wp-customize-manager.php | If the theme to be previewed isn’t the active theme, add filter callbacks to swap it out at runtime. |
| [WP\_Customize\_Manager::stop\_previewing\_theme()](stop_previewing_theme) wp-includes/class-wp-customize-manager.php | Stops previewing the selected theme. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::register_control_type( string $control ) WP\_Customize\_Manager::register\_control\_type( string $control )
==================================================================
Registers a customize control type.
Registered types are eligible to be rendered via JS and created dynamically.
`$control` string Required Name of a custom control which is a subclass of [WP\_Customize\_Control](../wp_customize_control). File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function register_control_type( $control ) {
$this->registered_control_types[] = $control;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::wp\_loaded()](wp_loaded) wp-includes/class-wp-customize-manager.php | Registers styles/scripts and initialize the preview of each setting |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Customize_Manager::_filter_revision_post_has_changed( bool $post_has_changed, WP_Post $latest_revision, WP_Post $post ): bool WP\_Customize\_Manager::\_filter\_revision\_post\_has\_changed( bool $post\_has\_changed, WP\_Post $latest\_revision, WP\_Post $post ): bool
============================================================================================================================================
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.
`$post_has_changed` bool Required Whether the post has changed. `$latest_revision` [WP\_Post](../wp_post) Required The latest revision post object. `$post` [WP\_Post](../wp_post) Required The post object. bool Whether a revision should be made.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::save_changeset_post( array $args = array() ): array|WP_Error WP\_Customize\_Manager::save\_changeset\_post( array $args = array() ): array|WP\_Error
=======================================================================================
Saves the post for the loaded changeset.
`$args` array Optional Args for changeset post.
* `data`arrayOptional additional changeset data. Values will be merged on top of any existing post values.
* `status`stringPost status. Optional. If supplied, the save will be transactional and a post revision will be allowed.
* `title`stringPost title. Optional.
* `date_gmt`stringDate in GMT. Optional.
* `user_id`intID for user who is saving the changeset. Optional, defaults to the current user ID.
* `starter_content`boolWhether the data is starter content. If false (default), then $starter\_content will be cleared for any $data being saved.
* `autosave`boolWhether this is a request to create an autosave revision.
Default: `array()`
array|[WP\_Error](../wp_error) Returns array on success and [WP\_Error](../wp_error) with array data on error.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
[apply\_filters( 'customize\_changeset\_save\_data', array $data, array $context )](../../hooks/customize_changeset_save_data)
Filters the settings’ data that will be persisted into the changeset.
[do\_action( 'customize\_save\_validation\_before', WP\_Customize\_Manager $manager )](../../hooks/customize_save_validation_before)
Fires before save validation happens.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::changeset\_post\_id()](changeset_post_id) wp-includes/class-wp-customize-manager.php | Gets the changeset post ID for the loaded changeset. |
| [switch\_theme()](../../functions/switch_theme) wp-includes/theme.php | Switches the theme. |
| [wp\_get\_post\_autosave()](../../functions/wp_get_post_autosave) wp-includes/revision.php | Retrieves the autosaved data of the specified post. |
| [get\_post\_status()](../../functions/get_post_status) wp-includes/post.php | Retrieves the post status based on the post ID. |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [wp\_update\_post()](../../functions/wp_update_post) wp-includes/post.php | Updates a post with new post data. |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| [has\_action()](../../functions/has_action) wp-includes/plugin.php | Checks if any action has been registered for a hook. |
| [current\_time()](../../functions/current_time) wp-includes/functions.php | Retrieves the current time based on specified type. |
| [mysql2date()](../../functions/mysql2date) wp-includes/functions.php | Converts given MySQL date string into a different format. |
| [WP\_Customize\_Manager::get\_changeset\_post\_data()](get_changeset_post_data) wp-includes/class-wp-customize-manager.php | Gets the data stored in a changeset post. |
| [\_n()](../../functions/_n) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number. |
| [get\_date\_from\_gmt()](../../functions/get_date_from_gmt) wp-includes/formatting.php | Given a date in UTC or GMT timezone, returns that date in the timezone of the site. |
| [WP\_Customize\_Manager::start\_previewing\_theme()](start_previewing_theme) wp-includes/class-wp-customize-manager.php | If the theme to be previewed isn’t the active theme, add filter callbacks to swap it out at runtime. |
| [WP\_Customize\_Manager::set\_post\_value()](set_post_value) wp-includes/class-wp-customize-manager.php | Overrides a setting’s value in the current customized state. |
| [WP\_Customize\_Manager::is\_theme\_active()](is_theme_active) wp-includes/class-wp-customize-manager.php | Checks if the current theme is active. |
| [WP\_Customize\_Manager::changeset\_uuid()](changeset_uuid) wp-includes/class-wp-customize-manager.php | Gets the changeset UUID. |
| [WP\_Customize\_Manager::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet name of the previewed theme. |
| [WP\_Customize\_Manager::get\_setting()](get_setting) wp-includes/class-wp-customize-manager.php | Retrieves a customize setting. |
| [wp\_create\_post\_autosave()](../../functions/wp_create_post_autosave) wp-admin/includes/post.php | Creates autosave data for the specified post from `$_POST` data. |
| [wp\_generate\_uuid4()](../../functions/wp_generate_uuid4) wp-includes/functions.php | Generates a random UUID (version 4). |
| [WP\_Customize\_Manager::validate\_setting\_values()](validate_setting_values) wp-includes/class-wp-customize-manager.php | Validates setting values. |
| [WP\_Customize\_Manager::add\_dynamic\_settings()](add_dynamic_settings) wp-includes/class-wp-customize-manager.php | Registers any dynamically-created settings, such as those from $\_POST[‘customized’] that have no corresponding setting created. |
| [WP\_Customize\_Manager::stop\_previewing\_theme()](stop_previewing_theme) wp-includes/class-wp-customize-manager.php | Stops previewing the selected theme. |
| [WP\_Customize\_Manager::unsanitized\_post\_values()](unsanitized_post_values) wp-includes/class-wp-customize-manager.php | Gets dirty pre-sanitized setting values in the current customized state. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::\_save\_starter\_content\_changeset()](_save_starter_content_changeset) wp-includes/class-wp-customize-manager.php | Saves starter content changeset. |
| [WP\_Customize\_Manager::save()](save) wp-includes/class-wp-customize-manager.php | Handles customize\_save WP Ajax request to save/update a changeset. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::settings(): array WP\_Customize\_Manager::settings(): array
=========================================
Gets the registered settings.
array
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function settings() {
return $this->settings;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::_render_custom_logo_partial(): string WP\_Customize\_Manager::\_render\_custom\_logo\_partial(): string
=================================================================
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()](../../functions/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.
* [WP\_Customize\_Manager::register\_controls()](../wp_customize_manager/register_controls)
string Custom logo.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function _render_custom_logo_partial() {
return get_custom_logo();
}
```
| Uses | Description |
| --- | --- |
| [get\_custom\_logo()](../../functions/get_custom_logo) wp-includes/general-template.php | Returns a custom logo, linked to home unless the theme supports removing the link on the home page. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Manager::handle_load_themes_request() WP\_Customize\_Manager::handle\_load\_themes\_request()
=======================================================
Loads themes into the theme browsing/installation UI.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 );
}
```
[apply\_filters( 'customize\_load\_themes', array|stdClass $themes, array $args, WP\_Customize\_Manager $manager )](../../hooks/customize_load_themes)
Filters the theme data loaded in the customizer.
| Uses | Description |
| --- | --- |
| [is\_wp\_version\_compatible()](../../functions/is_wp_version_compatible) wp-includes/functions.php | Checks compatibility with the current WordPress version. |
| [wp\_prepare\_themes\_for\_js()](../../functions/wp_prepare_themes_for_js) wp-admin/includes/theme.php | Prepares themes for JavaScript. |
| [themes\_api()](../../functions/themes_api) wp-admin/includes/theme.php | Retrieves theme installer pages from the WordPress.org Themes API. |
| [wp\_star\_rating()](../../functions/wp_star_rating) wp-admin/includes/template.php | Outputs a HTML element with a star rating for a given rating. |
| [wp\_get\_themes()](../../functions/wp_get_themes) wp-includes/theme.php | Returns an array of [WP\_Theme](../wp_theme) objects based on the arguments. |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [network\_admin\_url()](../../functions/network_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the network. |
| [set\_url\_scheme()](../../functions/set_url_scheme) wp-includes/link-template.php | Sets the scheme for a URL. |
| [wp\_create\_nonce()](../../functions/wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| [is\_php\_version\_compatible()](../../functions/is_php_version_compatible) wp-includes/functions.php | Checks compatibility with the current PHP version. |
| [wp\_kses()](../../functions/wp_kses) wp-includes/kses.php | Filters text content and strips out disallowed HTML. |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [check\_ajax\_referer()](../../functions/check_ajax_referer) wp-includes/pluggable.php | Verifies the Ajax request to prevent processing requests external of the blog. |
| [wp\_send\_json\_success()](../../functions/wp_send_json_success) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating success. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [wp\_send\_json\_error()](../../functions/wp_send_json_error) wp-includes/functions.php | Sends a JSON response back to an Ajax request, indicating failure. |
| [sanitize\_key()](../../functions/sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Manager::preserve_insert_changeset_post_content( array $data, array $postarr, array $unsanitized_postarr ): array WP\_Customize\_Manager::preserve\_insert\_changeset\_post\_content( array $data, array $postarr, array $unsanitized\_postarr ): array
=====================================================================================================================================
Preserves the initial JSON post\_content passed to save into the post.
This is needed to prevent KSES and other [‘content\_save\_pre’](../../hooks/content_save_pre) filters from corrupting JSON data.
Note that [WP\_Customize\_Manager::validate\_setting\_values()](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()](../wp_customize_setting/sanitize) method when being read out of the changeset, via [WP\_Customize\_Manager::post\_value()](post_value), and this sanitized value will also be sent into [WP\_Customize\_Setting::update()](../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.
`$data` array Required An array of slashed and processed post data. `$postarr` array Required An array of sanitized (and slashed) but otherwise unmodified post data. `$unsanitized_postarr` array Required An array of slashed yet \*unsanitized\* and unprocessed post data as originally passed to [wp\_insert\_post()](../../functions/wp_insert_post) . array Filtered post data.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [get\_post\_type()](../../functions/get_post_type) wp-includes/post.php | Retrieves the post type of the current post or of a given post. |
| Version | Description |
| --- | --- |
| [5.4.1](https://developer.wordpress.org/reference/since/5.4.1/) | Introduced. |
wordpress WP_Customize_Manager::theme(): WP_Theme WP\_Customize\_Manager::theme(): WP\_Theme
==========================================
Gets the theme being customized.
[WP\_Theme](../wp_theme)
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function theme() {
if ( ! $this->theme ) {
$this->theme = wp_get_theme();
}
return $this->theme;
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::register\_controls()](register_controls) wp-includes/class-wp-customize-manager.php | Registers some default controls. |
| [WP\_Customize\_Manager::get\_template()](get_template) wp-includes/class-wp-customize-manager.php | Retrieves the template name of the previewed theme. |
| [WP\_Customize\_Manager::get\_stylesheet()](get_stylesheet) wp-includes/class-wp-customize-manager.php | Retrieves the stylesheet name of the previewed theme. |
| [WP\_Customize\_Manager::current\_theme()](current_theme) wp-includes/class-wp-customize-manager.php | Filters the active theme and return the name of the previewed theme. |
| [WP\_Customize\_Manager::setup\_theme()](setup_theme) wp-includes/class-wp-customize-manager.php | Starts preview and customize theme. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::prepare_setting_validity_for_js( true|WP_Error $validity ): true|array WP\_Customize\_Manager::prepare\_setting\_validity\_for\_js( true|WP\_Error $validity ): true|array
===================================================================================================
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.
`$validity` true|[WP\_Error](../wp_error) Required Setting validity. true|array If `$validity` was a [WP\_Error](../wp_error), the error codes will be array-mapped to their respective `message` and `data` to pass into the `wp.customize.Notification` JS model.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
}
```
| Uses | Description |
| --- | --- |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Customize_Manager::refresh_changeset_lock( int $changeset_post_id ) WP\_Customize\_Manager::refresh\_changeset\_lock( int $changeset\_post\_id )
============================================================================
Refreshes changeset lock with the current time if current user edited the changeset before.
`$changeset_post_id` int Required Changeset post ID. File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 );
}
}
}
```
| Uses | Description |
| --- | --- |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [get\_post\_meta()](../../functions/get_post_meta) wp-includes/post.php | Retrieves a post meta field for the given post ID. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::check\_changeset\_lock\_with\_heartbeat()](check_changeset_lock_with_heartbeat) wp-includes/class-wp-customize-manager.php | Checks locked changeset with heartbeat API. |
| [WP\_Customize\_Manager::set\_changeset\_lock()](set_changeset_lock) wp-includes/class-wp-customize-manager.php | Marks the changeset post as being currently edited by the current user. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Manager::has_published_pages(): bool WP\_Customize\_Manager::has\_published\_pages(): bool
=====================================================
Returns whether there are published pages.
Used as active callback for static front page section and controls.
bool Whether there are published (or to be published) pages.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 ) ) );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::get\_setting()](get_setting) wp-includes/class-wp-customize-manager.php | Retrieves a customize setting. |
| [get\_pages()](../../functions/get_pages) wp-includes/post.php | Retrieves an array of pages (or hierarchical post type items). |
| [get\_post\_type()](../../functions/get_post_type) wp-includes/post.php | Retrieves the post type of the current post or of a given post. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::register_panel_type( string $panel ) WP\_Customize\_Manager::register\_panel\_type( string $panel )
==============================================================
Registers a customize panel type.
Registered types are eligible to be rendered via JS and created dynamically.
* [WP\_Customize\_Panel](../wp_customize_panel)
`$panel` string Required Name of a custom panel which is a subclass of [WP\_Customize\_Panel](../wp_customize_panel). File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function register_panel_type( $panel ) {
$this->registered_panel_types[] = $panel;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::wp\_loaded()](wp_loaded) wp-includes/class-wp-customize-manager.php | Registers styles/scripts and initialize the preview of each setting |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Manager::get_previewable_devices(): array WP\_Customize\_Manager::get\_previewable\_devices(): array
==========================================================
Returns a list of devices to allow previewing.
array List of devices with labels and default setting.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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;
}
```
[apply\_filters( 'customize\_previewable\_devices', array $devices )](../../hooks/customize_previewable_devices)
Filters the available devices to allow previewing in the Customizer.
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_Customize_Manager::controls(): array WP\_Customize\_Manager::controls(): array
=========================================
Gets the registered controls.
array
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function controls() {
return $this->controls;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Manager::get_changeset_posts( array $args = array() ): WP_Post[] WP\_Customize\_Manager::get\_changeset\_posts( array $args = array() ): WP\_Post[]
==================================================================================
Gets changeset posts.
`$args` array Optional Args to pass into `get_posts()` to query changesets.
* `posts_per_page`intNumber of posts to return. Defaults to -1 (all posts).
* `author`intPost author. Defaults to current user.
* `post_status`stringStatus of changeset. Defaults to `'auto-draft'`.
* `exclude_restore_dismissed`boolWhether to exclude changeset auto-drafts that have been dismissed. Defaults to true.
Default: `array()`
[WP\_Post](../wp_post)[] Auto-draft changesets.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [get\_posts()](../../functions/get_posts) wp-includes/post.php | Retrieves an array of the latest posts, or posts matching the given criteria. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::dismiss\_user\_auto\_draft\_changesets()](dismiss_user_auto_draft_changesets) wp-includes/class-wp-customize-manager.php | Dismisses all of the current user’s auto-drafts (other than the present one). |
| [WP\_Customize\_Manager::establish\_loaded\_changeset()](establish_loaded_changeset) wp-includes/class-wp-customize-manager.php | Establishes the loaded changeset. |
| [WP\_Customize\_Manager::customize\_pane\_settings()](customize_pane_settings) wp-includes/class-wp-customize-manager.php | Prints JavaScript settings for parent window. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Manager::add_customize_screen_to_heartbeat_settings( array $settings ): array WP\_Customize\_Manager::add\_customize\_screen\_to\_heartbeat\_settings( array $settings ): array
=================================================================================================
Filters heartbeat settings for the Customizer.
`$settings` array Required Current settings to filter. array Heartbeat settings.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
public function add_customize_screen_to_heartbeat_settings( $settings ) {
global $pagenow;
if ( 'customize.php' === $pagenow ) {
$settings['screenId'] = 'customize';
}
return $settings;
}
```
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Manager::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.
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.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Manager::establish_loaded_changeset() WP\_Customize\_Manager::establish\_loaded\_changeset()
======================================================
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.
File: `wp-includes/class-wp-customize-manager.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-customize-manager.php/)
```
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() );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Manager::set\_changeset\_lock()](set_changeset_lock) wp-includes/class-wp-customize-manager.php | Marks the changeset post as being currently edited by the current user. |
| [WP\_Customize\_Manager::get\_changeset\_posts()](get_changeset_posts) wp-includes/class-wp-customize-manager.php | Gets changeset posts. |
| [WP\_Customize\_Manager::branching()](branching) wp-includes/class-wp-customize-manager.php | Whether the changeset branching is allowed. |
| [wp\_is\_uuid()](../../functions/wp_is_uuid) wp-includes/functions.php | Validates that a UUID is valid. |
| [WP\_Customize\_Manager::changeset\_post\_id()](changeset_post_id) wp-includes/class-wp-customize-manager.php | Gets the changeset post ID for the loaded changeset. |
| [wp\_generate\_uuid4()](../../functions/wp_generate_uuid4) wp-includes/functions.php | Generates a random UUID (version 4). |
| [WP\_Customize\_Manager::is\_theme\_active()](is_theme_active) wp-includes/class-wp-customize-manager.php | Checks if the current theme is active. |
| [get\_post\_stati()](../../functions/get_post_stati) wp-includes/post.php | Gets a list of post statuses. |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::changeset\_uuid()](changeset_uuid) wp-includes/class-wp-customize-manager.php | Gets the changeset UUID. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_New_Menu_Control::__construct( WP_Customize_Manager $manager, string $id, array $args = array() ) WP\_Customize\_New\_Menu\_Control::\_\_construct( WP\_Customize\_Manager $manager, string $id, array $args = array() )
======================================================================================================================
This method has been deprecated. Use [WP\_Customize\_Control::\_\_construct()](../wp_customize_control/__construct) instead.
Constructor.
* [WP\_Customize\_Control::\_\_construct()](../wp_customize_control/__construct)
`$manager` [WP\_Customize\_Manager](../wp_customize_manager) Required Customizer bootstrap instance. `$id` string Required The control ID. `$args` array Optional Arguments to override class property defaults.
See [WP\_Customize\_Control::\_\_construct()](../wp_customize_control/__construct) for information on accepted arguments. More Arguments from WP\_Customize\_Control::\_\_construct( ... $args ) Array of properties for the new Control object.
* `instance_number`intOrder in which this instance was created in relation to other instances.
* `manager`[WP\_Customize\_Manager](../wp_customize_manager)Customizer bootstrap instance.
* `id`stringControl ID.
* `settings`arrayAll settings tied to the control. If undefined, `$id` will be used.
* `setting`stringThe primary setting for the control (if there is one).
Default `'default'`.
* `capability`stringCapability required to use this control. Normally this is empty and the capability is derived from `$settings`.
* `priority`intOrder priority to load the control. Default 10.
* `section`stringSection the control belongs to.
* `label`stringLabel for the control.
* `description`stringDescription for the control.
* `choices`arrayList of choices for `'radio'` or `'select'` type controls, where values are the keys, and labels are the values.
* `input_attrs`arrayList of custom input attributes for control output, where attribute names are the keys and values are the values. Not used for `'checkbox'`, `'radio'`, `'select'`, `'textarea'`, or `'dropdown-pages'` control types.
* `allow_addition`boolShow UI for adding new content, currently only used for the dropdown-pages control. Default false.
* `json`arrayDeprecated. Use [WP\_Customize\_Control::json()](../wp_customize_control/json) instead.
* `type`stringControl type. Core controls include `'text'`, `'checkbox'`, `'textarea'`, `'radio'`, `'select'`, and `'dropdown-pages'`. Additional input types such as `'email'`, `'url'`, `'number'`, `'hidden'`, and `'date'` are supported implicitly. Default `'text'`.
* `active_callback`callableActive callback.
Default: `array()`
File: `wp-includes/customize/class-wp-customize-new-menu-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-new-menu-control.php/)
```
public function __construct( WP_Customize_Manager $manager, $id, array $args = array() ) {
_deprecated_function( __METHOD__, '4.9.0' );
parent::__construct( $manager, $id, $args );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control::\_\_construct()](../wp_customize_control/__construct) wp-includes/class-wp-customize-control.php | Constructor. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_New_Menu_Control::render_content() WP\_Customize\_New\_Menu\_Control::render\_content()
====================================================
This method has been deprecated.
Render the control’s content.
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/)
```
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 |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | This method has been deprecated. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress Automatic_Upgrader_Skin::feedback( string|array|WP_Error $feedback, mixed $args ) Automatic\_Upgrader\_Skin::feedback( string|array|WP\_Error $feedback, mixed $args )
====================================================================================
Stores a message about the upgrade.
`$feedback` string|array|[WP\_Error](../wp_error) Required Message data. `$args` mixed Optional text replacements. 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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [wp\_kses()](../../functions/wp_kses) wp-includes/kses.php | Filters text content and strips out disallowed HTML. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Ajax\_Upgrader\_Skin::feedback()](../wp_ajax_upgrader_skin/feedback) wp-admin/includes/class-wp-ajax-upgrader-skin.php | Stores a message about the upgrade. |
| [Automatic\_Upgrader\_Skin::footer()](footer) wp-admin/includes/class-automatic-upgrader-skin.php | Retrieves the buffered content, deletes the buffer, and processes the output. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$data` to `$feedback` for PHP 8 named parameter support. |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
| programming_docs |
wordpress Automatic_Upgrader_Skin::request_filesystem_credentials( bool|WP_Error $error = false, string $context = '', bool $allow_relaxed_file_ownership = false ): bool Automatic\_Upgrader\_Skin::request\_filesystem\_credentials( bool|WP\_Error $error = false, string $context = '', bool $allow\_relaxed\_file\_ownership = false ): bool
=======================================================================================================================================================================
Determines whether the upgrader needs FTP/SSH details in order to connect to the filesystem.
* [request\_filesystem\_credentials()](../../functions/request_filesystem_credentials)
`$error` bool|[WP\_Error](../wp_error) Optional Whether the current request has failed to connect, or an error object. Default: `false`
`$context` string Optional Full path to the directory that is tested for being writable. Default: `''`
`$allow_relaxed_file_ownership` bool Optional Whether to allow Group/World writable. Default: `false`
bool True on success, false on failure.
File: `wp-admin/includes/class-automatic-upgrader-skin.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-automatic-upgrader-skin.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Upgrader\_Skin::request\_filesystem\_credentials()](../wp_upgrader_skin/request_filesystem_credentials) wp-admin/includes/class-wp-upgrader-skin.php | Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | The `$context` parameter default changed from `false` to an empty string. |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress Automatic_Upgrader_Skin::get_upgrade_messages(): string[] Automatic\_Upgrader\_Skin::get\_upgrade\_messages(): string[]
=============================================================
Retrieves the upgrade messages.
string[] Messages during an upgrade.
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/)
```
public function get_upgrade_messages() {
return $this->messages;
}
```
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress Automatic_Upgrader_Skin::footer() Automatic\_Upgrader\_Skin::footer()
===================================
Retrieves the buffered content, deletes the buffer, and processes the output.
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/)
```
public function footer() {
$output = ob_get_clean();
if ( ! empty( $output ) ) {
$this->feedback( $output );
}
}
```
| Uses | Description |
| --- | --- |
| [Automatic\_Upgrader\_Skin::feedback()](feedback) wp-admin/includes/class-automatic-upgrader-skin.php | Stores a message about the upgrade. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress Automatic_Upgrader_Skin::header() Automatic\_Upgrader\_Skin::header()
===================================
Creates a new output buffer.
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/)
```
public function header() {
ob_start();
}
```
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::get_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Application\_Passwords\_Controller::get\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
===================================================================================================================
Retrieves one application password from the collection.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_application\_password()](get_application_password) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested application password for a user. |
| [WP\_REST\_Application\_Passwords\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Prepares the application password for the REST response. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::prepare_item_for_response( array $item, WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Application\_Passwords\_Controller::prepare\_item\_for\_response( array $item, WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
===================================================================================================================================================
Prepares the application password for the REST response.
`$item` array Required WordPress representation of the item. `$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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 );
}
```
[apply\_filters( 'rest\_prepare\_application\_password', WP\_REST\_Response $response, array $item, WP\_REST\_Request $request )](../../hooks/rest_prepare_application_password)
Filters the REST API response for an application password.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [WP\_REST\_Application\_Passwords\_Controller::prepare\_links()](prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Prepares links for the request. |
| [rest\_is\_field\_included()](../../functions/rest_is_field_included) wp-includes/rest-api.php | Given an array of fields to include in a response, some of which may be `nested.fields`, determine whether the provided field should be included in the response body. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_current\_item()](get_current_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Retrieves the application password being currently used for authentication of a user. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Retrieves a collection of application passwords. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Retrieves one application password from the collection. |
| [WP\_REST\_Application\_Passwords\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Creates an application password. |
| [WP\_REST\_Application\_Passwords\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Updates an application password. |
| [WP\_REST\_Application\_Passwords\_Controller::delete\_item()](delete_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Deletes an application password for a user. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::prepare_links( WP_User $user, array $item ): array WP\_REST\_Application\_Passwords\_Controller::prepare\_links( WP\_User $user, array $item ): array
==================================================================================================
Prepares links for the request.
`$user` [WP\_User](../wp_user) Required The requested user. `$item` array Required The application password. array The list of links.
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/)
```
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']
)
),
),
);
}
```
| Uses | Description |
| --- | --- |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Prepares the application password for the REST response. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::get_items( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Application\_Passwords\_Controller::get\_items( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
====================================================================================================================
Retrieves a collection of application passwords.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [WP\_REST\_Application\_Passwords\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Prepares the application password for the REST response. |
| [WP\_Application\_Passwords::get\_user\_application\_passwords()](../wp_application_passwords/get_user_application_passwords) wp-includes/class-wp-application-passwords.php | Gets a user’s application passwords. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::get_current_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Application\_Passwords\_Controller::get\_current\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
============================================================================================================================
Retrieves the application password being currently used for authentication of a user.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [rest\_get\_authenticated\_app\_password()](../../functions/rest_get_authenticated_app_password) wp-includes/rest-api.php | Gets the Application Password used for authenticating the request. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [WP\_REST\_Application\_Passwords\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Prepares the application password for the REST response. |
| [WP\_Application\_Passwords::get\_user\_application\_password()](../wp_application_passwords/get_user_application_password) wp-includes/class-wp-application-passwords.php | Gets a user’s application password with the given UUID. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::create_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Application\_Passwords\_Controller::create\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
======================================================================================================================
Creates an application password.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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;
}
```
[do\_action( 'rest\_after\_insert\_application\_password', array $item, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_after_insert_application_password)
Fires after a single application password is completely created or updated via the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [WP\_REST\_Application\_Passwords\_Controller::prepare\_item\_for\_database()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Prepares an application password for a create or update operation. |
| [WP\_REST\_Application\_Passwords\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Prepares the application password for the REST response. |
| [WP\_Application\_Passwords::chunk\_password()](../wp_application_passwords/chunk_password) wp-includes/class-wp-application-passwords.php | Sanitizes and then splits a password into smaller chunks. |
| [WP\_Application\_Passwords::create\_new\_application\_password()](../wp_application_passwords/create_new_application_password) wp-includes/class-wp-application-passwords.php | Creates a new application password. |
| [WP\_Application\_Passwords::get\_user\_application\_password()](../wp_application_passwords/get_user_application_password) wp-includes/class-wp-application-passwords.php | Gets a user’s application password with the given UUID. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Application_Passwords_Controller::update_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Application\_Passwords\_Controller::update\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
======================================================================================================================
Updates an application password.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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 );
}
```
[do\_action( 'rest\_after\_insert\_application\_password', array $item, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_after_insert_application_password)
Fires after a single application password is completely created or updated via the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_application\_password()](get_application_password) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested application password for a user. |
| [WP\_REST\_Application\_Passwords\_Controller::prepare\_item\_for\_database()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Prepares an application password for a create or update operation. |
| [WP\_REST\_Application\_Passwords\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Prepares the application password for the REST response. |
| [WP\_Application\_Passwords::update\_application\_password()](../wp_application_passwords/update_application_password) wp-includes/class-wp-application-passwords.php | Updates an application password. |
| [WP\_Application\_Passwords::get\_user\_application\_password()](../wp_application_passwords/get_user_application_password) wp-includes/class-wp-application-passwords.php | Gets a user’s application password with the given UUID. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::delete_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Application\_Passwords\_Controller::delete\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
============================================================================================================================
Checks if a given request has access to delete a specific application password for a user.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has access to delete the item, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::get_current_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Application\_Passwords\_Controller::get\_current\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
==================================================================================================================================
Checks if a given request has access to get the currently used application password for a user.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access for the item, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::prepare_item_for_database( WP_REST_Request $request ): object|WP_Error WP\_REST\_Application\_Passwords\_Controller::prepare\_item\_for\_database( WP\_REST\_Request $request ): object|WP\_Error
==========================================================================================================================
Prepares an application password for a create or update operation.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. object|[WP\_Error](../wp_error) The prepared item, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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 );
}
```
[apply\_filters( 'rest\_pre\_insert\_application\_password', stdClass $prepared, WP\_REST\_Request $request )](../../hooks/rest_pre_insert_application_password)
Filters an application password before it is inserted via the REST API.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Creates an application password. |
| [WP\_REST\_Application\_Passwords\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Updates an application password. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::get_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Application\_Passwords\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
==========================================================================================================================
Checks if a given request has access to get application passwords.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::update_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Application\_Passwords\_Controller::update\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
============================================================================================================================
Checks if a given request has access to update application passwords.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has access to create items, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::get_user( WP_REST_Request $request ): WP_User|WP_Error WP\_REST\_Application\_Passwords\_Controller::get\_user( WP\_REST\_Request $request ): WP\_User|WP\_Error
=========================================================================================================
Gets the requested user.
`$request` [WP\_REST\_Request](../wp_rest_request) Required The request object. [WP\_User](../wp_user)|[WP\_Error](../wp_error) The WordPress user associated with the request, or a [WP\_Error](../wp_error) if none found.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [wp\_is\_application\_passwords\_available()](../../functions/wp_is_application_passwords_available) wp-includes/user.php | Checks if Application Passwords is globally available. |
| [wp\_is\_application\_passwords\_available\_for\_user()](../../functions/wp_is_application_passwords_available_for_user) wp-includes/user.php | Checks if Application Passwords is available for a specific user. |
| [user\_can()](../../functions/user_can) wp-includes/capabilities.php | Returns whether a particular user has the specified capability. |
| [wp\_get\_current\_user()](../../functions/wp_get_current_user) wp-includes/pluggable.php | Retrieves the current user object. |
| [is\_user\_member\_of\_blog()](../../functions/is_user_member_of_blog) wp-includes/user.php | Finds out whether a user is a member of a given blog. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_user\_logged\_in()](../../functions/is_user_logged_in) wp-includes/pluggable.php | Determines whether the current visitor is a logged in user. |
| [get\_userdata()](../../functions/get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_current\_item\_permissions\_check()](get_current_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to get the currently used application password for a user. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_current\_item()](get_current_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Retrieves the application password being currently used for authentication of a user. |
| [WP\_REST\_Application\_Passwords\_Controller::do\_permissions\_check()](do_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Performs a permissions check for the request. |
| [WP\_REST\_Application\_Passwords\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Prepares the application password for the REST response. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_application\_password()](get_application_password) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested application password for a user. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_items\_permissions\_check()](get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to get application passwords. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Retrieves a collection of application passwords. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to get a specific application password. |
| [WP\_REST\_Application\_Passwords\_Controller::create\_item\_permissions\_check()](create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to create application passwords. |
| [WP\_REST\_Application\_Passwords\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Creates an application password. |
| [WP\_REST\_Application\_Passwords\_Controller::update\_item\_permissions\_check()](update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to update application passwords. |
| [WP\_REST\_Application\_Passwords\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Updates an application password. |
| [WP\_REST\_Application\_Passwords\_Controller::delete\_items\_permissions\_check()](delete_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to delete all application passwords for a user. |
| [WP\_REST\_Application\_Passwords\_Controller::delete\_items()](delete_items) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Deletes all application passwords for a user. |
| [WP\_REST\_Application\_Passwords\_Controller::delete\_item\_permissions\_check()](delete_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to delete a specific application password for a user. |
| [WP\_REST\_Application\_Passwords\_Controller::delete\_item()](delete_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Deletes an application password for a user. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Application_Passwords_Controller::register_routes() WP\_REST\_Application\_Passwords\_Controller::register\_routes()
================================================================
Registers the REST API routes for the application passwords controller.
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/)
```
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' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Retrieves the query params for the collections. |
| [register\_rest\_route()](../../functions/register_rest_route) wp-includes/rest-api.php | Registers a REST API route. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::delete_items( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Application\_Passwords\_Controller::delete\_items( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=======================================================================================================================
Deletes all application passwords for a user.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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,
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [WP\_Application\_Passwords::delete\_all\_application\_passwords()](../wp_application_passwords/delete_all_application_passwords) wp-includes/class-wp-application-passwords.php | Deletes all application passwords for the given user. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::get_collection_params(): array WP\_REST\_Application\_Passwords\_Controller::get\_collection\_params(): array
==============================================================================
Retrieves the query params for the collections.
array Query parameters for the collection.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
public function get_collection_params() {
return array(
'context' => $this->get_context_param( array( 'default' => 'view' ) ),
);
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::register\_routes()](register_routes) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Registers the REST API routes for the application passwords controller. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::__construct() WP\_REST\_Application\_Passwords\_Controller::\_\_construct()
=============================================================
Application Passwords controller constructor.
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/)
```
public function __construct() {
$this->namespace = 'wp/v2';
$this->rest_base = 'users/(?P<user_id>(?:[\d]+|me))/application-passwords';
}
```
| Used By | Description |
| --- | --- |
| [create\_initial\_rest\_routes()](../../functions/create_initial_rest_routes) wp-includes/rest-api.php | Registers default REST API routes. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::get_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Application\_Passwords\_Controller::get\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=========================================================================================================================
Checks if a given request has access to get a specific application password.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access for the item, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::create_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Application\_Passwords\_Controller::create\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
============================================================================================================================
Checks if a given request has access to create application passwords.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has access to create items, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::delete_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Application\_Passwords\_Controller::delete\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
======================================================================================================================
Deletes an application password for a user.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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(),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_application\_password()](get_application_password) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested application password for a user. |
| [WP\_REST\_Application\_Passwords\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Prepares the application password for the REST response. |
| [WP\_Application\_Passwords::delete\_application\_password()](../wp_application_passwords/delete_application_password) wp-includes/class-wp-application-passwords.php | Deletes an application password. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::get_item_schema(): array WP\_REST\_Application\_Passwords\_Controller::get\_item\_schema(): array
========================================================================
Retrieves the application password’s schema, conforming to JSON Schema.
array Item schema data.
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/)
```
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 |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::delete_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Application\_Passwords\_Controller::delete\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=============================================================================================================================
Checks if a given request has access to delete all application passwords for a user.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has access to delete the item, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Application_Passwords_Controller::do_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Application\_Passwords\_Controller::do\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
==================================================================================================================
This method has been deprecated. Use edit\_user directly or one of the specific meta capabilities introduced in 5.7.0 instead.
Performs a permissions check for the request.
`$request` [WP\_REST\_Request](../wp_rest_request) Required true|[WP\_Error](../wp_error)
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Use `edit_user` directly or one of the specific meta capabilities introduced in 5.7.0. |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Application_Passwords_Controller::get_application_password( WP_REST_Request $request ): array|WP_Error WP\_REST\_Application\_Passwords\_Controller::get\_application\_password( WP\_REST\_Request $request ): array|WP\_Error
=======================================================================================================================
Gets the requested application password for a user.
`$request` [WP\_REST\_Request](../wp_rest_request) Required The request object. array|[WP\_Error](../wp_error) The application password details if found, a [WP\_Error](../wp_error) otherwise.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [WP\_Application\_Passwords::get\_user\_application\_password()](../wp_application_passwords/get_user_application_password) wp-includes/class-wp-application-passwords.php | Gets a user’s application password with the given UUID. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Application\_Passwords\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Retrieves one application password from the collection. |
| [WP\_REST\_Application\_Passwords\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Updates an application password. |
| [WP\_REST\_Application\_Passwords\_Controller::delete\_item()](delete_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Deletes an application password for a user. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Block::__get( string $name ): array|null WP\_Block::\_\_get( string $name ): array|null
==============================================
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.
`$name` string Required Property name. array|null Prepared attributes, or null.
File: `wp-includes/class-wp-block.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block.php/)
```
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;
}
```
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Block::__construct( array $block, array $available_context = array(), WP_Block_Type_Registry $registry = null ) WP\_Block::\_\_construct( array $block, array $available\_context = array(), WP\_Block\_Type\_Registry $registry = null )
=========================================================================================================================
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.
`$block` array Required Array of parsed block properties. `$available_context` array Optional array of ancestry context values. Default: `array()`
`$registry` [WP\_Block\_Type\_Registry](../wp_block_type_registry) Optional block type registry. Default: `null`
File: `wp-includes/class-wp-block.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block.php/)
```
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'];
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Block\_List::\_\_construct()](../wp_block_list/__construct) wp-includes/class-wp-block-list.php | Constructor. |
| [WP\_Block\_Type\_Registry::get\_instance()](../wp_block_type_registry/get_instance) wp-includes/class-wp-block-type-registry.php | Utility method to retrieve the main instance of the class. |
| Used By | Description |
| --- | --- |
| [WP\_Block\_List::offsetGet()](../wp_block_list/offsetget) wp-includes/class-wp-block-list.php | |
| [render\_block()](../../functions/render_block) wp-includes/blocks.php | Renders a single block into a HTML string. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Block::render( array $options = array() ): string WP\_Block::render( array $options = array() ): string
=====================================================
Generates the render output for the block.
`$options` array Optional Optional options object.
* `dynamic`boolDefaults to `'true'`. Optionally set to false to avoid using the block's render\_callback.
Default: `array()`
string Rendered block output.
File: `wp-includes/class-wp-block.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block.php/)
```
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;
}
```
[apply\_filters( 'pre\_render\_block', string|null $pre\_render, array $parsed\_block, WP\_Block|null $parent\_block )](../../hooks/pre_render_block)
Allows [render\_block()](../../functions/render_block) to be short-circuited, by returning a non-null value.
[apply\_filters( 'render\_block', string $block\_content, array $block, WP\_Block $instance )](../../hooks/render_block)
Filters the content of a single block.
[apply\_filters( 'render\_block\_context', array $context, array $parsed\_block, WP\_Block|null $parent\_block )](../../hooks/render_block_context)
Filters the default context provided to a rendered block.
[apply\_filters( 'render\_block\_data', array $parsed\_block, array $source\_block, WP\_Block|null $parent\_block )](../../hooks/render_block_data)
Filters the block being rendered in [render\_block()](../../functions/render_block) , before it’s processed.
[apply\_filters( "render\_block\_{$this->name}", string $block\_content, array $block, WP\_Block $instance )](../../hooks/render_block_this-name)
Filters the content of a single block.
| Uses | Description |
| --- | --- |
| [wp\_enqueue\_script()](../../functions/wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| [wp\_enqueue\_style()](../../functions/wp_enqueue_style) wp-includes/functions.wp-styles.php | Enqueue a CSS stylesheet. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Debug_Data::get_mysql_var( string $mysql_var ): string|null WP\_Debug\_Data::get\_mysql\_var( string $mysql\_var ): string|null
===================================================================
Returns the value of a MySQL system variable.
`$mysql_var` string Required Name of the MySQL system variable. string|null The variable value on success. Null if the variable does not exist.
File: `wp-admin/includes/class-wp-debug-data.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-debug-data.php/)
```
public static function get_mysql_var( $mysql_var ) {
global $wpdb;
$result = $wpdb->get_row(
$wpdb->prepare( 'SHOW VARIABLES LIKE %s', $mysql_var ),
ARRAY_A
);
if ( ! empty( $result ) && array_key_exists( 'Value', $result ) ) {
return $result['Value'];
}
return null;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_row()](../wpdb/get_row) wp-includes/class-wpdb.php | Retrieves one row from the database. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_Debug\_Data::debug\_data()](debug_data) wp-admin/includes/class-wp-debug-data.php | Static function for generating site debug data when required. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_Debug_Data::format( array $info_array, string $data_type ): string WP\_Debug\_Data::format( array $info\_array, string $data\_type ): string
=========================================================================
Formats the information gathered for debugging, in a manner suitable for copying to a forum or support ticket.
`$info_array` array Required Information gathered from the `WP_Debug_Data::debug_data()` function. `$data_type` string Required The data type to return, either `'info'` or `'debug'`. string The formatted data.
File: `wp-admin/includes/class-wp-debug-data.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-debug-data.php/)
```
public static function format( $info_array, $data_type ) {
$return = "`\n";
foreach ( $info_array as $section => $details ) {
// Skip this section if there are no fields, or the section has been declared as private.
if ( empty( $details['fields'] ) || ( isset( $details['private'] ) && $details['private'] ) ) {
continue;
}
$section_label = 'debug' === $data_type ? $section : $details['label'];
$return .= sprintf(
"### %s%s ###\n\n",
$section_label,
( isset( $details['show_count'] ) && $details['show_count'] ? sprintf( ' (%d)', count( $details['fields'] ) ) : '' )
);
foreach ( $details['fields'] as $field_name => $field ) {
if ( isset( $field['private'] ) && true === $field['private'] ) {
continue;
}
if ( 'debug' === $data_type && isset( $field['debug'] ) ) {
$debug_data = $field['debug'];
} else {
$debug_data = $field['value'];
}
// Can be array, one level deep only.
if ( is_array( $debug_data ) ) {
$value = '';
foreach ( $debug_data as $sub_field_name => $sub_field_value ) {
$value .= sprintf( "\n\t%s: %s", $sub_field_name, $sub_field_value );
}
} elseif ( is_bool( $debug_data ) ) {
$value = $debug_data ? 'true' : 'false';
} elseif ( empty( $debug_data ) && '0' !== $debug_data ) {
$value = 'undefined';
} else {
$value = $debug_data;
}
if ( 'debug' === $data_type ) {
$label = $field_name;
} else {
$label = $field['label'];
}
$return .= sprintf( "%s: %s\n", $label, $value );
}
$return .= "\n";
}
$return .= '`';
return $return;
}
```
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Debug_Data::check_for_updates() WP\_Debug\_Data::check\_for\_updates()
======================================
Calls all core functions to check for updates.
File: `wp-admin/includes/class-wp-debug-data.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-debug-data.php/)
```
public static function check_for_updates() {
wp_version_check();
wp_update_plugins();
wp_update_themes();
}
```
| Uses | Description |
| --- | --- |
| [wp\_version\_check()](../../functions/wp_version_check) wp-includes/update.php | Checks WordPress version against the newest version. |
| [wp\_update\_plugins()](../../functions/wp_update_plugins) wp-includes/update.php | Checks for available updates to plugins based on the latest versions hosted on WordPress.org. |
| [wp\_update\_themes()](../../functions/wp_update_themes) wp-includes/update.php | Checks for available updates to themes based on the latest versions hosted on WordPress.org. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Debug_Data::get_database_size(): int WP\_Debug\_Data::get\_database\_size(): int
===========================================
Fetches the total size of all the database tables for the active database user.
int The size of the database, in bytes.
File: `wp-admin/includes/class-wp-debug-data.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-debug-data.php/)
```
public static function get_database_size() {
global $wpdb;
$size = 0;
$rows = $wpdb->get_results( 'SHOW TABLE STATUS', ARRAY_A );
if ( $wpdb->num_rows > 0 ) {
foreach ( $rows as $row ) {
$size += $row['Data_length'] + $row['Index_length'];
}
}
return (int) $size;
}
```
| Uses | Description |
| --- | --- |
| [wpdb::get\_results()](../wpdb/get_results) wp-includes/class-wpdb.php | Retrieves an entire SQL result set from the database (i.e., many rows). |
| Used By | Description |
| --- | --- |
| [WP\_Debug\_Data::get\_sizes()](get_sizes) wp-admin/includes/class-wp-debug-data.php | Fetches the sizes of the WordPress directories: `wordpress` (ABSPATH), `plugins`, `themes`, and `uploads`. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress WP_Debug_Data::debug_data(): array WP\_Debug\_Data::debug\_data(): array
=====================================
Static function for generating site debug data when required.
array The debug data for the site.
File: `wp-admin/includes/class-wp-debug-data.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-debug-data.php/)
```
public static function debug_data() {
global $wpdb;
// Save few function calls.
$upload_dir = wp_upload_dir();
$permalink_structure = get_option( 'permalink_structure' );
$is_ssl = is_ssl();
$is_multisite = is_multisite();
$users_can_register = get_option( 'users_can_register' );
$blog_public = get_option( 'blog_public' );
$default_comment_status = get_option( 'default_comment_status' );
$environment_type = wp_get_environment_type();
$core_version = get_bloginfo( 'version' );
$core_updates = get_core_updates();
$core_update_needed = '';
if ( is_array( $core_updates ) ) {
foreach ( $core_updates as $core => $update ) {
if ( 'upgrade' === $update->response ) {
/* translators: %s: Latest WordPress version number. */
$core_update_needed = ' ' . sprintf( __( '(Latest version: %s)' ), $update->version );
} else {
$core_update_needed = '';
}
}
}
// Set up the array that holds all debug information.
$info = array();
$info['wp-core'] = array(
'label' => __( 'WordPress' ),
'fields' => array(
'version' => array(
'label' => __( 'Version' ),
'value' => $core_version . $core_update_needed,
'debug' => $core_version,
),
'site_language' => array(
'label' => __( 'Site Language' ),
'value' => get_locale(),
),
'user_language' => array(
'label' => __( 'User Language' ),
'value' => get_user_locale(),
),
'timezone' => array(
'label' => __( 'Timezone' ),
'value' => wp_timezone_string(),
),
'home_url' => array(
'label' => __( 'Home URL' ),
'value' => get_bloginfo( 'url' ),
'private' => true,
),
'site_url' => array(
'label' => __( 'Site URL' ),
'value' => get_bloginfo( 'wpurl' ),
'private' => true,
),
'permalink' => array(
'label' => __( 'Permalink structure' ),
'value' => $permalink_structure ? $permalink_structure : __( 'No permalink structure set' ),
'debug' => $permalink_structure,
),
'https_status' => array(
'label' => __( 'Is this site using HTTPS?' ),
'value' => $is_ssl ? __( 'Yes' ) : __( 'No' ),
'debug' => $is_ssl,
),
'multisite' => array(
'label' => __( 'Is this a multisite?' ),
'value' => $is_multisite ? __( 'Yes' ) : __( 'No' ),
'debug' => $is_multisite,
),
'user_registration' => array(
'label' => __( 'Can anyone register on this site?' ),
'value' => $users_can_register ? __( 'Yes' ) : __( 'No' ),
'debug' => $users_can_register,
),
'blog_public' => array(
'label' => __( 'Is this site discouraging search engines?' ),
'value' => $blog_public ? __( 'No' ) : __( 'Yes' ),
'debug' => $blog_public,
),
'default_comment_status' => array(
'label' => __( 'Default comment status' ),
'value' => 'open' === $default_comment_status ? _x( 'Open', 'comment status' ) : _x( 'Closed', 'comment status' ),
'debug' => $default_comment_status,
),
'environment_type' => array(
'label' => __( 'Environment type' ),
'value' => $environment_type,
'debug' => $environment_type,
),
),
);
if ( ! $is_multisite ) {
$info['wp-paths-sizes'] = array(
'label' => __( 'Directories and Sizes' ),
'fields' => array(),
);
}
$info['wp-dropins'] = array(
'label' => __( 'Drop-ins' ),
'show_count' => true,
'description' => 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>'
),
'fields' => array(),
);
$info['wp-active-theme'] = array(
'label' => __( 'Active Theme' ),
'fields' => array(),
);
$info['wp-parent-theme'] = array(
'label' => __( 'Parent Theme' ),
'fields' => array(),
);
$info['wp-themes-inactive'] = array(
'label' => __( 'Inactive Themes' ),
'show_count' => true,
'fields' => array(),
);
$info['wp-mu-plugins'] = array(
'label' => __( 'Must Use Plugins' ),
'show_count' => true,
'fields' => array(),
);
$info['wp-plugins-active'] = array(
'label' => __( 'Active Plugins' ),
'show_count' => true,
'fields' => array(),
);
$info['wp-plugins-inactive'] = array(
'label' => __( 'Inactive Plugins' ),
'show_count' => true,
'fields' => array(),
);
$info['wp-media'] = array(
'label' => __( 'Media Handling' ),
'fields' => array(),
);
$info['wp-server'] = array(
'label' => __( 'Server' ),
'description' => __( 'The options shown below relate to your server setup. If changes are required, you may need your web host’s assistance.' ),
'fields' => array(),
);
$info['wp-database'] = array(
'label' => __( 'Database' ),
'fields' => array(),
);
// Check if WP_DEBUG_LOG is set.
$wp_debug_log_value = __( 'Disabled' );
if ( is_string( WP_DEBUG_LOG ) ) {
$wp_debug_log_value = WP_DEBUG_LOG;
} elseif ( WP_DEBUG_LOG ) {
$wp_debug_log_value = __( 'Enabled' );
}
// Check CONCATENATE_SCRIPTS.
if ( defined( 'CONCATENATE_SCRIPTS' ) ) {
$concatenate_scripts = CONCATENATE_SCRIPTS ? __( 'Enabled' ) : __( 'Disabled' );
$concatenate_scripts_debug = CONCATENATE_SCRIPTS ? 'true' : 'false';
} else {
$concatenate_scripts = __( 'Undefined' );
$concatenate_scripts_debug = 'undefined';
}
// Check COMPRESS_SCRIPTS.
if ( defined( 'COMPRESS_SCRIPTS' ) ) {
$compress_scripts = COMPRESS_SCRIPTS ? __( 'Enabled' ) : __( 'Disabled' );
$compress_scripts_debug = COMPRESS_SCRIPTS ? 'true' : 'false';
} else {
$compress_scripts = __( 'Undefined' );
$compress_scripts_debug = 'undefined';
}
// Check COMPRESS_CSS.
if ( defined( 'COMPRESS_CSS' ) ) {
$compress_css = COMPRESS_CSS ? __( 'Enabled' ) : __( 'Disabled' );
$compress_css_debug = COMPRESS_CSS ? 'true' : 'false';
} else {
$compress_css = __( 'Undefined' );
$compress_css_debug = 'undefined';
}
// Check WP_ENVIRONMENT_TYPE.
if ( defined( 'WP_ENVIRONMENT_TYPE' ) && WP_ENVIRONMENT_TYPE ) {
$wp_environment_type = WP_ENVIRONMENT_TYPE;
} else {
$wp_environment_type = __( 'Undefined' );
}
$info['wp-constants'] = array(
'label' => __( 'WordPress Constants' ),
'description' => __( 'These settings alter where and how parts of WordPress are loaded.' ),
'fields' => array(
'ABSPATH' => array(
'label' => 'ABSPATH',
'value' => ABSPATH,
'private' => true,
),
'WP_HOME' => array(
'label' => 'WP_HOME',
'value' => ( defined( 'WP_HOME' ) ? WP_HOME : __( 'Undefined' ) ),
'debug' => ( defined( 'WP_HOME' ) ? WP_HOME : 'undefined' ),
),
'WP_SITEURL' => array(
'label' => 'WP_SITEURL',
'value' => ( defined( 'WP_SITEURL' ) ? WP_SITEURL : __( 'Undefined' ) ),
'debug' => ( defined( 'WP_SITEURL' ) ? WP_SITEURL : 'undefined' ),
),
'WP_CONTENT_DIR' => array(
'label' => 'WP_CONTENT_DIR',
'value' => WP_CONTENT_DIR,
),
'WP_PLUGIN_DIR' => array(
'label' => 'WP_PLUGIN_DIR',
'value' => WP_PLUGIN_DIR,
),
'WP_MEMORY_LIMIT' => array(
'label' => 'WP_MEMORY_LIMIT',
'value' => WP_MEMORY_LIMIT,
),
'WP_MAX_MEMORY_LIMIT' => array(
'label' => 'WP_MAX_MEMORY_LIMIT',
'value' => WP_MAX_MEMORY_LIMIT,
),
'WP_DEBUG' => array(
'label' => 'WP_DEBUG',
'value' => WP_DEBUG ? __( 'Enabled' ) : __( 'Disabled' ),
'debug' => WP_DEBUG,
),
'WP_DEBUG_DISPLAY' => array(
'label' => 'WP_DEBUG_DISPLAY',
'value' => WP_DEBUG_DISPLAY ? __( 'Enabled' ) : __( 'Disabled' ),
'debug' => WP_DEBUG_DISPLAY,
),
'WP_DEBUG_LOG' => array(
'label' => 'WP_DEBUG_LOG',
'value' => $wp_debug_log_value,
'debug' => WP_DEBUG_LOG,
),
'SCRIPT_DEBUG' => array(
'label' => 'SCRIPT_DEBUG',
'value' => SCRIPT_DEBUG ? __( 'Enabled' ) : __( 'Disabled' ),
'debug' => SCRIPT_DEBUG,
),
'WP_CACHE' => array(
'label' => 'WP_CACHE',
'value' => WP_CACHE ? __( 'Enabled' ) : __( 'Disabled' ),
'debug' => WP_CACHE,
),
'CONCATENATE_SCRIPTS' => array(
'label' => 'CONCATENATE_SCRIPTS',
'value' => $concatenate_scripts,
'debug' => $concatenate_scripts_debug,
),
'COMPRESS_SCRIPTS' => array(
'label' => 'COMPRESS_SCRIPTS',
'value' => $compress_scripts,
'debug' => $compress_scripts_debug,
),
'COMPRESS_CSS' => array(
'label' => 'COMPRESS_CSS',
'value' => $compress_css,
'debug' => $compress_css_debug,
),
'WP_ENVIRONMENT_TYPE' => array(
'label' => 'WP_ENVIRONMENT_TYPE',
'value' => $wp_environment_type,
'debug' => $wp_environment_type,
),
'DB_CHARSET' => array(
'label' => 'DB_CHARSET',
'value' => ( defined( 'DB_CHARSET' ) ? DB_CHARSET : __( 'Undefined' ) ),
'debug' => ( defined( 'DB_CHARSET' ) ? DB_CHARSET : 'undefined' ),
),
'DB_COLLATE' => array(
'label' => 'DB_COLLATE',
'value' => ( defined( 'DB_COLLATE' ) ? DB_COLLATE : __( 'Undefined' ) ),
'debug' => ( defined( 'DB_COLLATE' ) ? DB_COLLATE : 'undefined' ),
),
),
);
$is_writable_abspath = wp_is_writable( ABSPATH );
$is_writable_wp_content_dir = wp_is_writable( WP_CONTENT_DIR );
$is_writable_upload_dir = wp_is_writable( $upload_dir['basedir'] );
$is_writable_wp_plugin_dir = wp_is_writable( WP_PLUGIN_DIR );
$is_writable_template_directory = wp_is_writable( get_theme_root( get_template() ) );
$info['wp-filesystem'] = array(
'label' => __( 'Filesystem Permissions' ),
'description' => __( 'Shows whether WordPress is able to write to the directories it needs access to.' ),
'fields' => array(
'wordpress' => array(
'label' => __( 'The main WordPress directory' ),
'value' => ( $is_writable_abspath ? __( 'Writable' ) : __( 'Not writable' ) ),
'debug' => ( $is_writable_abspath ? 'writable' : 'not writable' ),
),
'wp-content' => array(
'label' => __( 'The wp-content directory' ),
'value' => ( $is_writable_wp_content_dir ? __( 'Writable' ) : __( 'Not writable' ) ),
'debug' => ( $is_writable_wp_content_dir ? 'writable' : 'not writable' ),
),
'uploads' => array(
'label' => __( 'The uploads directory' ),
'value' => ( $is_writable_upload_dir ? __( 'Writable' ) : __( 'Not writable' ) ),
'debug' => ( $is_writable_upload_dir ? 'writable' : 'not writable' ),
),
'plugins' => array(
'label' => __( 'The plugins directory' ),
'value' => ( $is_writable_wp_plugin_dir ? __( 'Writable' ) : __( 'Not writable' ) ),
'debug' => ( $is_writable_wp_plugin_dir ? 'writable' : 'not writable' ),
),
'themes' => array(
'label' => __( 'The themes directory' ),
'value' => ( $is_writable_template_directory ? __( 'Writable' ) : __( 'Not writable' ) ),
'debug' => ( $is_writable_template_directory ? 'writable' : 'not writable' ),
),
),
);
// Conditionally add debug information for multisite setups.
if ( is_multisite() ) {
$network_query = new WP_Network_Query();
$network_ids = $network_query->query(
array(
'fields' => 'ids',
'number' => 100,
'no_found_rows' => false,
)
);
$site_count = 0;
foreach ( $network_ids as $network_id ) {
$site_count += get_blog_count( $network_id );
}
$info['wp-core']['fields']['site_count'] = array(
'label' => __( 'Site count' ),
'value' => $site_count,
);
$info['wp-core']['fields']['network_count'] = array(
'label' => __( 'Network count' ),
'value' => $network_query->found_networks,
);
}
$info['wp-core']['fields']['user_count'] = array(
'label' => __( 'User count' ),
'value' => get_user_count(),
);
// WordPress features requiring processing.
$wp_dotorg = wp_remote_get( 'https://wordpress.org', array( 'timeout' => 10 ) );
if ( ! is_wp_error( $wp_dotorg ) ) {
$info['wp-core']['fields']['dotorg_communication'] = array(
'label' => __( 'Communication with WordPress.org' ),
'value' => __( 'WordPress.org is reachable' ),
'debug' => 'true',
);
} else {
$info['wp-core']['fields']['dotorg_communication'] = array(
'label' => __( 'Communication with WordPress.org' ),
'value' => sprintf(
/* translators: 1: The IP address WordPress.org resolves to. 2: The error returned by the lookup. */
__( 'Unable to reach WordPress.org at %1$s: %2$s' ),
gethostbyname( 'wordpress.org' ),
$wp_dotorg->get_error_message()
),
'debug' => $wp_dotorg->get_error_message(),
);
}
// Remove accordion for Directories and Sizes if in Multisite.
if ( ! $is_multisite ) {
$loading = __( 'Loading…' );
$info['wp-paths-sizes']['fields'] = array(
'wordpress_path' => array(
'label' => __( 'WordPress directory location' ),
'value' => untrailingslashit( ABSPATH ),
),
'wordpress_size' => array(
'label' => __( 'WordPress directory size' ),
'value' => $loading,
'debug' => 'loading...',
),
'uploads_path' => array(
'label' => __( 'Uploads directory location' ),
'value' => $upload_dir['basedir'],
),
'uploads_size' => array(
'label' => __( 'Uploads directory size' ),
'value' => $loading,
'debug' => 'loading...',
),
'themes_path' => array(
'label' => __( 'Themes directory location' ),
'value' => get_theme_root(),
),
'themes_size' => array(
'label' => __( 'Themes directory size' ),
'value' => $loading,
'debug' => 'loading...',
),
'plugins_path' => array(
'label' => __( 'Plugins directory location' ),
'value' => WP_PLUGIN_DIR,
),
'plugins_size' => array(
'label' => __( 'Plugins directory size' ),
'value' => $loading,
'debug' => 'loading...',
),
'database_size' => array(
'label' => __( 'Database size' ),
'value' => $loading,
'debug' => 'loading...',
),
'total_size' => array(
'label' => __( 'Total installation size' ),
'value' => $loading,
'debug' => 'loading...',
),
);
}
// Get a list of all drop-in replacements.
$dropins = get_dropins();
// Get dropins descriptions.
$dropin_descriptions = _get_dropins();
// Spare few function calls.
$not_available = __( 'Not available' );
foreach ( $dropins as $dropin_key => $dropin ) {
$info['wp-dropins']['fields'][ sanitize_text_field( $dropin_key ) ] = array(
'label' => $dropin_key,
'value' => $dropin_descriptions[ $dropin_key ][0],
'debug' => 'true',
);
}
// Populate the media fields.
$info['wp-media']['fields']['image_editor'] = array(
'label' => __( 'Active editor' ),
'value' => _wp_image_editor_choose(),
);
// Get ImageMagic information, if available.
if ( class_exists( 'Imagick' ) ) {
// Save the Imagick instance for later use.
$imagick = new Imagick();
$imagemagick_version = $imagick->getVersion();
} else {
$imagemagick_version = __( 'Not available' );
}
$info['wp-media']['fields']['imagick_module_version'] = array(
'label' => __( 'ImageMagick version number' ),
'value' => ( is_array( $imagemagick_version ) ? $imagemagick_version['versionNumber'] : $imagemagick_version ),
);
$info['wp-media']['fields']['imagemagick_version'] = array(
'label' => __( 'ImageMagick version string' ),
'value' => ( is_array( $imagemagick_version ) ? $imagemagick_version['versionString'] : $imagemagick_version ),
);
$imagick_version = phpversion( 'imagick' );
$info['wp-media']['fields']['imagick_version'] = array(
'label' => __( 'Imagick version' ),
'value' => ( $imagick_version ) ? $imagick_version : __( 'Not available' ),
);
if ( ! function_exists( 'ini_get' ) ) {
$info['wp-media']['fields']['ini_get'] = array(
'label' => __( 'File upload settings' ),
'value' => sprintf(
/* translators: %s: ini_get() */
__( 'Unable to determine some settings, as the %s function has been disabled.' ),
'ini_get()'
),
'debug' => 'ini_get() is disabled',
);
} else {
// Get the PHP ini directive values.
$post_max_size = ini_get( 'post_max_size' );
$upload_max_filesize = ini_get( 'upload_max_filesize' );
$max_file_uploads = ini_get( 'max_file_uploads' );
$effective = min( wp_convert_hr_to_bytes( $post_max_size ), wp_convert_hr_to_bytes( $upload_max_filesize ) );
// Add info in Media section.
$info['wp-media']['fields']['file_uploads'] = array(
'label' => __( 'File uploads' ),
'value' => empty( ini_get( 'file_uploads' ) ) ? __( 'Disabled' ) : __( 'Enabled' ),
'debug' => 'File uploads is turned off',
);
$info['wp-media']['fields']['post_max_size'] = array(
'label' => __( 'Max size of post data allowed' ),
'value' => $post_max_size,
);
$info['wp-media']['fields']['upload_max_filesize'] = array(
'label' => __( 'Max size of an uploaded file' ),
'value' => $upload_max_filesize,
);
$info['wp-media']['fields']['max_effective_size'] = array(
'label' => __( 'Max effective file size' ),
'value' => size_format( $effective ),
);
$info['wp-media']['fields']['max_file_uploads'] = array(
'label' => __( 'Max number of files allowed' ),
'value' => number_format( $max_file_uploads ),
);
}
// If Imagick is used as our editor, provide some more information about its limitations.
if ( 'WP_Image_Editor_Imagick' === _wp_image_editor_choose() && isset( $imagick ) && $imagick instanceof Imagick ) {
$limits = array(
'area' => ( defined( 'imagick::RESOURCETYPE_AREA' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_AREA ) ) : $not_available ),
'disk' => ( defined( 'imagick::RESOURCETYPE_DISK' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_DISK ) : $not_available ),
'file' => ( defined( 'imagick::RESOURCETYPE_FILE' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_FILE ) : $not_available ),
'map' => ( defined( 'imagick::RESOURCETYPE_MAP' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_MAP ) ) : $not_available ),
'memory' => ( defined( 'imagick::RESOURCETYPE_MEMORY' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_MEMORY ) ) : $not_available ),
'thread' => ( defined( 'imagick::RESOURCETYPE_THREAD' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_THREAD ) : $not_available ),
);
$limits_debug = array(
'imagick::RESOURCETYPE_AREA' => ( defined( 'imagick::RESOURCETYPE_AREA' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_AREA ) ) : 'not available' ),
'imagick::RESOURCETYPE_DISK' => ( defined( 'imagick::RESOURCETYPE_DISK' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_DISK ) : 'not available' ),
'imagick::RESOURCETYPE_FILE' => ( defined( 'imagick::RESOURCETYPE_FILE' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_FILE ) : 'not available' ),
'imagick::RESOURCETYPE_MAP' => ( defined( 'imagick::RESOURCETYPE_MAP' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_MAP ) ) : 'not available' ),
'imagick::RESOURCETYPE_MEMORY' => ( defined( 'imagick::RESOURCETYPE_MEMORY' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_MEMORY ) ) : 'not available' ),
'imagick::RESOURCETYPE_THREAD' => ( defined( 'imagick::RESOURCETYPE_THREAD' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_THREAD ) : 'not available' ),
);
$info['wp-media']['fields']['imagick_limits'] = array(
'label' => __( 'Imagick Resource Limits' ),
'value' => $limits,
'debug' => $limits_debug,
);
try {
$formats = Imagick::queryFormats( '*' );
} catch ( Exception $e ) {
$formats = array();
}
$info['wp-media']['fields']['imagemagick_file_formats'] = array(
'label' => __( 'ImageMagick supported file formats' ),
'value' => ( empty( $formats ) ) ? __( 'Unable to determine' ) : implode( ', ', $formats ),
'debug' => ( empty( $formats ) ) ? 'Unable to determine' : implode( ', ', $formats ),
);
}
// Get GD information, if available.
if ( function_exists( 'gd_info' ) ) {
$gd = gd_info();
} else {
$gd = false;
}
$info['wp-media']['fields']['gd_version'] = array(
'label' => __( 'GD version' ),
'value' => ( is_array( $gd ) ? $gd['GD Version'] : $not_available ),
'debug' => ( is_array( $gd ) ? $gd['GD Version'] : 'not available' ),
);
$gd_image_formats = array();
$gd_supported_formats = array(
'GIF Create' => 'GIF',
'JPEG' => 'JPEG',
'PNG' => 'PNG',
'WebP' => 'WebP',
'BMP' => 'BMP',
'AVIF' => 'AVIF',
'HEIF' => 'HEIF',
'TIFF' => 'TIFF',
'XPM' => 'XPM',
);
foreach ( $gd_supported_formats as $format_key => $format ) {
$index = $format_key . ' Support';
if ( isset( $gd[ $index ] ) && $gd[ $index ] ) {
array_push( $gd_image_formats, $format );
}
}
if ( ! empty( $gd_image_formats ) ) {
$info['wp-media']['fields']['gd_formats'] = array(
'label' => __( 'GD supported file formats' ),
'value' => implode( ', ', $gd_image_formats ),
);
}
// Get Ghostscript information, if available.
if ( function_exists( 'exec' ) ) {
$gs = exec( 'gs --version' );
if ( empty( $gs ) ) {
$gs = $not_available;
$gs_debug = 'not available';
} else {
$gs_debug = $gs;
}
} else {
$gs = __( 'Unable to determine if Ghostscript is installed' );
$gs_debug = 'unknown';
}
$info['wp-media']['fields']['ghostscript_version'] = array(
'label' => __( 'Ghostscript version' ),
'value' => $gs,
'debug' => $gs_debug,
);
// Populate the server debug fields.
if ( function_exists( 'php_uname' ) ) {
$server_architecture = sprintf( '%s %s %s', php_uname( 's' ), php_uname( 'r' ), php_uname( 'm' ) );
} else {
$server_architecture = 'unknown';
}
$php_version_debug = PHP_VERSION;
// Whether PHP supports 64-bit.
$php64bit = ( PHP_INT_SIZE * 8 === 64 );
$php_version = sprintf(
'%s %s',
$php_version_debug,
( $php64bit ? __( '(Supports 64bit values)' ) : __( '(Does not support 64bit values)' ) )
);
if ( $php64bit ) {
$php_version_debug .= ' 64bit';
}
if ( function_exists( 'php_sapi_name' ) ) {
$php_sapi = php_sapi_name();
} else {
$php_sapi = 'unknown';
}
$info['wp-server']['fields']['server_architecture'] = array(
'label' => __( 'Server architecture' ),
'value' => ( 'unknown' !== $server_architecture ? $server_architecture : __( 'Unable to determine server architecture' ) ),
'debug' => $server_architecture,
);
$info['wp-server']['fields']['httpd_software'] = array(
'label' => __( 'Web server' ),
'value' => ( isset( $_SERVER['SERVER_SOFTWARE'] ) ? $_SERVER['SERVER_SOFTWARE'] : __( 'Unable to determine what web server software is used' ) ),
'debug' => ( isset( $_SERVER['SERVER_SOFTWARE'] ) ? $_SERVER['SERVER_SOFTWARE'] : 'unknown' ),
);
$info['wp-server']['fields']['php_version'] = array(
'label' => __( 'PHP version' ),
'value' => $php_version,
'debug' => $php_version_debug,
);
$info['wp-server']['fields']['php_sapi'] = array(
'label' => __( 'PHP SAPI' ),
'value' => ( 'unknown' !== $php_sapi ? $php_sapi : __( 'Unable to determine PHP SAPI' ) ),
'debug' => $php_sapi,
);
// Some servers disable `ini_set()` and `ini_get()`, we check this before trying to get configuration values.
if ( ! function_exists( 'ini_get' ) ) {
$info['wp-server']['fields']['ini_get'] = array(
'label' => __( 'Server settings' ),
'value' => sprintf(
/* translators: %s: ini_get() */
__( 'Unable to determine some settings, as the %s function has been disabled.' ),
'ini_get()'
),
'debug' => 'ini_get() is disabled',
);
} else {
$info['wp-server']['fields']['max_input_variables'] = array(
'label' => __( 'PHP max input variables' ),
'value' => ini_get( 'max_input_vars' ),
);
$info['wp-server']['fields']['time_limit'] = array(
'label' => __( 'PHP time limit' ),
'value' => ini_get( 'max_execution_time' ),
);
if ( WP_Site_Health::get_instance()->php_memory_limit !== ini_get( 'memory_limit' ) ) {
$info['wp-server']['fields']['memory_limit'] = array(
'label' => __( 'PHP memory limit' ),
'value' => WP_Site_Health::get_instance()->php_memory_limit,
);
$info['wp-server']['fields']['admin_memory_limit'] = array(
'label' => __( 'PHP memory limit (only for admin screens)' ),
'value' => ini_get( 'memory_limit' ),
);
} else {
$info['wp-server']['fields']['memory_limit'] = array(
'label' => __( 'PHP memory limit' ),
'value' => ini_get( 'memory_limit' ),
);
}
$info['wp-server']['fields']['max_input_time'] = array(
'label' => __( 'Max input time' ),
'value' => ini_get( 'max_input_time' ),
);
$info['wp-server']['fields']['upload_max_filesize'] = array(
'label' => __( 'Upload max filesize' ),
'value' => ini_get( 'upload_max_filesize' ),
);
$info['wp-server']['fields']['php_post_max_size'] = array(
'label' => __( 'PHP post max size' ),
'value' => ini_get( 'post_max_size' ),
);
}
if ( function_exists( 'curl_version' ) ) {
$curl = curl_version();
$info['wp-server']['fields']['curl_version'] = array(
'label' => __( 'cURL version' ),
'value' => sprintf( '%s %s', $curl['version'], $curl['ssl_version'] ),
);
} else {
$info['wp-server']['fields']['curl_version'] = array(
'label' => __( 'cURL version' ),
'value' => $not_available,
'debug' => 'not available',
);
}
// SUHOSIN.
$suhosin_loaded = ( extension_loaded( 'suhosin' ) || ( defined( 'SUHOSIN_PATCH' ) && constant( 'SUHOSIN_PATCH' ) ) );
$info['wp-server']['fields']['suhosin'] = array(
'label' => __( 'Is SUHOSIN installed?' ),
'value' => ( $suhosin_loaded ? __( 'Yes' ) : __( 'No' ) ),
'debug' => $suhosin_loaded,
);
// Imagick.
$imagick_loaded = extension_loaded( 'imagick' );
$info['wp-server']['fields']['imagick_availability'] = array(
'label' => __( 'Is the Imagick library available?' ),
'value' => ( $imagick_loaded ? __( 'Yes' ) : __( 'No' ) ),
'debug' => $imagick_loaded,
);
// Pretty permalinks.
$pretty_permalinks_supported = got_url_rewrite();
$info['wp-server']['fields']['pretty_permalinks'] = array(
'label' => __( 'Are pretty permalinks supported?' ),
'value' => ( $pretty_permalinks_supported ? __( 'Yes' ) : __( 'No' ) ),
'debug' => $pretty_permalinks_supported,
);
// Check if a .htaccess file exists.
if ( is_file( ABSPATH . '.htaccess' ) ) {
// If the file exists, grab the content of it.
$htaccess_content = file_get_contents( ABSPATH . '.htaccess' );
// Filter away the core WordPress rules.
$filtered_htaccess_content = trim( preg_replace( '/\# BEGIN WordPress[\s\S]+?# END WordPress/si', '', $htaccess_content ) );
$filtered_htaccess_content = ! empty( $filtered_htaccess_content );
if ( $filtered_htaccess_content ) {
/* translators: %s: .htaccess */
$htaccess_rules_string = sprintf( __( 'Custom rules have been added to your %s file.' ), '.htaccess' );
} else {
/* translators: %s: .htaccess */
$htaccess_rules_string = sprintf( __( 'Your %s file contains only core WordPress features.' ), '.htaccess' );
}
$info['wp-server']['fields']['htaccess_extra_rules'] = array(
'label' => __( '.htaccess rules' ),
'value' => $htaccess_rules_string,
'debug' => $filtered_htaccess_content,
);
}
// Populate the database debug fields.
if ( is_resource( $wpdb->dbh ) ) {
// Old mysql extension.
$extension = 'mysql';
} elseif ( is_object( $wpdb->dbh ) ) {
// mysqli or PDO.
$extension = get_class( $wpdb->dbh );
} else {
// Unknown sql extension.
$extension = null;
}
$server = $wpdb->get_var( 'SELECT VERSION()' );
if ( isset( $wpdb->use_mysqli ) && $wpdb->use_mysqli ) {
$client_version = $wpdb->dbh->client_info;
} else {
// phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysql_get_client_info,PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved
if ( preg_match( '|[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}|', mysql_get_client_info(), $matches ) ) {
$client_version = $matches[0];
} else {
$client_version = null;
}
}
$info['wp-database']['fields']['extension'] = array(
'label' => __( 'Extension' ),
'value' => $extension,
);
$info['wp-database']['fields']['server_version'] = array(
'label' => __( 'Server version' ),
'value' => $server,
);
$info['wp-database']['fields']['client_version'] = array(
'label' => __( 'Client version' ),
'value' => $client_version,
);
$info['wp-database']['fields']['database_user'] = array(
'label' => __( 'Database username' ),
'value' => $wpdb->dbuser,
'private' => true,
);
$info['wp-database']['fields']['database_host'] = array(
'label' => __( 'Database host' ),
'value' => $wpdb->dbhost,
'private' => true,
);
$info['wp-database']['fields']['database_name'] = array(
'label' => __( 'Database name' ),
'value' => $wpdb->dbname,
'private' => true,
);
$info['wp-database']['fields']['database_prefix'] = array(
'label' => __( 'Table prefix' ),
'value' => $wpdb->prefix,
'private' => true,
);
$info['wp-database']['fields']['database_charset'] = array(
'label' => __( 'Database charset' ),
'value' => $wpdb->charset,
'private' => true,
);
$info['wp-database']['fields']['database_collate'] = array(
'label' => __( 'Database collation' ),
'value' => $wpdb->collate,
'private' => true,
);
$info['wp-database']['fields']['max_allowed_packet'] = array(
'label' => __( 'Max allowed packet size' ),
'value' => self::get_mysql_var( 'max_allowed_packet' ),
);
$info['wp-database']['fields']['max_connections'] = array(
'label' => __( 'Max connections number' ),
'value' => self::get_mysql_var( 'max_connections' ),
);
// List must use plugins if there are any.
$mu_plugins = get_mu_plugins();
foreach ( $mu_plugins as $plugin_path => $plugin ) {
$plugin_version = $plugin['Version'];
$plugin_author = $plugin['Author'];
$plugin_version_string = __( 'No version or author information is available.' );
$plugin_version_string_debug = 'author: (undefined), version: (undefined)';
if ( ! empty( $plugin_version ) && ! empty( $plugin_author ) ) {
/* translators: 1: Plugin version number. 2: Plugin author name. */
$plugin_version_string = sprintf( __( 'Version %1$s by %2$s' ), $plugin_version, $plugin_author );
$plugin_version_string_debug = sprintf( 'version: %s, author: %s', $plugin_version, $plugin_author );
} else {
if ( ! empty( $plugin_author ) ) {
/* translators: %s: Plugin author name. */
$plugin_version_string = sprintf( __( 'By %s' ), $plugin_author );
$plugin_version_string_debug = sprintf( 'author: %s, version: (undefined)', $plugin_author );
}
if ( ! empty( $plugin_version ) ) {
/* translators: %s: Plugin version number. */
$plugin_version_string = sprintf( __( 'Version %s' ), $plugin_version );
$plugin_version_string_debug = sprintf( 'author: (undefined), version: %s', $plugin_version );
}
}
$info['wp-mu-plugins']['fields'][ sanitize_text_field( $plugin['Name'] ) ] = array(
'label' => $plugin['Name'],
'value' => $plugin_version_string,
'debug' => $plugin_version_string_debug,
);
}
// List all available plugins.
$plugins = get_plugins();
$plugin_updates = get_plugin_updates();
$transient = get_site_transient( 'update_plugins' );
$auto_updates = array();
$auto_updates_enabled = wp_is_auto_update_enabled_for_type( 'plugin' );
if ( $auto_updates_enabled ) {
$auto_updates = (array) get_site_option( 'auto_update_plugins', array() );
}
foreach ( $plugins as $plugin_path => $plugin ) {
$plugin_part = ( is_plugin_active( $plugin_path ) ) ? 'wp-plugins-active' : 'wp-plugins-inactive';
$plugin_version = $plugin['Version'];
$plugin_author = $plugin['Author'];
$plugin_version_string = __( 'No version or author information is available.' );
$plugin_version_string_debug = 'author: (undefined), version: (undefined)';
if ( ! empty( $plugin_version ) && ! empty( $plugin_author ) ) {
/* translators: 1: Plugin version number. 2: Plugin author name. */
$plugin_version_string = sprintf( __( 'Version %1$s by %2$s' ), $plugin_version, $plugin_author );
$plugin_version_string_debug = sprintf( 'version: %s, author: %s', $plugin_version, $plugin_author );
} else {
if ( ! empty( $plugin_author ) ) {
/* translators: %s: Plugin author name. */
$plugin_version_string = sprintf( __( 'By %s' ), $plugin_author );
$plugin_version_string_debug = sprintf( 'author: %s, version: (undefined)', $plugin_author );
}
if ( ! empty( $plugin_version ) ) {
/* translators: %s: Plugin version number. */
$plugin_version_string = sprintf( __( 'Version %s' ), $plugin_version );
$plugin_version_string_debug = sprintf( 'author: (undefined), version: %s', $plugin_version );
}
}
if ( array_key_exists( $plugin_path, $plugin_updates ) ) {
/* translators: %s: Latest plugin version number. */
$plugin_version_string .= ' ' . sprintf( __( '(Latest version: %s)' ), $plugin_updates[ $plugin_path ]->update->new_version );
$plugin_version_string_debug .= sprintf( ' (latest version: %s)', $plugin_updates[ $plugin_path ]->update->new_version );
}
if ( $auto_updates_enabled ) {
if ( isset( $transient->response[ $plugin_path ] ) ) {
$item = $transient->response[ $plugin_path ];
} elseif ( isset( $transient->no_update[ $plugin_path ] ) ) {
$item = $transient->no_update[ $plugin_path ];
} else {
$item = array(
'id' => $plugin_path,
'slug' => '',
'plugin' => $plugin_path,
'new_version' => '',
'url' => '',
'package' => '',
'icons' => array(),
'banners' => array(),
'banners_rtl' => array(),
'tested' => '',
'requires_php' => '',
'compatibility' => new stdClass(),
);
$item = wp_parse_args( $plugin, $item );
}
$auto_update_forced = wp_is_auto_update_forced_for_item( 'plugin', null, (object) $item );
if ( ! is_null( $auto_update_forced ) ) {
$enabled = $auto_update_forced;
} else {
$enabled = in_array( $plugin_path, $auto_updates, true );
}
if ( $enabled ) {
$auto_updates_string = __( 'Auto-updates enabled' );
} else {
$auto_updates_string = __( 'Auto-updates disabled' );
}
/**
* Filters the text string of the auto-updates setting for each plugin in the Site Health debug data.
*
* @since 5.5.0
*
* @param string $auto_updates_string The string output for the auto-updates column.
* @param string $plugin_path The path to the plugin file.
* @param array $plugin An array of plugin data.
* @param bool $enabled Whether auto-updates are enabled for this item.
*/
$auto_updates_string = apply_filters( 'plugin_auto_update_debug_string', $auto_updates_string, $plugin_path, $plugin, $enabled );
$plugin_version_string .= ' | ' . $auto_updates_string;
$plugin_version_string_debug .= ', ' . $auto_updates_string;
}
$info[ $plugin_part ]['fields'][ sanitize_text_field( $plugin['Name'] ) ] = array(
'label' => $plugin['Name'],
'value' => $plugin_version_string,
'debug' => $plugin_version_string_debug,
);
}
// Populate the section for the currently active theme.
global $_wp_theme_features;
$theme_features = array();
if ( ! empty( $_wp_theme_features ) ) {
foreach ( $_wp_theme_features as $feature => $options ) {
$theme_features[] = $feature;
}
}
$active_theme = wp_get_theme();
$theme_updates = get_theme_updates();
$transient = get_site_transient( 'update_themes' );
$active_theme_version = $active_theme->version;
$active_theme_version_debug = $active_theme_version;
$auto_updates = array();
$auto_updates_enabled = wp_is_auto_update_enabled_for_type( 'theme' );
if ( $auto_updates_enabled ) {
$auto_updates = (array) get_site_option( 'auto_update_themes', array() );
}
if ( array_key_exists( $active_theme->stylesheet, $theme_updates ) ) {
$theme_update_new_version = $theme_updates[ $active_theme->stylesheet ]->update['new_version'];
/* translators: %s: Latest theme version number. */
$active_theme_version .= ' ' . sprintf( __( '(Latest version: %s)' ), $theme_update_new_version );
$active_theme_version_debug .= sprintf( ' (latest version: %s)', $theme_update_new_version );
}
$active_theme_author_uri = $active_theme->display( 'AuthorURI' );
if ( $active_theme->parent_theme ) {
$active_theme_parent_theme = sprintf(
/* translators: 1: Theme name. 2: Theme slug. */
__( '%1$s (%2$s)' ),
$active_theme->parent_theme,
$active_theme->template
);
$active_theme_parent_theme_debug = sprintf(
'%s (%s)',
$active_theme->parent_theme,
$active_theme->template
);
} else {
$active_theme_parent_theme = __( 'None' );
$active_theme_parent_theme_debug = 'none';
}
$info['wp-active-theme']['fields'] = array(
'name' => array(
'label' => __( 'Name' ),
'value' => sprintf(
/* translators: 1: Theme name. 2: Theme slug. */
__( '%1$s (%2$s)' ),
$active_theme->name,
$active_theme->stylesheet
),
),
'version' => array(
'label' => __( 'Version' ),
'value' => $active_theme_version,
'debug' => $active_theme_version_debug,
),
'author' => array(
'label' => __( 'Author' ),
'value' => wp_kses( $active_theme->author, array() ),
),
'author_website' => array(
'label' => __( 'Author website' ),
'value' => ( $active_theme_author_uri ? $active_theme_author_uri : __( 'Undefined' ) ),
'debug' => ( $active_theme_author_uri ? $active_theme_author_uri : '(undefined)' ),
),
'parent_theme' => array(
'label' => __( 'Parent theme' ),
'value' => $active_theme_parent_theme,
'debug' => $active_theme_parent_theme_debug,
),
'theme_features' => array(
'label' => __( 'Theme features' ),
'value' => implode( ', ', $theme_features ),
),
'theme_path' => array(
'label' => __( 'Theme directory location' ),
'value' => get_stylesheet_directory(),
),
);
if ( $auto_updates_enabled ) {
if ( isset( $transient->response[ $active_theme->stylesheet ] ) ) {
$item = $transient->response[ $active_theme->stylesheet ];
} elseif ( isset( $transient->no_update[ $active_theme->stylesheet ] ) ) {
$item = $transient->no_update[ $active_theme->stylesheet ];
} else {
$item = array(
'theme' => $active_theme->stylesheet,
'new_version' => $active_theme->version,
'url' => '',
'package' => '',
'requires' => '',
'requires_php' => '',
);
}
$auto_update_forced = wp_is_auto_update_forced_for_item( 'theme', null, (object) $item );
if ( ! is_null( $auto_update_forced ) ) {
$enabled = $auto_update_forced;
} else {
$enabled = in_array( $active_theme->stylesheet, $auto_updates, true );
}
if ( $enabled ) {
$auto_updates_string = __( 'Enabled' );
} else {
$auto_updates_string = __( 'Disabled' );
}
/** This filter is documented in wp-admin/includes/class-wp-debug-data.php */
$auto_updates_string = apply_filters( 'theme_auto_update_debug_string', $auto_updates_string, $active_theme, $enabled );
$info['wp-active-theme']['fields']['auto_update'] = array(
'label' => __( 'Auto-updates' ),
'value' => $auto_updates_string,
'debug' => $auto_updates_string,
);
}
$parent_theme = $active_theme->parent();
if ( $parent_theme ) {
$parent_theme_version = $parent_theme->version;
$parent_theme_version_debug = $parent_theme_version;
if ( array_key_exists( $parent_theme->stylesheet, $theme_updates ) ) {
$parent_theme_update_new_version = $theme_updates[ $parent_theme->stylesheet ]->update['new_version'];
/* translators: %s: Latest theme version number. */
$parent_theme_version .= ' ' . sprintf( __( '(Latest version: %s)' ), $parent_theme_update_new_version );
$parent_theme_version_debug .= sprintf( ' (latest version: %s)', $parent_theme_update_new_version );
}
$parent_theme_author_uri = $parent_theme->display( 'AuthorURI' );
$info['wp-parent-theme']['fields'] = array(
'name' => array(
'label' => __( 'Name' ),
'value' => sprintf(
/* translators: 1: Theme name. 2: Theme slug. */
__( '%1$s (%2$s)' ),
$parent_theme->name,
$parent_theme->stylesheet
),
),
'version' => array(
'label' => __( 'Version' ),
'value' => $parent_theme_version,
'debug' => $parent_theme_version_debug,
),
'author' => array(
'label' => __( 'Author' ),
'value' => wp_kses( $parent_theme->author, array() ),
),
'author_website' => array(
'label' => __( 'Author website' ),
'value' => ( $parent_theme_author_uri ? $parent_theme_author_uri : __( 'Undefined' ) ),
'debug' => ( $parent_theme_author_uri ? $parent_theme_author_uri : '(undefined)' ),
),
'theme_path' => array(
'label' => __( 'Theme directory location' ),
'value' => get_template_directory(),
),
);
if ( $auto_updates_enabled ) {
if ( isset( $transient->response[ $parent_theme->stylesheet ] ) ) {
$item = $transient->response[ $parent_theme->stylesheet ];
} elseif ( isset( $transient->no_update[ $parent_theme->stylesheet ] ) ) {
$item = $transient->no_update[ $parent_theme->stylesheet ];
} else {
$item = array(
'theme' => $parent_theme->stylesheet,
'new_version' => $parent_theme->version,
'url' => '',
'package' => '',
'requires' => '',
'requires_php' => '',
);
}
$auto_update_forced = wp_is_auto_update_forced_for_item( 'theme', null, (object) $item );
if ( ! is_null( $auto_update_forced ) ) {
$enabled = $auto_update_forced;
} else {
$enabled = in_array( $parent_theme->stylesheet, $auto_updates, true );
}
if ( $enabled ) {
$parent_theme_auto_update_string = __( 'Enabled' );
} else {
$parent_theme_auto_update_string = __( 'Disabled' );
}
/** This filter is documented in wp-admin/includes/class-wp-debug-data.php */
$parent_theme_auto_update_string = apply_filters( 'theme_auto_update_debug_string', $auto_updates_string, $parent_theme, $enabled );
$info['wp-parent-theme']['fields']['auto_update'] = array(
'label' => __( 'Auto-update' ),
'value' => $parent_theme_auto_update_string,
'debug' => $parent_theme_auto_update_string,
);
}
}
// Populate a list of all themes available in the install.
$all_themes = wp_get_themes();
foreach ( $all_themes as $theme_slug => $theme ) {
// Exclude the currently active theme from the list of all themes.
if ( $active_theme->stylesheet === $theme_slug ) {
continue;
}
// Exclude the currently active parent theme from the list of all themes.
if ( ! empty( $parent_theme ) && $parent_theme->stylesheet === $theme_slug ) {
continue;
}
$theme_version = $theme->version;
$theme_author = $theme->author;
// Sanitize.
$theme_author = wp_kses( $theme_author, array() );
$theme_version_string = __( 'No version or author information is available.' );
$theme_version_string_debug = 'undefined';
if ( ! empty( $theme_version ) && ! empty( $theme_author ) ) {
/* translators: 1: Theme version number. 2: Theme author name. */
$theme_version_string = sprintf( __( 'Version %1$s by %2$s' ), $theme_version, $theme_author );
$theme_version_string_debug = sprintf( 'version: %s, author: %s', $theme_version, $theme_author );
} else {
if ( ! empty( $theme_author ) ) {
/* translators: %s: Theme author name. */
$theme_version_string = sprintf( __( 'By %s' ), $theme_author );
$theme_version_string_debug = sprintf( 'author: %s, version: (undefined)', $theme_author );
}
if ( ! empty( $theme_version ) ) {
/* translators: %s: Theme version number. */
$theme_version_string = sprintf( __( 'Version %s' ), $theme_version );
$theme_version_string_debug = sprintf( 'author: (undefined), version: %s', $theme_version );
}
}
if ( array_key_exists( $theme_slug, $theme_updates ) ) {
/* translators: %s: Latest theme version number. */
$theme_version_string .= ' ' . sprintf( __( '(Latest version: %s)' ), $theme_updates[ $theme_slug ]->update['new_version'] );
$theme_version_string_debug .= sprintf( ' (latest version: %s)', $theme_updates[ $theme_slug ]->update['new_version'] );
}
if ( $auto_updates_enabled ) {
if ( isset( $transient->response[ $theme_slug ] ) ) {
$item = $transient->response[ $theme_slug ];
} elseif ( isset( $transient->no_update[ $theme_slug ] ) ) {
$item = $transient->no_update[ $theme_slug ];
} else {
$item = array(
'theme' => $theme_slug,
'new_version' => $theme->version,
'url' => '',
'package' => '',
'requires' => '',
'requires_php' => '',
);
}
$auto_update_forced = wp_is_auto_update_forced_for_item( 'theme', null, (object) $item );
if ( ! is_null( $auto_update_forced ) ) {
$enabled = $auto_update_forced;
} else {
$enabled = in_array( $theme_slug, $auto_updates, true );
}
if ( $enabled ) {
$auto_updates_string = __( 'Auto-updates enabled' );
} else {
$auto_updates_string = __( 'Auto-updates disabled' );
}
/**
* Filters the text string of the auto-updates setting for each theme in the Site Health debug data.
*
* @since 5.5.0
*
* @param string $auto_updates_string The string output for the auto-updates column.
* @param WP_Theme $theme An object of theme data.
* @param bool $enabled Whether auto-updates are enabled for this item.
*/
$auto_updates_string = apply_filters( 'theme_auto_update_debug_string', $auto_updates_string, $theme, $enabled );
$theme_version_string .= ' | ' . $auto_updates_string;
$theme_version_string_debug .= ', ' . $auto_updates_string;
}
$info['wp-themes-inactive']['fields'][ sanitize_text_field( $theme->name ) ] = array(
'label' => sprintf(
/* translators: 1: Theme name. 2: Theme slug. */
__( '%1$s (%2$s)' ),
$theme->name,
$theme_slug
),
'value' => $theme_version_string,
'debug' => $theme_version_string_debug,
);
}
// Add more filesystem checks.
if ( defined( 'WPMU_PLUGIN_DIR' ) && is_dir( WPMU_PLUGIN_DIR ) ) {
$is_writable_wpmu_plugin_dir = wp_is_writable( WPMU_PLUGIN_DIR );
$info['wp-filesystem']['fields']['mu-plugins'] = array(
'label' => __( 'The must use plugins directory' ),
'value' => ( $is_writable_wpmu_plugin_dir ? __( 'Writable' ) : __( 'Not writable' ) ),
'debug' => ( $is_writable_wpmu_plugin_dir ? 'writable' : 'not writable' ),
);
}
/**
* Filters the debug information shown on the Tools -> Site Health -> Info screen.
*
* Plugin or themes may wish to introduce their own debug information without creating
* additional admin pages. They can utilize this filter to introduce their own sections
* or add more data to existing sections.
*
* Array keys for sections added by core are all prefixed with `wp-`. Plugins and themes
* should use their own slug as a prefix, both for consistency as well as avoiding
* key collisions. Note that the array keys are used as labels for the copied data.
*
* All strings are expected to be plain text except `$description` that can contain
* inline HTML tags (see below).
*
* @since 5.2.0
*
* @param array $args {
* The debug information to be added to the core information page.
*
* This is an associative multi-dimensional array, up to three levels deep.
* The topmost array holds the sections, keyed by section ID.
*
* @type array ...$0 {
* Each section has a `$fields` associative array (see below), and each `$value` in `$fields`
* can be another associative array of name/value pairs when there is more structured data
* to display.
*
* @type string $label Required. The title for this section of the debug output.
* @type string $description Optional. A description for your information section which
* may contain basic HTML markup, inline tags only as it is
* outputted in a paragraph.
* @type bool $show_count Optional. If set to `true`, the amount of fields will be included
* in the title for this section. Default false.
* @type bool $private Optional. If set to `true`, the section and all associated fields
* will be excluded from the copied data. Default false.
* @type array $fields {
* Required. An associative array containing the fields to be displayed in the section,
* keyed by field ID.
*
* @type array ...$0 {
* An associative array containing the data to be displayed for the field.
*
* @type string $label Required. The label for this piece of information.
* @type mixed $value Required. The output that is displayed for this field.
* Text should be translated. Can be an associative array
* that is displayed as name/value pairs.
* Accepted types: `string|int|float|(string|int|float)[]`.
* @type string $debug Optional. The output that is used for this field when
* the user copies the data. It should be more concise and
* not translated. If not set, the content of `$value`
* is used. Note that the array keys are used as labels
* for the copied data.
* @type bool $private Optional. If set to `true`, the field will be excluded
* from the copied data, allowing you to show, for example,
* API keys here. Default false.
* }
* }
* }
* }
*/
$info = apply_filters( 'debug_information', $info );
return $info;
}
```
[apply\_filters( 'debug\_information', array $args )](../../hooks/debug_information)
Filters the debug information shown on the Tools -> Site Health -> Info screen.
[apply\_filters( 'plugin\_auto\_update\_debug\_string', string $auto\_updates\_string, string $plugin\_path, array $plugin, bool $enabled )](../../hooks/plugin_auto_update_debug_string)
Filters the text string of the auto-updates setting for each plugin in the Site Health debug data.
[apply\_filters( 'theme\_auto\_update\_debug\_string', string $auto\_updates\_string, WP\_Theme $theme, bool $enabled )](../../hooks/theme_auto_update_debug_string)
Filters the text string of the auto-updates setting for each theme in the Site Health debug data.
| Uses | Description |
| --- | --- |
| [WP\_Debug\_Data::get\_mysql\_var()](get_mysql_var) wp-admin/includes/class-wp-debug-data.php | Returns the value of a MySQL system variable. |
| [get\_blog\_count()](../../functions/get_blog_count) wp-includes/ms-functions.php | Gets the number of active sites on the installation. |
| [wp\_get\_themes()](../../functions/wp_get_themes) wp-includes/theme.php | Returns an array of [WP\_Theme](../wp_theme) objects based on the arguments. |
| [wp\_is\_auto\_update\_forced\_for\_item()](../../functions/wp_is_auto_update_forced_for_item) wp-admin/includes/update.php | Checks whether auto-updates are forced for an item. |
| [get\_user\_count()](../../functions/get_user_count) wp-includes/user.php | Returns the number of active users in your installation. |
| [get\_locale()](../../functions/get_locale) wp-includes/l10n.php | Retrieves the current locale. |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [untrailingslashit()](../../functions/untrailingslashit) wp-includes/formatting.php | Removes trailing forward slashes and backslashes if they exist. |
| [wp\_kses()](../../functions/wp_kses) wp-includes/kses.php | Filters text content and strips out disallowed HTML. |
| [get\_site\_transient()](../../functions/get_site_transient) wp-includes/option.php | Retrieves the value of a site transient. |
| [wp\_convert\_hr\_to\_bytes()](../../functions/wp_convert_hr_to_bytes) wp-includes/load.php | Converts a shorthand byte value to an integer byte value. |
| [is\_ssl()](../../functions/is_ssl) wp-includes/load.php | Determines if SSL is used. |
| [wp\_upload\_dir()](../../functions/wp_upload_dir) wp-includes/functions.php | Returns an array containing the current upload directory’s path and URL. |
| [wp\_is\_writable()](../../functions/wp_is_writable) wp-includes/functions.php | Determines if a directory is writable. |
| [size\_format()](../../functions/size_format) wp-includes/functions.php | Converts a number of bytes to the largest unit the bytes will fit into. |
| [wp\_remote\_get()](../../functions/wp_remote_get) wp-includes/http.php | Performs an HTTP request using the GET method and returns its response. |
| [get\_template\_directory()](../../functions/get_template_directory) wp-includes/theme.php | Retrieves template directory path for the active theme. |
| [get\_stylesheet\_directory()](../../functions/get_stylesheet_directory) wp-includes/theme.php | Retrieves stylesheet directory path for the active theme. |
| [get\_template()](../../functions/get_template) wp-includes/theme.php | Retrieves name of the active theme. |
| [get\_theme\_root()](../../functions/get_theme_root) wp-includes/theme.php | Retrieves path to themes directory. |
| [wp\_get\_environment\_type()](../../functions/wp_get_environment_type) wp-includes/load.php | Retrieves the current environment type. |
| [wp\_is\_auto\_update\_enabled\_for\_type()](../../functions/wp_is_auto_update_enabled_for_type) wp-admin/includes/update.php | Checks whether auto-updates are enabled. |
| [WP\_Site\_Health::get\_instance()](../wp_site_health/get_instance) wp-admin/includes/class-wp-site-health.php | Returns an instance of the [WP\_Site\_Health](../wp_site_health) class, or create one if none exist yet. |
| [wp\_timezone\_string()](../../functions/wp_timezone_string) wp-includes/functions.php | Retrieves the timezone of the site as a string. |
| [get\_user\_locale()](../../functions/get_user_locale) wp-includes/l10n.php | Retrieves the locale of a user. |
| [WP\_Network\_Query::\_\_construct()](../wp_network_query/__construct) wp-includes/class-wp-network-query.php | Constructor. |
| [got\_url\_rewrite()](../../functions/got_url_rewrite) wp-admin/includes/misc.php | Returns whether the server supports URL rewriting. |
| [get\_core\_updates()](../../functions/get_core_updates) wp-admin/includes/update.php | Gets available core updates. |
| [get\_plugin\_updates()](../../functions/get_plugin_updates) wp-admin/includes/update.php | Retrieves plugins with updates available. |
| [get\_theme\_updates()](../../functions/get_theme_updates) wp-admin/includes/update.php | Retrieves themes with updates available. |
| [get\_dropins()](../../functions/get_dropins) wp-admin/includes/plugin.php | Checks the wp-content directory and retrieve all drop-ins with any plugin data. |
| [\_get\_dropins()](../../functions/_get_dropins) wp-admin/includes/plugin.php | Returns drop-ins that WordPress uses. |
| [is\_plugin\_active()](../../functions/is_plugin_active) wp-admin/includes/plugin.php | Determines whether a plugin is active. |
| [get\_mu\_plugins()](../../functions/get_mu_plugins) wp-admin/includes/plugin.php | Checks the mu-plugins directory and retrieve all mu-plugin files with any plugin data. |
| [get\_plugins()](../../functions/get_plugins) wp-admin/includes/plugin.php | Checks the plugins directory and retrieve all plugin files with plugin data. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [wpdb::get\_var()](../wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| [get\_site\_option()](../../functions/get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Added pretty permalinks support information. |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Added database charset, database collation, and timezone information. |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
| programming_docs |
wordpress WP_Debug_Data::get_sizes(): array WP\_Debug\_Data::get\_sizes(): array
====================================
Fetches the sizes of the WordPress directories: `wordpress` (ABSPATH), `plugins`, `themes`, and `uploads`.
Intended to supplement the array returned by `WP_Debug_Data::debug_data()`.
array The sizes of the directories, also the database size and total installation size.
File: `wp-admin/includes/class-wp-debug-data.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-debug-data.php/)
```
public static function get_sizes() {
$size_db = self::get_database_size();
$upload_dir = wp_get_upload_dir();
/*
* We will be using the PHP max execution time to prevent the size calculations
* from causing a timeout. The default value is 30 seconds, and some
* hosts do not allow you to read configuration values.
*/
if ( function_exists( 'ini_get' ) ) {
$max_execution_time = ini_get( 'max_execution_time' );
}
// The max_execution_time defaults to 0 when PHP runs from cli.
// We still want to limit it below.
if ( empty( $max_execution_time ) ) {
$max_execution_time = 30; // 30 seconds.
}
if ( $max_execution_time > 20 ) {
// If the max_execution_time is set to lower than 20 seconds, reduce it a bit to prevent
// edge-case timeouts that may happen after the size loop has finished running.
$max_execution_time -= 2;
}
// Go through the various installation directories and calculate their sizes.
// No trailing slashes.
$paths = array(
'wordpress_size' => untrailingslashit( ABSPATH ),
'themes_size' => get_theme_root(),
'plugins_size' => WP_PLUGIN_DIR,
'uploads_size' => $upload_dir['basedir'],
);
$exclude = $paths;
unset( $exclude['wordpress_size'] );
$exclude = array_values( $exclude );
$size_total = 0;
$all_sizes = array();
// Loop over all the directories we want to gather the sizes for.
foreach ( $paths as $name => $path ) {
$dir_size = null; // Default to timeout.
$results = array(
'path' => $path,
'raw' => 0,
);
if ( microtime( true ) - WP_START_TIMESTAMP < $max_execution_time ) {
if ( 'wordpress_size' === $name ) {
$dir_size = recurse_dirsize( $path, $exclude, $max_execution_time );
} else {
$dir_size = recurse_dirsize( $path, null, $max_execution_time );
}
}
if ( false === $dir_size ) {
// Error reading.
$results['size'] = __( 'The size cannot be calculated. The directory is not accessible. Usually caused by invalid permissions.' );
$results['debug'] = 'not accessible';
// Stop total size calculation.
$size_total = null;
} elseif ( null === $dir_size ) {
// Timeout.
$results['size'] = __( 'The directory size calculation has timed out. Usually caused by a very large number of sub-directories and files.' );
$results['debug'] = 'timeout while calculating size';
// Stop total size calculation.
$size_total = null;
} else {
if ( null !== $size_total ) {
$size_total += $dir_size;
}
$results['raw'] = $dir_size;
$results['size'] = size_format( $dir_size, 2 );
$results['debug'] = $results['size'] . " ({$dir_size} bytes)";
}
$all_sizes[ $name ] = $results;
}
if ( $size_db > 0 ) {
$database_size = size_format( $size_db, 2 );
$all_sizes['database_size'] = array(
'raw' => $size_db,
'size' => $database_size,
'debug' => $database_size . " ({$size_db} bytes)",
);
} else {
$all_sizes['database_size'] = array(
'size' => __( 'Not available' ),
'debug' => 'not available',
);
}
if ( null !== $size_total && $size_db > 0 ) {
$total_size = $size_total + $size_db;
$total_size_mb = size_format( $total_size, 2 );
$all_sizes['total_size'] = array(
'raw' => $total_size,
'size' => $total_size_mb,
'debug' => $total_size_mb . " ({$total_size} bytes)",
);
} else {
$all_sizes['total_size'] = array(
'size' => __( 'Total size is not available. Some errors were encountered when determining the size of your installation.' ),
'debug' => 'not available',
);
}
return $all_sizes;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Debug\_Data::get\_database\_size()](get_database_size) wp-admin/includes/class-wp-debug-data.php | Fetches the total size of all the database tables for the active database user. |
| [wp\_get\_upload\_dir()](../../functions/wp_get_upload_dir) wp-includes/functions.php | Retrieves uploads directory information. |
| [get\_theme\_root()](../../functions/get_theme_root) wp-includes/theme.php | Retrieves path to themes directory. |
| [untrailingslashit()](../../functions/untrailingslashit) wp-includes/formatting.php | Removes trailing forward slashes and backslashes if they exist. |
| [size\_format()](../../functions/size_format) wp-includes/functions.php | Converts a number of bytes to the largest unit the bytes will fit into. |
| [recurse\_dirsize()](../../functions/recurse_dirsize) wp-includes/functions.php | Gets the size of a directory recursively. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Site\_Health\_Controller::get\_directory\_sizes()](../wp_rest_site_health_controller/get_directory_sizes) wp-includes/rest-api/endpoints/class-wp-rest-site-health-controller.php | Gets the current directory sizes for this install. |
| [wp\_ajax\_health\_check\_get\_sizes()](../../functions/wp_ajax_health_check_get_sizes) wp-admin/includes/ajax-actions.php | Ajax handler for site health check to get directories and database sizes. |
| Version | Description |
| --- | --- |
| [5.2.0](https://developer.wordpress.org/reference/since/5.2.0/) | Introduced. |
wordpress Theme_Upgrader::install( string $package, array $args = array() ): bool|WP_Error Theme\_Upgrader::install( string $package, array $args = array() ): bool|WP\_Error
==================================================================================
Install a theme package.
`$package` string Required The full local path or URI of the package. `$args` array Optional Other arguments for installing a theme package.
* `clear_update_cache`boolWhether to clear the updates cache if successful.
Default true.
Default: `array()`
bool|[WP\_Error](../wp_error) True if the installation was successful, false or a [WP\_Error](../wp_error) object otherwise.
File: `wp-admin/includes/class-theme-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-theme-upgrader.php/)
```
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;
}
```
[do\_action( 'upgrader\_overwrote\_package', string $package, array $data, string $package\_type )](../../hooks/upgrader_overwrote_package)
Fires when the upgrader has successfully overwritten a currently installed plugin or theme with an uploaded zip package.
| Uses | Description |
| --- | --- |
| [Theme\_Upgrader::install\_strings()](install_strings) wp-admin/includes/class-theme-upgrader.php | Initialize the installation strings. |
| [get\_theme\_root()](../../functions/get_theme_root) wp-includes/theme.php | Retrieves path to themes directory. |
| [wp\_clean\_themes\_cache()](../../functions/wp_clean_themes_cache) wp-includes/theme.php | Clears the cache held by [get\_theme\_roots()](../../functions/get_theme_roots) and [WP\_Theme](../wp_theme). |
| [remove\_action()](../../functions/remove_action) wp-includes/plugin.php | Removes a callback function from an action hook. |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | The `$args` parameter was added, making clearing the update cache optional. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress Theme_Upgrader::current_before( bool|WP_Error $response, array $theme ): bool|WP_Error Theme\_Upgrader::current\_before( bool|WP\_Error $response, array $theme ): bool|WP\_Error
==========================================================================================
Turn on maintenance mode before attempting to upgrade the active theme.
Hooked to the [‘upgrader\_pre\_install’](../../hooks/upgrader_pre_install) filter by [Theme\_Upgrader::upgrade()](upgrade) and [Theme\_Upgrader::bulk\_upgrade()](bulk_upgrade).
`$response` bool|[WP\_Error](../wp_error) Required The installation response before the installation has started. `$theme` array Required Theme arguments. bool|[WP\_Error](../wp_error) The original `$response` parameter or [WP\_Error](../wp_error).
File: `wp-admin/includes/class-theme-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-theme-upgrader.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [get\_stylesheet()](../../functions/get_stylesheet) wp-includes/theme.php | Retrieves name of the current stylesheet. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress Theme_Upgrader::bulk_upgrade( string[] $themes, array $args = array() ): array[]|false Theme\_Upgrader::bulk\_upgrade( string[] $themes, array $args = array() ): array[]|false
========================================================================================
Upgrade several themes at once.
`$themes` string[] Required Array of the theme slugs. `$args` array Optional Other arguments for upgrading several themes at once.
* `clear_update_cache`boolWhether to clear the update cache if successful.
Default true.
Default: `array()`
array[]|false An array of results, or false if unable to connect to the filesystem.
File: `wp-admin/includes/class-theme-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-theme-upgrader.php/)
```
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;
}
```
[do\_action( 'upgrader\_process\_complete', WP\_Upgrader $upgrader, array $hook\_extra )](../../hooks/upgrader_process_complete)
Fires when the upgrader process is complete.
| Uses | Description |
| --- | --- |
| [Theme\_Upgrader::theme\_info()](theme_info) wp-admin/includes/class-theme-upgrader.php | Get the [WP\_Theme](../wp_theme) object for a theme. |
| [Theme\_Upgrader::upgrade\_strings()](upgrade_strings) wp-admin/includes/class-theme-upgrader.php | Initialize the upgrade strings. |
| [get\_theme\_root()](../../functions/get_theme_root) wp-includes/theme.php | Retrieves path to themes directory. |
| [get\_template()](../../functions/get_template) wp-includes/theme.php | Retrieves name of the active theme. |
| [get\_stylesheet()](../../functions/get_stylesheet) wp-includes/theme.php | Retrieves name of the current stylesheet. |
| [wp\_clean\_themes\_cache()](../../functions/wp_clean_themes_cache) wp-includes/theme.php | Clears the cache held by [get\_theme\_roots()](../../functions/get_theme_roots) and [WP\_Theme](../wp_theme). |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| [get\_site\_transient()](../../functions/get_site_transient) wp-includes/option.php | Retrieves the value of a site transient. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | The `$args` parameter was added, making clearing the update cache optional. |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | Introduced. |
wordpress Theme_Upgrader::check_package( string $source ): string|WP_Error Theme\_Upgrader::check\_package( string $source ): string|WP\_Error
===================================================================
Checks that the package source contains a valid theme.
Hooked to the [‘upgrader\_source\_selection’](../../hooks/upgrader_source_selection) filter by [Theme\_Upgrader::install()](install).
`$source` string Required The path to the downloaded package source. string|[WP\_Error](../wp_error) The source as passed, or a [WP\_Error](../wp_error) object on failure.
File: `wp-admin/includes/class-theme-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-theme-upgrader.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [is\_php\_version\_compatible()](../../functions/is_php_version_compatible) wp-includes/functions.php | Checks compatibility with the current PHP version. |
| [is\_wp\_version\_compatible()](../../functions/is_wp_version_compatible) wp-includes/functions.php | Checks compatibility with the current WordPress version. |
| [get\_file\_data()](../../functions/get_file_data) wp-includes/functions.php | Retrieves metadata from a file. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [3.3.0](https://developer.wordpress.org/reference/since/3.3.0/) | Introduced. |
| programming_docs |
wordpress Theme_Upgrader::current_after( bool|WP_Error $response, array $theme ): bool|WP_Error Theme\_Upgrader::current\_after( bool|WP\_Error $response, array $theme ): bool|WP\_Error
=========================================================================================
Turn off maintenance mode after upgrading the active theme.
Hooked to the [‘upgrader\_post\_install’](../../hooks/upgrader_post_install) filter by [Theme\_Upgrader::upgrade()](upgrade) and [Theme\_Upgrader::bulk\_upgrade()](bulk_upgrade).
`$response` bool|[WP\_Error](../wp_error) Required The installation response after the installation has finished. `$theme` array Required Theme arguments. bool|[WP\_Error](../wp_error) The original `$response` parameter or [WP\_Error](../wp_error).
File: `wp-admin/includes/class-theme-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-theme-upgrader.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [switch\_theme()](../../functions/switch_theme) wp-includes/theme.php | Switches the theme. |
| [get\_stylesheet()](../../functions/get_stylesheet) wp-includes/theme.php | Retrieves name of the current stylesheet. |
| [wp\_clean\_themes\_cache()](../../functions/wp_clean_themes_cache) wp-includes/theme.php | Clears the cache held by [get\_theme\_roots()](../../functions/get_theme_roots) and [WP\_Theme](../wp_theme). |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress Theme_Upgrader::check_parent_theme_filter( bool $install_result, array $hook_extra, array $child_result ): bool Theme\_Upgrader::check\_parent\_theme\_filter( bool $install\_result, array $hook\_extra, array $child\_result ): bool
======================================================================================================================
Check if a child theme is being installed and we need to install its parent.
Hooked to the [‘upgrader\_post\_install’](../../hooks/upgrader_post_install) filter by [Theme\_Upgrader::install()](install).
`$install_result` bool Required `$hook_extra` array Required `$child_result` array Required bool
File: `wp-admin/includes/class-theme-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-theme-upgrader.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [Theme\_Upgrader::theme\_info()](theme_info) wp-admin/includes/class-theme-upgrader.php | Get the [WP\_Theme](../wp_theme) object for a theme. |
| [themes\_api()](../../functions/themes_api) wp-admin/includes/theme.php | Retrieves theme installer pages from the WordPress.org Themes API. |
| [get\_theme\_root()](../../functions/get_theme_root) wp-includes/theme.php | Retrieves path to themes directory. |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress Theme_Upgrader::upgrade( string $theme, array $args = array() ): bool|WP_Error Theme\_Upgrader::upgrade( string $theme, array $args = array() ): bool|WP\_Error
================================================================================
Upgrade a theme.
`$theme` string Required The theme slug. `$args` array Optional Other arguments for upgrading a theme.
* `clear_update_cache`boolWhether to clear the update cache if successful.
Default true.
Default: `array()`
bool|[WP\_Error](../wp_error) True if the upgrade was successful, false or a [WP\_Error](../wp_error) object otherwise.
File: `wp-admin/includes/class-theme-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-theme-upgrader.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [Theme\_Upgrader::upgrade\_strings()](upgrade_strings) wp-admin/includes/class-theme-upgrader.php | Initialize the upgrade strings. |
| [get\_theme\_root()](../../functions/get_theme_root) wp-includes/theme.php | Retrieves path to themes directory. |
| [wp\_clean\_themes\_cache()](../../functions/wp_clean_themes_cache) wp-includes/theme.php | Clears the cache held by [get\_theme\_roots()](../../functions/get_theme_roots) and [WP\_Theme](../wp_theme). |
| [remove\_action()](../../functions/remove_action) wp-includes/plugin.php | Removes a callback function from an action hook. |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| [get\_site\_transient()](../../functions/get_site_transient) wp-includes/option.php | Retrieves the value of a site transient. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [3.7.0](https://developer.wordpress.org/reference/since/3.7.0/) | The `$args` parameter was added, making clearing the update cache optional. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress Theme_Upgrader::delete_old_theme( bool $removed, string $local_destination, string $remote_destination, array $theme ): bool Theme\_Upgrader::delete\_old\_theme( bool $removed, string $local\_destination, string $remote\_destination, array $theme ): bool
=================================================================================================================================
Delete the old theme during an upgrade.
Hooked to the [‘upgrader\_clear\_destination’](../../hooks/upgrader_clear_destination) filter by [Theme\_Upgrader::upgrade()](upgrade) and [Theme\_Upgrader::bulk\_upgrade()](bulk_upgrade).
`$removed` bool Required `$local_destination` string Required `$remote_destination` string Required `$theme` array Required bool
File: `wp-admin/includes/class-theme-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-theme-upgrader.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [trailingslashit()](../../functions/trailingslashit) wp-includes/formatting.php | Appends a trailing slash. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress Theme_Upgrader::hide_activate_preview_actions( array $actions ): array Theme\_Upgrader::hide\_activate\_preview\_actions( array $actions ): array
==========================================================================
Don’t display the activate and preview actions to the user.
Hooked to the [‘install\_theme\_complete\_actions’](../../hooks/install_theme_complete_actions) filter by [Theme\_Upgrader::check\_parent\_theme\_filter()](check_parent_theme_filter) when installing a child theme and installing the parent theme fails.
`$actions` array Required Preview actions. array
File: `wp-admin/includes/class-theme-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-theme-upgrader.php/)
```
public function hide_activate_preview_actions( $actions ) {
unset( $actions['activate'], $actions['preview'] );
return $actions;
}
```
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress Theme_Upgrader::install_strings() Theme\_Upgrader::install\_strings()
===================================
Initialize the installation 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/)
```
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…' ), '<span class="code">%s</span>' );
$this->strings['unpack_package'] = __( 'Unpacking the package…' );
$this->strings['installing_package'] = __( 'Installing the theme…' );
$this->strings['remove_old'] = __( 'Removing the old version of the theme…' );
$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…' );
/* translators: 1: Theme name, 2: Theme version. */
$this->strings['parent_theme_prepare_install'] = __( 'Preparing to install <strong>%1$s %2$s</strong>…' );
/* 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…' );
$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…' );
$this->strings['process_failed'] = __( 'Theme downgrade failed.' );
$this->strings['process_success'] = __( 'Theme downgraded successfully.' );
}
}
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [Theme\_Upgrader::install()](install) wp-admin/includes/class-theme-upgrader.php | Install a theme package. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress Theme_Upgrader::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/)
```
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…' ), '<span class="code">%s</span>' );
$this->strings['unpack_package'] = __( 'Unpacking the update…' );
$this->strings['remove_old'] = __( 'Removing the old version of the theme…' );
$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.' );
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [Theme\_Upgrader::upgrade()](upgrade) wp-admin/includes/class-theme-upgrader.php | Upgrade a theme. |
| [Theme\_Upgrader::bulk\_upgrade()](bulk_upgrade) wp-admin/includes/class-theme-upgrader.php | Upgrade several themes at once. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress Theme_Upgrader::theme_info( string $theme = null ): WP_Theme|false Theme\_Upgrader::theme\_info( string $theme = null ): WP\_Theme|false
=====================================================================
Get the [WP\_Theme](../wp_theme) object for a theme.
`$theme` string Optional The directory name of the theme. This is optional, and if not supplied, the directory name from the last result will be used. Default: `null`
[WP\_Theme](../wp_theme)|false The theme's info object, or false `$theme` is not supplied and the last result isn't set.
File: `wp-admin/includes/class-theme-upgrader.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-theme-upgrader.php/)
```
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\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| Used By | Description |
| --- | --- |
| [Theme\_Upgrader::check\_parent\_theme\_filter()](check_parent_theme_filter) wp-admin/includes/class-theme-upgrader.php | Check if a child theme is being installed and we need to install its parent. |
| [Theme\_Upgrader::bulk\_upgrade()](bulk_upgrade) wp-admin/includes/class-theme-upgrader.php | Upgrade several themes at once. |
| Version | Description |
| --- | --- |
| [3.0.0](https://developer.wordpress.org/reference/since/3.0.0/) | The `$theme` argument was added. |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Background_Image_Control::__construct( WP_Customize_Manager $manager ) WP\_Customize\_Background\_Image\_Control::\_\_construct( WP\_Customize\_Manager $manager )
===========================================================================================
Constructor.
`$manager` [WP\_Customize\_Manager](../wp_customize_manager) Required Customizer bootstrap instance. 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/)
```
public function __construct( $manager ) {
parent::__construct(
$manager,
'background_image',
array(
'label' => __( 'Background Image' ),
'section' => 'background_image',
)
);
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::register\_controls()](../wp_customize_manager/register_controls) wp-includes/class-wp-customize-manager.php | Registers some default controls. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Background_Image_Control::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/)
```
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 |
| --- | --- |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [wp\_create\_nonce()](../../functions/wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| [wp\_localize\_script()](../../functions/wp_localize_script) wp-includes/functions.wp-scripts.php | Localize a script. |
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Sitemaps_Index::get_index_url(): string WP\_Sitemaps\_Index::get\_index\_url(): string
==============================================
Builds the URL for the sitemap index.
string The sitemap index URL.
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/)
```
public function get_index_url() {
global $wp_rewrite;
if ( ! $wp_rewrite->using_permalinks() ) {
return home_url( '/?sitemap=index' );
}
return home_url( '/wp-sitemap.xml' );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Rewrite::using\_permalinks()](../wp_rewrite/using_permalinks) wp-includes/class-wp-rewrite.php | Determines whether permalinks are being used. |
| [home\_url()](../../functions/home_url) wp-includes/link-template.php | Retrieves the URL for the current site where the front end is accessible. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps_Index::get_sitemap_list(): array[] WP\_Sitemaps\_Index::get\_sitemap\_list(): array[]
==================================================
Gets a sitemap list for the index.
array[] Array of all sitemaps.
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/)
```
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 );
}
```
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Sitemaps_Index::__construct( WP_Sitemaps_Registry $registry ) WP\_Sitemaps\_Index::\_\_construct( WP\_Sitemaps\_Registry $registry )
======================================================================
[WP\_Sitemaps\_Index](../wp_sitemaps_index) constructor.
`$registry` [WP\_Sitemaps\_Registry](../wp_sitemaps_registry) Required Sitemap provider registry. 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/)
```
public function __construct( WP_Sitemaps_Registry $registry ) {
$this->registry = $registry;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Sitemaps::\_\_construct()](../wp_sitemaps/__construct) wp-includes/sitemaps/class-wp-sitemaps.php | [WP\_Sitemaps](../wp_sitemaps) constructor. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_Theme_JSON_Data::get_data(): array WP\_Theme\_JSON\_Data::get\_data(): array
=========================================
Returns an array containing the underlying data following the theme.json specification.
array
File: `wp-includes/class-wp-theme-json-data.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme-json-data.php/)
```
public function get_data() {
return $this->theme_json->get_raw_data();
}
```
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Theme_JSON_Data::update_with( array $new_data ): WP_Theme_JSON_Data WP\_Theme\_JSON\_Data::update\_with( array $new\_data ): WP\_Theme\_JSON\_Data
==============================================================================
Updates the theme.json with the the given data.
`$new_data` array Required Array following the theme.json specification. [WP\_Theme\_JSON\_Data](../wp_theme_json_data) The own instance with access to the modified data.
File: `wp-includes/class-wp-theme-json-data.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme-json-data.php/)
```
public function update_with( $new_data ) {
$this->theme_json->merge( new WP_Theme_JSON( $new_data, $this->origin ) );
return $this;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme\_JSON::\_\_construct()](../wp_theme_json/__construct) wp-includes/class-wp-theme-json.php | Constructor. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Theme_JSON_Data::__construct( array $data = array(), string $origin = 'theme' ) WP\_Theme\_JSON\_Data::\_\_construct( array $data = array(), string $origin = 'theme' )
=======================================================================================
Constructor.
`$data` array Optional Array following the theme.json specification. Default: `array()`
`$origin` string Optional The origin of the data: default, theme, user. Default: `'theme'`
File: `wp-includes/class-wp-theme-json-data.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-theme-json-data.php/)
```
public function __construct( $data = array(), $origin = 'theme' ) {
$this->origin = $origin;
$this->theme_json = new WP_Theme_JSON( $data, $this->origin );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme\_JSON::\_\_construct()](../wp_theme_json/__construct) wp-includes/class-wp-theme-json.php | Constructor. |
| Used By | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Resolver::get\_block\_data()](../wp_theme_json_resolver/get_block_data) wp-includes/class-wp-theme-json-resolver.php | Gets the styles for blocks from the block.json file. |
| [WP\_Theme\_JSON\_Resolver::get\_user\_data()](../wp_theme_json_resolver/get_user_data) wp-includes/class-wp-theme-json-resolver.php | Returns the user’s origin config. |
| [WP\_Theme\_JSON\_Resolver::get\_theme\_data()](../wp_theme_json_resolver/get_theme_data) wp-includes/class-wp-theme-json-resolver.php | Returns the theme’s data. |
| [WP\_Theme\_JSON\_Resolver::get\_core\_data()](../wp_theme_json_resolver/get_core_data) wp-includes/class-wp-theme-json-resolver.php | Returns core’s origin config. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_REST_Request::has_param( string $key ): bool WP\_REST\_Request::has\_param( string $key ): bool
==================================================
Checks if a parameter exists in the request.
This allows distinguishing between an omitted parameter, and a parameter specifically set to null.
`$key` string Required Parameter name. bool True if a param exists for the given key.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function has_param( $key ) {
$order = $this->get_parameter_order();
foreach ( $order as $type ) {
if ( is_array( $this->params[ $type ] ) && array_key_exists( $key, $this->params[ $type ] ) ) {
return true;
}
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::get\_parameter\_order()](get_parameter_order) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the parameter priority order. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_REST_Request::from_url( string $url ): WP_REST_Request|false WP\_REST\_Request::from\_url( string $url ): WP\_REST\_Request|false
====================================================================
Retrieves a [WP\_REST\_Request](../wp_rest_request) object from a full URL.
`$url` string Required URL with protocol, domain, path and query args. [WP\_REST\_Request](../wp_rest_request)|false [WP\_REST\_Request](../wp_rest_request) object on success, false on failure.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public static function from_url( $url ) {
$bits = parse_url( $url );
$query_params = array();
if ( ! empty( $bits['query'] ) ) {
wp_parse_str( $bits['query'], $query_params );
}
$api_root = rest_url();
if ( get_option( 'permalink_structure' ) && 0 === strpos( $url, $api_root ) ) {
// Pretty permalinks on, and URL is under the API root.
$api_url_part = substr( $url, strlen( untrailingslashit( $api_root ) ) );
$route = parse_url( $api_url_part, PHP_URL_PATH );
} elseif ( ! empty( $query_params['rest_route'] ) ) {
// ?rest_route=... set directly.
$route = $query_params['rest_route'];
unset( $query_params['rest_route'] );
}
$request = false;
if ( ! empty( $route ) ) {
$request = new WP_REST_Request( 'GET', $route );
$request->set_query_params( $query_params );
}
/**
* Filters the REST API request generated from a URL.
*
* @since 4.5.0
*
* @param WP_REST_Request|false $request Generated request object, or false if URL
* could not be parsed.
* @param string $url URL the request was generated from.
*/
return apply_filters( 'rest_request_from_url', $request, $url );
}
```
[apply\_filters( 'rest\_request\_from\_url', WP\_REST\_Request|false $request, string $url )](../../hooks/rest_request_from_url)
Filters the REST API request generated from a URL.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::\_\_construct()](__construct) wp-includes/rest-api/class-wp-rest-request.php | Constructor. |
| [wp\_parse\_str()](../../functions/wp_parse_str) wp-includes/formatting.php | Parses a string into variables to be stored in an array. |
| [untrailingslashit()](../../functions/untrailingslashit) wp-includes/formatting.php | Removes trailing forward slashes and backslashes if they exist. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Server::embed\_links()](../wp_rest_server/embed_links) wp-includes/rest-api/class-wp-rest-server.php | Embeds the links from the data into the request. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_REST_Request::get_params(): array WP\_REST\_Request::get\_params(): array
=======================================
Retrieves merged parameters from the request.
The equivalent of get\_param(), but returns all parameters for the request.
Handles merging all the available values into a single array.
array Map of key to value.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_params() {
$order = $this->get_parameter_order();
$order = array_reverse( $order, true );
$params = array();
foreach ( $order as $type ) {
// array_merge() / the "+" operator will mess up
// numeric keys, so instead do a manual foreach.
foreach ( (array) $this->params[ $type ] as $key => $value ) {
$params[ $key ] = $value;
}
}
return $params;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::get\_parameter\_order()](get_parameter_order) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the parameter priority order. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::offsetGet( $offset ) WP\_REST\_Request::offsetGet( $offset )
=======================================
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function offsetGet( $offset ) {
return $this->get_param( $offset );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::get\_param()](get_param) wp-includes/rest-api/class-wp-rest-request.php | Retrieves a parameter from the request. |
wordpress WP_REST_Request::offsetUnset( $offset ) WP\_REST\_Request::offsetUnset( $offset )
=========================================
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function offsetUnset( $offset ) {
$order = $this->get_parameter_order();
// Remove the offset from every group.
foreach ( $order as $type ) {
unset( $this->params[ $type ][ $offset ] );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::get\_parameter\_order()](get_parameter_order) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the parameter priority order. |
wordpress WP_REST_Request::set_attributes( array $attributes ) WP\_REST\_Request::set\_attributes( array $attributes )
=======================================================
Sets the attributes for the request.
`$attributes` array Required Attributes for the request. File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function set_attributes( $attributes ) {
$this->attributes = $attributes;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::\_\_construct()](__construct) wp-includes/rest-api/class-wp-rest-request.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::offsetSet( $offset, $value ) WP\_REST\_Request::offsetSet( $offset, $value )
===============================================
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function offsetSet( $offset, $value ) {
$this->set_param( $offset, $value );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::set\_param()](set_param) wp-includes/rest-api/class-wp-rest-request.php | Sets a parameter on the request. |
wordpress WP_REST_Request::set_param( string $key, mixed $value ) WP\_REST\_Request::set\_param( string $key, mixed $value )
==========================================================
Sets a parameter on the request.
If the given parameter key exists in any parameter type an update will take place, otherwise a new param will be created in the first parameter type (respecting get\_parameter\_order()).
`$key` string Required Parameter name. `$value` mixed Required Parameter value. File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function set_param( $key, $value ) {
$order = $this->get_parameter_order();
$found_key = false;
foreach ( $order as $type ) {
if ( 'defaults' !== $type && is_array( $this->params[ $type ] ) && array_key_exists( $key, $this->params[ $type ] ) ) {
$this->params[ $type ][ $key ] = $value;
$found_key = true;
}
}
if ( ! $found_key ) {
$this->params[ $order[0] ][ $key ] = $value;
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::get\_parameter\_order()](get_parameter_order) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the parameter priority order. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::offsetSet()](offsetset) wp-includes/rest-api/class-wp-rest-request.php | |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::set_default_params( array $params ) WP\_REST\_Request::set\_default\_params( array $params )
========================================================
Sets default parameters.
These are the parameters set in the route registration.
`$params` array Required Parameter map of key to value. File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function set_default_params( $params ) {
$this->params['defaults'] = $params;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Request::set_method( string $method ) WP\_REST\_Request::set\_method( string $method )
================================================
Sets HTTP method for the request.
`$method` string Required HTTP method. File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function set_method( $method ) {
$this->method = strtoupper( $method );
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::\_\_construct()](__construct) wp-includes/rest-api/class-wp-rest-request.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::sanitize_params(): true|WP_Error WP\_REST\_Request::sanitize\_params(): true|WP\_Error
=====================================================
Sanitizes (where possible) the params on the request.
This is primarily based off the sanitize\_callback param on each registered argument.
true|[WP\_Error](../wp_error) True if parameters were sanitized, [WP\_Error](../wp_error) if an error occurred during sanitization.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function sanitize_params() {
$attributes = $this->get_attributes();
// No arguments set, skip sanitizing.
if ( empty( $attributes['args'] ) ) {
return true;
}
$order = $this->get_parameter_order();
$invalid_params = array();
$invalid_details = array();
foreach ( $order as $type ) {
if ( empty( $this->params[ $type ] ) ) {
continue;
}
foreach ( $this->params[ $type ] as $key => $value ) {
if ( ! isset( $attributes['args'][ $key ] ) ) {
continue;
}
$param_args = $attributes['args'][ $key ];
// If the arg has a type but no sanitize_callback attribute, default to rest_parse_request_arg.
if ( ! array_key_exists( 'sanitize_callback', $param_args ) && ! empty( $param_args['type'] ) ) {
$param_args['sanitize_callback'] = 'rest_parse_request_arg';
}
// If there's still no sanitize_callback, nothing to do here.
if ( empty( $param_args['sanitize_callback'] ) ) {
continue;
}
/** @var mixed|WP_Error $sanitized_value */
$sanitized_value = call_user_func( $param_args['sanitize_callback'], $value, $this, $key );
if ( is_wp_error( $sanitized_value ) ) {
$invalid_params[ $key ] = implode( ' ', $sanitized_value->get_error_messages() );
$invalid_details[ $key ] = rest_convert_error_to_response( $sanitized_value )->get_data();
} else {
$this->params[ $type ][ $key ] = $sanitized_value;
}
}
}
if ( $invalid_params ) {
return new WP_Error(
'rest_invalid_param',
/* translators: %s: List of invalid parameters. */
sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', array_keys( $invalid_params ) ) ),
array(
'status' => 400,
'params' => $invalid_params,
'details' => $invalid_details,
)
);
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [rest\_convert\_error\_to\_response()](../../functions/rest_convert_error_to_response) wp-includes/rest-api.php | Converts an error to a response object. |
| [WP\_REST\_Request::get\_attributes()](get_attributes) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the attributes for the request. |
| [WP\_REST\_Request::get\_parameter\_order()](get_parameter_order) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the parameter priority order. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::canonicalize_header_name( string $key ): string WP\_REST\_Request::canonicalize\_header\_name( string $key ): string
====================================================================
Canonicalizes the header name.
Ensures that header names are always treated the same regardless of source. Header names are always case insensitive.
Note that we treat `-` (dashes) and `_` (underscores) as the same character, as per header parsing rules in both Apache and nginx.
`$key` string Required Header name. string Canonicalized name.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public static function canonicalize_header_name( $key ) {
$key = strtolower( $key );
$key = str_replace( '-', '_', $key );
return $key;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::get\_header\_as\_array()](get_header_as_array) wp-includes/rest-api/class-wp-rest-request.php | Retrieves header values from the request. |
| [WP\_REST\_Request::set\_header()](set_header) wp-includes/rest-api/class-wp-rest-request.php | Sets the header on request. |
| [WP\_REST\_Request::add\_header()](add_header) wp-includes/rest-api/class-wp-rest-request.php | Appends a header value for the given header. |
| [WP\_REST\_Request::remove\_header()](remove_header) wp-includes/rest-api/class-wp-rest-request.php | Removes all values for a header. |
| [WP\_REST\_Request::get\_header()](get_header) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the given header from the request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::get_content_type(): array|null WP\_REST\_Request::get\_content\_type(): array|null
===================================================
Retrieves the content-type of the request.
array|null Map containing `'value'` and `'parameters'` keys or null when no valid content-type header was available.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_content_type() {
$value = $this->get_header( 'content-type' );
if ( empty( $value ) ) {
return null;
}
$parameters = '';
if ( strpos( $value, ';' ) ) {
list( $value, $parameters ) = explode( ';', $value, 2 );
}
$value = strtolower( $value );
if ( false === strpos( $value, '/' ) ) {
return null;
}
// Parse type and subtype out.
list( $type, $subtype ) = explode( '/', $value, 2 );
$data = compact( 'value', 'type', 'subtype', 'parameters' );
$data = array_map( 'trim', $data );
return $data;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::get\_header()](get_header) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the given header from the request. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::is\_json\_content\_type()](is_json_content_type) wp-includes/rest-api/class-wp-rest-request.php | Checks if the request has specified a JSON content-type. |
| [WP\_REST\_Request::parse\_body\_params()](parse_body_params) wp-includes/rest-api/class-wp-rest-request.php | Parses the request body parameters. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::parse_body_params() WP\_REST\_Request::parse\_body\_params()
========================================
Parses the request body parameters.
Parses out URL-encoded bodies for request methods that aren’t supported natively by PHP. In PHP 5.x, only POST has these parsed automatically.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
protected function parse_body_params() {
if ( $this->parsed_body ) {
return;
}
$this->parsed_body = true;
/*
* Check that we got URL-encoded. Treat a missing content-type as
* URL-encoded for maximum compatibility.
*/
$content_type = $this->get_content_type();
if ( ! empty( $content_type ) && 'application/x-www-form-urlencoded' !== $content_type['value'] ) {
return;
}
parse_str( $this->get_body(), $params );
/*
* Add to the POST parameters stored internally. If a user has already
* set these manually (via `set_body_params`), don't override them.
*/
$this->params['POST'] = array_merge( $params, $this->params['POST'] );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::get\_body()](get_body) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the request body content. |
| [WP\_REST\_Request::get\_content\_type()](get_content_type) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the content-type of the request. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::get\_parameter\_order()](get_parameter_order) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the parameter priority order. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::set_url_params( array $params ) WP\_REST\_Request::set\_url\_params( array $params )
====================================================
Sets parameters from the route.
Typically, this is set after parsing the URL.
`$params` array Required Parameter map of key to value. File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function set_url_params( $params ) {
$this->params['URL'] = $params;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::set_body( string $data ) WP\_REST\_Request::set\_body( string $data )
============================================
Sets body content.
`$data` string Required Binary data from the request body. File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function set_body( $data ) {
$this->body = $data;
// Enable lazy parsing.
$this->parsed_json = false;
$this->parsed_body = false;
$this->params['JSON'] = null;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::get_param( string $key ): mixed|null WP\_REST\_Request::get\_param( string $key ): mixed|null
========================================================
Retrieves a parameter from the request.
`$key` string Required Parameter name. mixed|null Value if set, null otherwise.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_param( $key ) {
$order = $this->get_parameter_order();
foreach ( $order as $type ) {
// Determine if we have the parameter for this type.
if ( isset( $this->params[ $type ][ $key ] ) ) {
return $this->params[ $type ][ $key ];
}
}
return null;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::get\_parameter\_order()](get_parameter_order) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the parameter priority order. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::has\_valid\_params()](has_valid_params) wp-includes/rest-api/class-wp-rest-request.php | Checks whether this request is valid according to its attributes. |
| [WP\_REST\_Request::offsetGet()](offsetget) wp-includes/rest-api/class-wp-rest-request.php | |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::get_json_params(): array WP\_REST\_Request::get\_json\_params(): array
=============================================
Retrieves the parameters from a JSON-formatted body.
array Parameter map of key to value.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_json_params() {
// Ensure the parameters have been parsed out.
$this->parse_json_params();
return $this->params['JSON'];
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::parse\_json\_params()](parse_json_params) wp-includes/rest-api/class-wp-rest-request.php | Parses the JSON parameters. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::get_header( string $key ): string|null WP\_REST\_Request::get\_header( string $key ): string|null
==========================================================
Retrieves the given header from the request.
If the header has multiple values, they will be concatenated with a comma as per the HTTP specification. Be aware that some non-compliant headers (notably cookie headers) cannot be joined this way.
`$key` string Required Header name, will be canonicalized to lowercase. string|null String value if set, null otherwise.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_header( $key ) {
$key = $this->canonicalize_header_name( $key );
if ( ! isset( $this->headers[ $key ] ) ) {
return null;
}
return implode( ',', $this->headers[ $key ] );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::canonicalize\_header\_name()](canonicalize_header_name) wp-includes/rest-api/class-wp-rest-request.php | Canonicalizes the header name. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::get\_content\_type()](get_content_type) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the content-type of the request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::set_headers( array $headers, bool $override = true ) WP\_REST\_Request::set\_headers( array $headers, bool $override = true )
========================================================================
Sets headers on the request.
`$headers` array Required Map of header name to value. `$override` bool Optional If true, replace the request's headers. Otherwise, merge with existing. Default: `true`
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function set_headers( $headers, $override = true ) {
if ( true === $override ) {
$this->headers = array();
}
foreach ( $headers as $key => $value ) {
$this->set_header( $key, $value );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::set\_header()](set_header) wp-includes/rest-api/class-wp-rest-request.php | Sets the header on request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::set_header( string $key, string $value ) WP\_REST\_Request::set\_header( string $key, string $value )
============================================================
Sets the header on request.
`$key` string Required Header name. `$value` string Required Header value, or list of values. File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function set_header( $key, $value ) {
$key = $this->canonicalize_header_name( $key );
$value = (array) $value;
$this->headers[ $key ] = $value;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::canonicalize\_header\_name()](canonicalize_header_name) wp-includes/rest-api/class-wp-rest-request.php | Canonicalizes the header name. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::set\_headers()](set_headers) wp-includes/rest-api/class-wp-rest-request.php | Sets headers on the request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::get_headers(): array WP\_REST\_Request::get\_headers(): array
========================================
Retrieves all headers from the request.
array Map of key to value. Key is always lowercase, as per HTTP specification.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_headers() {
return $this->headers;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::remove_header( string $key ) WP\_REST\_Request::remove\_header( string $key )
================================================
Removes all values for a header.
`$key` string Required Header name. File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function remove_header( $key ) {
$key = $this->canonicalize_header_name( $key );
unset( $this->headers[ $key ] );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::canonicalize\_header\_name()](canonicalize_header_name) wp-includes/rest-api/class-wp-rest-request.php | Canonicalizes the header name. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::set_file_params( array $params ) WP\_REST\_Request::set\_file\_params( array $params )
=====================================================
Sets multipart file parameters from the body.
Typically, this is set from `$_FILES`.
`$params` array Required Parameter map of key to value. File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function set_file_params( $params ) {
$this->params['FILES'] = $params;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::get_file_params(): array WP\_REST\_Request::get\_file\_params(): array
=============================================
Retrieves multipart file parameters from the body.
These are the parameters you’d typically find in `$_FILES`.
array Parameter map of key to value
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_file_params() {
return $this->params['FILES'];
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Request::is_json_content_type(): bool WP\_REST\_Request::is\_json\_content\_type(): bool
==================================================
Checks if the request has specified a JSON content-type.
bool True if the content-type header is JSON.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function is_json_content_type() {
$content_type = $this->get_content_type();
return isset( $content_type['value'] ) && wp_is_json_media_type( $content_type['value'] );
}
```
| Uses | Description |
| --- | --- |
| [wp\_is\_json\_media\_type()](../../functions/wp_is_json_media_type) wp-includes/load.php | Checks whether a string is a valid JSON Media Type. |
| [WP\_REST\_Request::get\_content\_type()](get_content_type) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the content-type of the request. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::parse\_json\_params()](parse_json_params) wp-includes/rest-api/class-wp-rest-request.php | Parses the JSON parameters. |
| [WP\_REST\_Request::get\_parameter\_order()](get_parameter_order) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the parameter priority order. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_REST_Request::get_attributes(): array WP\_REST\_Request::get\_attributes(): array
===========================================
Retrieves the attributes for the request.
These are the options for the route that was matched.
array Attributes for the request.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_attributes() {
return $this->attributes;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::sanitize\_params()](sanitize_params) wp-includes/rest-api/class-wp-rest-request.php | Sanitizes (where possible) the params on the request. |
| [WP\_REST\_Request::has\_valid\_params()](has_valid_params) wp-includes/rest-api/class-wp-rest-request.php | Checks whether this request is valid according to its attributes. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::get_body(): string WP\_REST\_Request::get\_body(): string
======================================
Retrieves the request body content.
string Binary data from the request body.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_body() {
return $this->body;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::parse\_json\_params()](parse_json_params) wp-includes/rest-api/class-wp-rest-request.php | Parses the JSON parameters. |
| [WP\_REST\_Request::parse\_body\_params()](parse_body_params) wp-includes/rest-api/class-wp-rest-request.php | Parses the request body parameters. |
| [WP\_REST\_Request::get\_parameter\_order()](get_parameter_order) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the parameter priority order. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::set_route( string $route ) WP\_REST\_Request::set\_route( string $route )
==============================================
Sets the route that matched the request.
`$route` string Required Route matching regex. File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function set_route( $route ) {
$this->route = $route;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::\_\_construct()](__construct) wp-includes/rest-api/class-wp-rest-request.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::get_method(): string WP\_REST\_Request::get\_method(): string
========================================
Retrieves the HTTP method for the request.
string HTTP method.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_method() {
return $this->method;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::get_parameter_order(): string[] WP\_REST\_Request::get\_parameter\_order(): string[]
====================================================
Retrieves the parameter priority order.
Used when checking parameters in [WP\_REST\_Request::get\_param()](get_param).
string[] Array of types to check, in order of priority.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
protected function get_parameter_order() {
$order = array();
if ( $this->is_json_content_type() ) {
$order[] = 'JSON';
}
$this->parse_json_params();
// Ensure we parse the body data.
$body = $this->get_body();
if ( 'POST' !== $this->method && ! empty( $body ) ) {
$this->parse_body_params();
}
$accepts_body_data = array( 'POST', 'PUT', 'PATCH', 'DELETE' );
if ( in_array( $this->method, $accepts_body_data, true ) ) {
$order[] = 'POST';
}
$order[] = 'GET';
$order[] = 'URL';
$order[] = 'defaults';
/**
* Filters the parameter priority order for a REST API request.
*
* The order affects which parameters are checked when using WP_REST_Request::get_param()
* and family. This acts similarly to PHP's `request_order` setting.
*
* @since 4.4.0
*
* @param string[] $order Array of types to check, in order of priority.
* @param WP_REST_Request $request The request object.
*/
return apply_filters( 'rest_request_parameter_order', $order, $this );
}
```
[apply\_filters( 'rest\_request\_parameter\_order', string[] $order, WP\_REST\_Request $request )](../../hooks/rest_request_parameter_order)
Filters the parameter priority order for a REST API request.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::is\_json\_content\_type()](is_json_content_type) wp-includes/rest-api/class-wp-rest-request.php | Checks if the request has specified a JSON content-type. |
| [WP\_REST\_Request::parse\_json\_params()](parse_json_params) wp-includes/rest-api/class-wp-rest-request.php | Parses the JSON parameters. |
| [WP\_REST\_Request::parse\_body\_params()](parse_body_params) wp-includes/rest-api/class-wp-rest-request.php | Parses the request body parameters. |
| [WP\_REST\_Request::get\_body()](get_body) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the request body content. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::has\_param()](has_param) wp-includes/rest-api/class-wp-rest-request.php | Checks if a parameter exists in the request. |
| [WP\_REST\_Request::offsetUnset()](offsetunset) wp-includes/rest-api/class-wp-rest-request.php | |
| [WP\_REST\_Request::sanitize\_params()](sanitize_params) wp-includes/rest-api/class-wp-rest-request.php | Sanitizes (where possible) the params on the request. |
| [WP\_REST\_Request::offsetExists()](offsetexists) wp-includes/rest-api/class-wp-rest-request.php | |
| [WP\_REST\_Request::get\_param()](get_param) wp-includes/rest-api/class-wp-rest-request.php | Retrieves a parameter from the request. |
| [WP\_REST\_Request::set\_param()](set_param) wp-includes/rest-api/class-wp-rest-request.php | Sets a parameter on the request. |
| [WP\_REST\_Request::get\_params()](get_params) wp-includes/rest-api/class-wp-rest-request.php | Retrieves merged parameters from the request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::offsetExists( $offset ) WP\_REST\_Request::offsetExists( $offset )
==========================================
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function offsetExists( $offset ) {
$order = $this->get_parameter_order();
foreach ( $order as $type ) {
if ( isset( $this->params[ $type ][ $offset ] ) ) {
return true;
}
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::get\_parameter\_order()](get_parameter_order) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the parameter priority order. |
wordpress WP_REST_Request::get_body_params(): array WP\_REST\_Request::get\_body\_params(): array
=============================================
Retrieves parameters from the body.
These are the parameters you’d typically find in `$_POST`.
array Parameter map of key to value.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_body_params() {
return $this->params['POST'];
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::__construct( string $method = '', string $route = '', array $attributes = array() ) WP\_REST\_Request::\_\_construct( string $method = '', string $route = '', array $attributes = array() )
========================================================================================================
Constructor.
`$method` string Optional Request method. Default: `''`
`$route` string Optional Request route. Default: `''`
`$attributes` array Optional Request attributes. Default: `array()`
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function __construct( $method = '', $route = '', $attributes = array() ) {
$this->params = array(
'URL' => array(),
'GET' => array(),
'POST' => array(),
'FILES' => array(),
// See parse_json_params.
'JSON' => null,
'defaults' => array(),
);
$this->set_method( $method );
$this->set_route( $route );
$this->set_attributes( $attributes );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::set\_attributes()](set_attributes) wp-includes/rest-api/class-wp-rest-request.php | Sets the attributes for the request. |
| [WP\_REST\_Request::set\_route()](set_route) wp-includes/rest-api/class-wp-rest-request.php | Sets the route that matched the request. |
| [WP\_REST\_Request::set\_method()](set_method) wp-includes/rest-api/class-wp-rest-request.php | Sets HTTP method for the request. |
| Used By | Description |
| --- | --- |
| [\_register\_remote\_theme\_patterns()](../../functions/_register_remote_theme_patterns) wp-includes/block-patterns.php | Registers patterns from Pattern Directory provided by a theme’s `theme.json` file. |
| [\_load\_remote\_featured\_patterns()](../../functions/_load_remote_featured_patterns) wp-includes/block-patterns.php | Register `Featured` (category) patterns from wordpress.org/patterns. |
| [\_load\_remote\_block\_patterns()](../../functions/_load_remote_block_patterns) wp-includes/block-patterns.php | Register Core’s official patterns from wordpress.org/patterns. |
| [WP\_REST\_Server::serve\_batch\_request\_v1()](../wp_rest_server/serve_batch_request_v1) wp-includes/rest-api/class-wp-rest-server.php | Serves the batch/v1 request. |
| [rest\_preload\_api\_request()](../../functions/rest_preload_api_request) wp-includes/rest-api.php | Append result of internal request to REST API for purpose of preloading data to be attached to a page. |
| [WP\_REST\_Request::from\_url()](from_url) wp-includes/rest-api/class-wp-rest-request.php | Retrieves a [WP\_REST\_Request](../wp_rest_request) object from a full URL. |
| [rest\_ensure\_request()](../../functions/rest_ensure_request) wp-includes/rest-api.php | Ensures request arguments are a request object (for consistency). |
| [WP\_REST\_Server::serve\_request()](../wp_rest_server/serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::get_query_params(): array WP\_REST\_Request::get\_query\_params(): array
==============================================
Retrieves parameters from the query string.
These are the parameters you’d typically find in `$_GET`.
array Parameter map of key to value
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_query_params() {
return $this->params['GET'];
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::add_header( string $key, string $value ) WP\_REST\_Request::add\_header( string $key, string $value )
============================================================
Appends a header value for the given header.
`$key` string Required Header name. `$value` string Required Header value, or list of values. File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function add_header( $key, $value ) {
$key = $this->canonicalize_header_name( $key );
$value = (array) $value;
if ( ! isset( $this->headers[ $key ] ) ) {
$this->headers[ $key ] = array();
}
$this->headers[ $key ] = array_merge( $this->headers[ $key ], $value );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::canonicalize\_header\_name()](canonicalize_header_name) wp-includes/rest-api/class-wp-rest-request.php | Canonicalizes the header name. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::has_valid_params(): true|WP_Error WP\_REST\_Request::has\_valid\_params(): true|WP\_Error
=======================================================
Checks whether this request is valid according to its attributes.
true|[WP\_Error](../wp_error) True if there are no parameters to validate or if all pass validation, [WP\_Error](../wp_error) if required parameters are missing.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function has_valid_params() {
// If JSON data was passed, check for errors.
$json_error = $this->parse_json_params();
if ( is_wp_error( $json_error ) ) {
return $json_error;
}
$attributes = $this->get_attributes();
$required = array();
$args = empty( $attributes['args'] ) ? array() : $attributes['args'];
foreach ( $args as $key => $arg ) {
$param = $this->get_param( $key );
if ( isset( $arg['required'] ) && true === $arg['required'] && null === $param ) {
$required[] = $key;
}
}
if ( ! empty( $required ) ) {
return new WP_Error(
'rest_missing_callback_param',
/* translators: %s: List of required parameters. */
sprintf( __( 'Missing parameter(s): %s' ), implode( ', ', $required ) ),
array(
'status' => 400,
'params' => $required,
)
);
}
/*
* Check the validation callbacks for each registered arg.
*
* This is done after required checking as required checking is cheaper.
*/
$invalid_params = array();
$invalid_details = array();
foreach ( $args as $key => $arg ) {
$param = $this->get_param( $key );
if ( null !== $param && ! empty( $arg['validate_callback'] ) ) {
/** @var bool|\WP_Error $valid_check */
$valid_check = call_user_func( $arg['validate_callback'], $param, $this, $key );
if ( false === $valid_check ) {
$invalid_params[ $key ] = __( 'Invalid parameter.' );
}
if ( is_wp_error( $valid_check ) ) {
$invalid_params[ $key ] = implode( ' ', $valid_check->get_error_messages() );
$invalid_details[ $key ] = rest_convert_error_to_response( $valid_check )->get_data();
}
}
}
if ( $invalid_params ) {
return new WP_Error(
'rest_invalid_param',
/* translators: %s: List of invalid parameters. */
sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', array_keys( $invalid_params ) ) ),
array(
'status' => 400,
'params' => $invalid_params,
'details' => $invalid_details,
)
);
}
if ( isset( $attributes['validate_callback'] ) ) {
$valid_check = call_user_func( $attributes['validate_callback'], $this );
if ( is_wp_error( $valid_check ) ) {
return $valid_check;
}
if ( false === $valid_check ) {
// A WP_Error instance is preferred, but false is supported for parity with the per-arg validate_callback.
return new WP_Error( 'rest_invalid_params', __( 'Invalid parameters.' ), array( 'status' => 400 ) );
}
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [rest\_convert\_error\_to\_response()](../../functions/rest_convert_error_to_response) wp-includes/rest-api.php | Converts an error to a response object. |
| [WP\_REST\_Request::get\_attributes()](get_attributes) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the attributes for the request. |
| [WP\_REST\_Request::parse\_json\_params()](parse_json_params) wp-includes/rest-api/class-wp-rest-request.php | Parses the JSON parameters. |
| [WP\_REST\_Request::get\_param()](get_param) wp-includes/rest-api/class-wp-rest-request.php | Retrieves a parameter from the request. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::get_header_as_array( string $key ): array|null WP\_REST\_Request::get\_header\_as\_array( string $key ): array|null
====================================================================
Retrieves header values from the request.
`$key` string Required Header name, will be canonicalized to lowercase. array|null List of string values if set, null otherwise.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_header_as_array( $key ) {
$key = $this->canonicalize_header_name( $key );
if ( ! isset( $this->headers[ $key ] ) ) {
return null;
}
return $this->headers[ $key ];
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::canonicalize\_header\_name()](canonicalize_header_name) wp-includes/rest-api/class-wp-rest-request.php | Canonicalizes the header name. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Request::parse_json_params(): true|WP_Error WP\_REST\_Request::parse\_json\_params(): true|WP\_Error
========================================================
Parses the JSON parameters.
Avoids parsing the JSON data until we need to access it.
true|[WP\_Error](../wp_error) True if the JSON data was passed or no JSON data was provided, [WP\_Error](../wp_error) if invalid JSON was passed.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
protected function parse_json_params() {
if ( $this->parsed_json ) {
return true;
}
$this->parsed_json = true;
// Check that we actually got JSON.
if ( ! $this->is_json_content_type() ) {
return true;
}
$body = $this->get_body();
if ( empty( $body ) ) {
return true;
}
$params = json_decode( $body, true );
/*
* Check for a parsing error.
*/
if ( null === $params && JSON_ERROR_NONE !== json_last_error() ) {
// Ensure subsequent calls receive error instance.
$this->parsed_json = false;
$error_data = array(
'status' => WP_Http::BAD_REQUEST,
'json_error_code' => json_last_error(),
'json_error_message' => json_last_error_msg(),
);
return new WP_Error( 'rest_invalid_json', __( 'Invalid JSON body passed.' ), $error_data );
}
$this->params['JSON'] = $params;
return true;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Request::is\_json\_content\_type()](is_json_content_type) wp-includes/rest-api/class-wp-rest-request.php | Checks if the request has specified a JSON content-type. |
| [WP\_REST\_Request::get\_body()](get_body) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the request body content. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Request::has\_valid\_params()](has_valid_params) wp-includes/rest-api/class-wp-rest-request.php | Checks whether this request is valid according to its attributes. |
| [WP\_REST\_Request::get\_json\_params()](get_json_params) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the parameters from a JSON-formatted body. |
| [WP\_REST\_Request::get\_parameter\_order()](get_parameter_order) wp-includes/rest-api/class-wp-rest-request.php | Retrieves the parameter priority order. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Returns error instance if value cannot be decoded. |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::set_query_params( array $params ) WP\_REST\_Request::set\_query\_params( array $params )
======================================================
Sets parameters from the query string.
Typically, this is set from `$_GET`.
`$params` array Required Parameter map of key to value. File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function set_query_params( $params ) {
$this->params['GET'] = $params;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::get_url_params(): array WP\_REST\_Request::get\_url\_params(): array
============================================
Retrieves parameters from the route itself.
These are parsed from the URL using the regex.
array Parameter map of key to value.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_url_params() {
return $this->params['URL'];
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::get_route(): string WP\_REST\_Request::get\_route(): string
=======================================
Retrieves the route that matched the request.
string Route matching regex.
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_route() {
return $this->route;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::get_default_params(): array WP\_REST\_Request::get\_default\_params(): array
================================================
Retrieves the default parameters.
These are the parameters set in the route registration.
array Parameter map of key to value
File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function get_default_params() {
return $this->params['defaults'];
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Request::set_body_params( array $params ) WP\_REST\_Request::set\_body\_params( array $params )
=====================================================
Sets parameters from the body.
Typically, this is set from `$_POST`.
`$params` array Required Parameter map of key to value. File: `wp-includes/rest-api/class-wp-rest-request.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/class-wp-rest-request.php/)
```
public function set_body_params( $params ) {
$this->params['POST'] = $params;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Error::get_error_message( string|int $code = '' ): string WP\_Error::get\_error\_message( string|int $code = '' ): string
===============================================================
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.
`$code` string|int Optional Error code to retrieve message. Default: `''`
string The error message.
File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/)
```
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];
}
```
| Uses | Description |
| --- | --- |
| [WP\_Error::get\_error\_code()](get_error_code) wp-includes/class-wp-error.php | Retrieves the first error code available. |
| [WP\_Error::get\_error\_messages()](get_error_messages) wp-includes/class-wp-error.php | Retrieves all error messages, or the error messages for the given error code. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Error::copy_errors( WP_Error $from, WP_Error $to ) WP\_Error::copy\_errors( WP\_Error $from, WP\_Error $to )
=========================================================
Copies errors from one [WP\_Error](../wp_error) instance to another.
`$from` [WP\_Error](../wp_error) Required The [WP\_Error](../wp_error) to copy from. `$to` [WP\_Error](../wp_error) Required The [WP\_Error](../wp_error) to copy to. File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/)
```
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 |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Error::merge_from( WP_Error $error ) WP\_Error::merge\_from( WP\_Error $error )
==========================================
Merges the errors in the given error object into this one.
`$error` [WP\_Error](../wp_error) Required Error object to merge. File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/)
```
public function merge_from( WP_Error $error ) {
static::copy_errors( $error, $this );
}
```
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Error::add( string|int $code, string $message, mixed $data = '' ) WP\_Error::add( string|int $code, string $message, mixed $data = '' )
=====================================================================
Adds an error or appends an additional message to an existing error.
`$code` string|int Required Error code. `$message` string Required Error message. `$data` mixed Optional Error data. Default: `''`
File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/)
```
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 );
}
```
[do\_action( 'wp\_error\_added', string|int $code, string $message, mixed $data, WP\_Error $wp\_error )](../../hooks/wp_error_added)
Fires when an error is added to a [WP\_Error](../wp_error) object.
| Uses | Description |
| --- | --- |
| [WP\_Error::add\_data()](add_data) wp-includes/class-wp-error.php | Adds data to an error with the given code. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [login\_header()](../../functions/login_header) wp-login.php | Output the login page header. |
| [WP\_Error::\_\_construct()](__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Error::remove( string|int $code ) WP\_Error::remove( string|int $code )
=====================================
Removes the specified error.
This function removes all error messages associated with the specified error code, along with any error data for that code.
`$code` string|int Required Error code. File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/)
```
public function remove( $code ) {
unset( $this->errors[ $code ] );
unset( $this->error_data[ $code ] );
unset( $this->additional_data[ $code ] );
}
```
| Version | Description |
| --- | --- |
| [4.1.0](https://developer.wordpress.org/reference/since/4.1.0/) | Introduced. |
wordpress WP_Error::get_error_code(): string|int WP\_Error::get\_error\_code(): string|int
=========================================
Retrieves the first error code available.
string|int Empty string, if no error codes.
File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/)
```
public function get_error_code() {
$codes = $this->get_error_codes();
if ( empty( $codes ) ) {
return '';
}
return $codes[0];
}
```
| Uses | Description |
| --- | --- |
| [WP\_Error::get\_error\_codes()](get_error_codes) wp-includes/class-wp-error.php | Retrieves all error codes. |
| Used By | Description |
| --- | --- |
| [WP\_Error::get\_all\_error\_data()](get_all_error_data) wp-includes/class-wp-error.php | Retrieves all error data for an error code in the order in which the data was added. |
| [Plugin\_Installer\_Skin::hide\_process\_failed()](../plugin_installer_skin/hide_process_failed) wp-admin/includes/class-plugin-installer-skin.php | Hides the `process_failed` error when updating a plugin by uploading a zip file. |
| [Theme\_Installer\_Skin::hide\_process\_failed()](../theme_installer_skin/hide_process_failed) wp-admin/includes/class-theme-installer-skin.php | Hides the `process_failed` error when updating a theme by uploading a zip file. |
| [login\_header()](../../functions/login_header) wp-login.php | Output the login page header. |
| [WP\_Error::get\_error\_message()](get_error_message) wp-includes/class-wp-error.php | Gets a single error message. |
| [WP\_Error::get\_error\_data()](get_error_data) wp-includes/class-wp-error.php | Retrieves the most recently added error data for an error code. |
| [WP\_Error::add\_data()](add_data) wp-includes/class-wp-error.php | Adds data to an error with the given code. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Error::get_error_codes(): array WP\_Error::get\_error\_codes(): array
=====================================
Retrieves all error codes.
array List of error codes, if available.
File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/)
```
public function get_error_codes() {
if ( ! $this->has_errors() ) {
return array();
}
return array_keys( $this->errors );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Error::has\_errors()](has_errors) wp-includes/class-wp-error.php | Verifies if the instance contains errors. |
| Used By | Description |
| --- | --- |
| [login\_header()](../../functions/login_header) wp-login.php | Output the login page header. |
| [WP\_Error::get\_error\_code()](get_error_code) wp-includes/class-wp-error.php | Retrieves the first error code available. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Error::add_data( mixed $data, string|int $code = '' ) WP\_Error::add\_data( mixed $data, string|int $code = '' )
==========================================================
Adds data to an error with the given code.
`$data` mixed Required Error data. `$code` string|int Optional Error code. Default: `''`
File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Error::get\_error\_code()](get_error_code) wp-includes/class-wp-error.php | Retrieves the first error code available. |
| Used By | Description |
| --- | --- |
| [WP\_Error::add()](add) wp-includes/class-wp-error.php | Adds an error or appends an additional message to an existing error. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Errors can now contain more than one item of error data. WP\_Error::$additional\_data. |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Error::export_to( WP_Error $error ) WP\_Error::export\_to( WP\_Error $error )
=========================================
Exports the errors in this object into the given one.
`$error` [WP\_Error](../wp_error) Required Error object to export into. File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/)
```
public function export_to( WP_Error $error ) {
static::copy_errors( $this, $error );
}
```
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Error::get_all_error_data( string|int $code = '' ): mixed[] WP\_Error::get\_all\_error\_data( string|int $code = '' ): mixed[]
==================================================================
Retrieves all error data for an error code in the order in which the data was added.
`$code` string|int Optional Error code. Default: `''`
mixed[] Array of error data, if it exists.
File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Error::get\_error\_code()](get_error_code) wp-includes/class-wp-error.php | Retrieves the first error code available. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Error::get_error_messages( string|int $code = '' ): string[] WP\_Error::get\_error\_messages( string|int $code = '' ): string[]
==================================================================
Retrieves all error messages, or the error messages for the given error code.
`$code` string|int Optional Retrieve messages matching code, if exists. Default: `''`
string[] Error strings on success, or empty array if there are none.
File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/)
```
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();
}
}
```
| Used By | Description |
| --- | --- |
| [login\_header()](../../functions/login_header) wp-login.php | Output the login page header. |
| [WP\_Error::get\_error\_message()](get_error_message) wp-includes/class-wp-error.php | Gets a single error message. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Error::__construct( string|int $code = '', string $message = '', mixed $data = '' ) WP\_Error::\_\_construct( string|int $code = '', string $message = '', mixed $data = '' )
=========================================================================================
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.
`$code` string|int Optional Error code. Default: `''`
`$message` string Optional Error message. Default: `''`
`$data` mixed Optional Error data. Default: `''`
File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/)
```
public function __construct( $code = '', $message = '', $data = '' ) {
if ( empty( $code ) ) {
return;
}
$this->add( $code, $message, $data );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Error::add()](add) wp-includes/class-wp-error.php | Adds an error or appends an additional message to an existing error. |
| Used By | Description |
| --- | --- |
| [wp\_get\_latest\_revision\_id\_and\_total\_count()](../../functions/wp_get_latest_revision_id_and_total_count) wp-includes/revision.php | Returns the latest revision ID and count of revisions for a post. |
| [WP\_Site\_Health::check\_for\_page\_caching()](../wp_site_health/check_for_page_caching) wp-admin/includes/class-wp-site-health.php | Checks if site has page cache enabled or not. |
| [WP\_REST\_Block\_Patterns\_Controller::get\_items\_permissions\_check()](../wp_rest_block_patterns_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-block-patterns-controller.php | Checks whether a given request has permission to read block patterns. |
| [WP\_REST\_Global\_Styles\_Controller::get\_theme\_items\_permissions\_check()](../wp_rest_global_styles_controller/get_theme_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Checks if a given request has access to read a single theme global styles config. |
| [WP\_REST\_Global\_Styles\_Controller::get\_theme\_items()](../wp_rest_global_styles_controller/get_theme_items) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Returns the given theme global styles variations. |
| [WP\_REST\_Block\_Pattern\_Categories\_Controller::get\_items\_permissions\_check()](../wp_rest_block_pattern_categories_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-block-pattern-categories-controller.php | Checks whether a given request has permission to read block patterns. |
| [WP\_REST\_Menu\_Items\_Controller::get\_item\_schema()](../wp_rest_menu_items_controller/get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Retrieves the term’s schema, conforming to JSON Schema. |
| [WP\_REST\_Menu\_Items\_Controller::check\_has\_read\_only\_access()](../wp_rest_menu_items_controller/check_has_read_only_access) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Checks whether the current user has read permission for the endpoint. |
| [WP\_REST\_Menu\_Items\_Controller::create\_item()](../wp_rest_menu_items_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Creates a single post. |
| [WP\_REST\_Menu\_Items\_Controller::delete\_item()](../wp_rest_menu_items_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Deletes a single menu item. |
| [WP\_REST\_Menu\_Items\_Controller::prepare\_item\_for\_database()](../wp_rest_menu_items_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Prepares a single post for create or update. |
| [WP\_REST\_Global\_Styles\_Controller::get\_theme\_item\_permissions\_check()](../wp_rest_global_styles_controller/get_theme_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Checks if a given request has access to read a single theme global styles config. |
| [WP\_REST\_Global\_Styles\_Controller::get\_theme\_item()](../wp_rest_global_styles_controller/get_theme_item) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Returns the given theme global styles config. |
| [WP\_REST\_Global\_Styles\_Controller::get\_post()](../wp_rest_global_styles_controller/get_post) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Get the post, if the ID is valid. |
| [WP\_REST\_Global\_Styles\_Controller::get\_item\_permissions\_check()](../wp_rest_global_styles_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Checks if a given request has access to read a single global style. |
| [WP\_REST\_Global\_Styles\_Controller::update\_item\_permissions\_check()](../wp_rest_global_styles_controller/update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-global-styles-controller.php | Checks if a given request has access to write a single global styles config. |
| [WP\_REST\_URL\_Details\_Controller::parse\_url\_details()](../wp_rest_url_details_controller/parse_url_details) wp-includes/rest-api/endpoints/class-wp-rest-url-details-controller.php | Retrieves the contents of the title tag from the HTML response. |
| [WP\_REST\_URL\_Details\_Controller::permissions\_check()](../wp_rest_url_details_controller/permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-url-details-controller.php | Checks whether a given request has permission to read remote URLs. |
| [WP\_REST\_URL\_Details\_Controller::get\_remote\_url()](../wp_rest_url_details_controller/get_remote_url) wp-includes/rest-api/endpoints/class-wp-rest-url-details-controller.php | Retrieves the document title from a remote URL. |
| [WP\_REST\_Menus\_Controller::check\_has\_read\_only\_access()](../wp_rest_menus_controller/check_has_read_only_access) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Checks whether the current user has read permission for the endpoint. |
| [WP\_REST\_Menus\_Controller::create\_item()](../wp_rest_menus_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Creates a single term in a taxonomy. |
| [WP\_REST\_Menus\_Controller::update\_item()](../wp_rest_menus_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Updates a single term from a taxonomy. |
| [WP\_REST\_Menus\_Controller::delete\_item()](../wp_rest_menus_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Deletes a single term from a taxonomy. |
| [WP\_REST\_Menus\_Controller::handle\_locations()](../wp_rest_menus_controller/handle_locations) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Updates the menu’s locations from a REST request. |
| [WP\_REST\_Menus\_Controller::get\_item\_schema()](../wp_rest_menus_controller/get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php | Retrieves the term’s schema, conforming to JSON Schema. |
| [WP\_REST\_Menu\_Locations\_Controller::get\_items\_permissions\_check()](../wp_rest_menu_locations_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php | Checks whether a given request has permission to read menu locations. |
| [WP\_REST\_Menu\_Locations\_Controller::get\_item\_permissions\_check()](../wp_rest_menu_locations_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php | Checks if a given request has access to read a menu location. |
| [WP\_REST\_Menu\_Locations\_Controller::get\_item()](../wp_rest_menu_locations_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-menu-locations-controller.php | Retrieves a specific menu location. |
| [WP\_REST\_Edit\_Site\_Export\_Controller::permissions\_check()](../wp_rest_edit_site_export_controller/permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-edit-site-export-controller.php | Checks whether a given request has permission to export. |
| [wp\_generate\_block\_templates\_export\_file()](../../functions/wp_generate_block_templates_export_file) wp-includes/block-template-utils.php | Creates an export of the current templates and template parts from the site editor at the specified path in a ZIP file. |
| [\_build\_block\_template\_result\_from\_post()](../../functions/_build_block_template_result_from_post) wp-includes/block-template-utils.php | Builds a unified template object based a post Object. |
| [WP\_REST\_Widgets\_Controller::prepare\_item\_for\_response()](../wp_rest_widgets_controller/prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Prepares the widget for the REST response. |
| [WP\_REST\_Widgets\_Controller::get\_item()](../wp_rest_widgets_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Gets an individual widget. |
| [WP\_REST\_Widgets\_Controller::update\_item()](../wp_rest_widgets_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Updates an existing widget. |
| [WP\_REST\_Widgets\_Controller::delete\_item()](../wp_rest_widgets_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Deletes a widget. |
| [WP\_REST\_Widgets\_Controller::permissions\_check()](../wp_rest_widgets_controller/permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Performs a permissions check for managing widgets. |
| [WP\_REST\_Widgets\_Controller::save\_widget()](../wp_rest_widgets_controller/save_widget) wp-includes/rest-api/endpoints/class-wp-rest-widgets-controller.php | Saves the widget in the request object. |
| [WP\_REST\_Sidebars\_Controller::get\_item()](../wp_rest_sidebars_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Retrieves one sidebar from the collection. |
| [WP\_REST\_Sidebars\_Controller::do\_permissions\_check()](../wp_rest_sidebars_controller/do_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-sidebars-controller.php | Checks if the user has permissions to make the request. |
| [WP\_REST\_Templates\_Controller::permissions\_check()](../wp_rest_templates_controller/permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Checks if the user has permissions to make the request. |
| [WP\_REST\_Templates\_Controller::get\_item()](../wp_rest_templates_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Returns the given template |
| [WP\_REST\_Templates\_Controller::update\_item()](../wp_rest_templates_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Updates a single template. |
| [WP\_REST\_Templates\_Controller::create\_item()](../wp_rest_templates_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Creates a single template. |
| [WP\_REST\_Templates\_Controller::delete\_item()](../wp_rest_templates_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Deletes a single template. |
| [WP\_REST\_Templates\_Controller::prepare\_item\_for\_database()](../wp_rest_templates_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | Prepares a single template for create or update. |
| [WP\_REST\_Pattern\_Directory\_Controller::get\_items\_permissions\_check()](../wp_rest_pattern_directory_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php | Checks whether a given request has permission to view the local block pattern directory. |
| [WP\_REST\_Pattern\_Directory\_Controller::get\_items()](../wp_rest_pattern_directory_controller/get_items) wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php | Search and retrieve block patterns metadata |
| [WP\_REST\_Widget\_Types\_Controller::encode\_form\_data()](../wp_rest_widget_types_controller/encode_form_data) wp-includes/rest-api/endpoints/class-wp-rest-widget-types-controller.php | An RPC-style endpoint which can be used by clients to turn user input in a widget admin form into an encoded instance object. |
| [WP\_REST\_Widget\_Types\_Controller::check\_read\_permission()](../wp_rest_widget_types_controller/check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-widget-types-controller.php | Checks whether the user can read widget types. |
| [WP\_REST\_Widget\_Types\_Controller::get\_widget()](../wp_rest_widget_types_controller/get_widget) wp-includes/rest-api/endpoints/class-wp-rest-widget-types-controller.php | Gets the details about the requested widget. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_current\_item\_permissions\_check()](../wp_rest_application_passwords_controller/get_current_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to get the currently used application password for a user. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_current\_item()](../wp_rest_application_passwords_controller/get_current_item) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Retrieves the application password being currently used for authentication of a user. |
| [WP\_REST\_Themes\_Controller::get\_item\_permissions\_check()](../wp_rest_themes_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Checks if a given request has access to read the theme. |
| [WP\_REST\_Themes\_Controller::check\_read\_active\_theme\_permission()](../wp_rest_themes_controller/check_read_active_theme_permission) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Checks if a theme can be read. |
| [WP\_REST\_Themes\_Controller::get\_item()](../wp_rest_themes_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Retrieves a single theme. |
| [wp\_update\_https\_detection\_errors()](../../functions/wp_update_https_detection_errors) wp-includes/https-detection.php | Runs a remote HTTPS request to detect whether HTTPS supported, and stores potential errors. |
| [rest\_validate\_integer\_value\_from\_schema()](../../functions/rest_validate_integer_value_from_schema) wp-includes/rest-api.php | Validates an integer value based on a schema. |
| [rest\_validate\_enum()](../../functions/rest_validate_enum) wp-includes/rest-api.php | Validates that the given value is a member of the JSON Schema “enum”. |
| [rest\_validate\_null\_value\_from\_schema()](../../functions/rest_validate_null_value_from_schema) wp-includes/rest-api.php | Validates a null value based on a schema. |
| [rest\_validate\_boolean\_value\_from\_schema()](../../functions/rest_validate_boolean_value_from_schema) wp-includes/rest-api.php | Validates a boolean value based on a schema. |
| [rest\_validate\_object\_value\_from\_schema()](../../functions/rest_validate_object_value_from_schema) wp-includes/rest-api.php | Validates an object value based on a schema. |
| [rest\_validate\_array\_value\_from\_schema()](../../functions/rest_validate_array_value_from_schema) wp-includes/rest-api.php | Validates an array value based on a schema. |
| [rest\_validate\_number\_value\_from\_schema()](../../functions/rest_validate_number_value_from_schema) wp-includes/rest-api.php | Validates a number value based on a schema. |
| [rest\_validate\_string\_value\_from\_schema()](../../functions/rest_validate_string_value_from_schema) wp-includes/rest-api.php | Validates a string value based on a schema. |
| [WP\_REST\_Server::serve\_batch\_request\_v1()](../wp_rest_server/serve_batch_request_v1) wp-includes/rest-api/class-wp-rest-server.php | Serves the batch/v1 request. |
| [WP\_REST\_Server::match\_request\_to\_handler()](../wp_rest_server/match_request_to_handler) wp-includes/rest-api/class-wp-rest-server.php | Matches a request object to its handler. |
| [WP\_REST\_Server::respond\_to\_request()](../wp_rest_server/respond_to_request) wp-includes/rest-api/class-wp-rest-server.php | Dispatches the request to the callback handler. |
| [WP\_REST\_Site\_Health\_Controller::get\_directory\_sizes()](../wp_rest_site_health_controller/get_directory_sizes) wp-includes/rest-api/endpoints/class-wp-rest-site-health-controller.php | Gets the current directory sizes for this install. |
| [WP\_REST\_Application\_Passwords\_Controller::do\_permissions\_check()](../wp_rest_application_passwords_controller/do_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Performs a permissions check for the request. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_user()](../wp_rest_application_passwords_controller/get_user) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested user. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_application\_password()](../wp_rest_application_passwords_controller/get_application_password) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Gets the requested application password for a user. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_items\_permissions\_check()](../wp_rest_application_passwords_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to get application passwords. |
| [WP\_REST\_Application\_Passwords\_Controller::get\_item\_permissions\_check()](../wp_rest_application_passwords_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to get a specific application password. |
| [WP\_REST\_Application\_Passwords\_Controller::create\_item\_permissions\_check()](../wp_rest_application_passwords_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to create application passwords. |
| [WP\_REST\_Application\_Passwords\_Controller::update\_item\_permissions\_check()](../wp_rest_application_passwords_controller/update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to update application passwords. |
| [WP\_REST\_Application\_Passwords\_Controller::delete\_items\_permissions\_check()](../wp_rest_application_passwords_controller/delete_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to delete all application passwords for a user. |
| [WP\_REST\_Application\_Passwords\_Controller::delete\_item\_permissions\_check()](../wp_rest_application_passwords_controller/delete_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php | Checks if a given request has access to delete a specific application password for a user. |
| [WP\_Image\_Editor\_Imagick::write\_image()](../wp_image_editor_imagick/write_image) wp-includes/class-wp-image-editor-imagick.php | Writes an image to a file or stream. |
| [WP\_Application\_Passwords::delete\_application\_password()](../wp_application_passwords/delete_application_password) wp-includes/class-wp-application-passwords.php | Deletes an application password. |
| [WP\_Application\_Passwords::delete\_all\_application\_passwords()](../wp_application_passwords/delete_all_application_passwords) wp-includes/class-wp-application-passwords.php | Deletes all application passwords for the given user. |
| [WP\_Application\_Passwords::create\_new\_application\_password()](../wp_application_passwords/create_new_application_password) wp-includes/class-wp-application-passwords.php | Creates a new application password. |
| [WP\_Application\_Passwords::update\_application\_password()](../wp_application_passwords/update_application_password) wp-includes/class-wp-application-passwords.php | Updates an application password. |
| [WP\_Application\_Passwords::record\_application\_password\_usage()](../wp_application_passwords/record_application_password_usage) wp-includes/class-wp-application-passwords.php | Records that an application password has been used. |
| [wp\_authenticate\_application\_password()](../../functions/wp_authenticate_application_password) wp-includes/user.php | Authenticates the user using an application password. |
| [rest\_format\_combining\_operation\_error()](../../functions/rest_format_combining_operation_error) wp-includes/rest-api.php | Formats a combining operation error into a [WP\_Error](../wp_error) object. |
| [rest\_get\_combining\_operation\_error()](../../functions/rest_get_combining_operation_error) wp-includes/rest-api.php | Gets the error of combining operation. |
| [rest\_find\_one\_matching\_schema()](../../functions/rest_find_one_matching_schema) wp-includes/rest-api.php | Finds the matching schema among the “oneOf” schemas. |
| [wp\_is\_authorize\_application\_password\_request\_valid()](../../functions/wp_is_authorize_application_password_request_valid) wp-admin/includes/user.php | Checks if the Authorize Application Password request is valid. |
| [WP\_REST\_Block\_Directory\_Controller::get\_items\_permissions\_check()](../wp_rest_block_directory_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-block-directory-controller.php | Checks whether a given request has permission to install and activate plugins. |
| [WP\_REST\_Plugins\_Controller::get\_plugin\_data()](../wp_rest_plugins_controller/get_plugin_data) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Gets the plugin header data for a plugin. |
| [WP\_REST\_Plugins\_Controller::plugin\_status\_permission\_check()](../wp_rest_plugins_controller/plugin_status_permission_check) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Handle updating a plugin’s status. |
| [WP\_REST\_Plugins\_Controller::handle\_plugin\_status()](../wp_rest_plugins_controller/handle_plugin_status) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Handle updating a plugin’s status. |
| [WP\_REST\_Plugins\_Controller::is\_filesystem\_available()](../wp_rest_plugins_controller/is_filesystem_available) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Determine if the endpoints are available. |
| [WP\_REST\_Plugins\_Controller::get\_item\_permissions\_check()](../wp_rest_plugins_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if a given request has access to get a specific plugin. |
| [WP\_REST\_Plugins\_Controller::check\_read\_permission()](../wp_rest_plugins_controller/check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if the given plugin can be viewed by the current user. |
| [WP\_REST\_Plugins\_Controller::create\_item\_permissions\_check()](../wp_rest_plugins_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if a given request has access to upload plugins. |
| [WP\_REST\_Plugins\_Controller::create\_item()](../wp_rest_plugins_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Uploads a plugin and optionally activates it. |
| [WP\_REST\_Plugins\_Controller::update\_item\_permissions\_check()](../wp_rest_plugins_controller/update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if a given request has access to update a specific plugin. |
| [WP\_REST\_Plugins\_Controller::delete\_item\_permissions\_check()](../wp_rest_plugins_controller/delete_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if a given request has access to delete a specific plugin. |
| [WP\_REST\_Plugins\_Controller::delete\_item()](../wp_rest_plugins_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Deletes one plugin from the site. |
| [WP\_REST\_Plugins\_Controller::get\_items\_permissions\_check()](../wp_rest_plugins_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-plugins-controller.php | Checks if a given request has access to get plugins. |
| [WP\_REST\_Block\_Types\_Controller::get\_block()](../wp_rest_block_types_controller/get_block) wp-includes/rest-api/endpoints/class-wp-rest-block-types-controller.php | Get the block, if the name is valid. |
| [WP\_REST\_Block\_Types\_Controller::check\_read\_permission()](../wp_rest_block_types_controller/check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-block-types-controller.php | Checks whether a given block type should be visible. |
| [WP\_REST\_Attachments\_Controller::edit\_media\_item\_permissions\_check()](../wp_rest_attachments_controller/edit_media_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Checks if a given request has access to editing media. |
| [WP\_REST\_Attachments\_Controller::edit\_media\_item()](../wp_rest_attachments_controller/edit_media_item) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Applies edits to a media item and creates a new attachment record. |
| [register\_theme\_feature()](../../functions/register_theme_feature) wp-includes/theme.php | Registers a theme feature for use in [add\_theme\_support()](../../functions/add_theme_support) . |
| [validate\_theme\_requirements()](../../functions/validate_theme_requirements) wp-includes/theme.php | Validates the theme requirements for WordPress version and PHP version. |
| [WP\_Image\_Editor\_Imagick::make\_subsize()](../wp_image_editor_imagick/make_subsize) wp-includes/class-wp-image-editor-imagick.php | Create an image sub-size and return the image meta data value for it. |
| [WP\_Image\_Editor\_Imagick::maybe\_exif\_rotate()](../wp_image_editor_imagick/maybe_exif_rotate) wp-includes/class-wp-image-editor-imagick.php | Check if a JPEG image has EXIF Orientation tag and rotate it if needed. |
| [WP\_Image\_Editor\_GD::make\_subsize()](../wp_image_editor_gd/make_subsize) wp-includes/class-wp-image-editor-gd.php | Create an image sub-size and return the image meta data value for it. |
| [wp\_update\_image\_subsizes()](../../functions/wp_update_image_subsizes) wp-admin/includes/image.php | If any of the currently registered image sub-sizes are missing, create them and update the image meta data. |
| [WP\_Recovery\_Mode::handle\_error()](../wp_recovery_mode/handle_error) wp-includes/class-wp-recovery-mode.php | Handles a fatal error occurring. |
| [WP\_Recovery\_Mode\_Key\_Service::validate\_recovery\_mode\_key()](../wp_recovery_mode_key_service/validate_recovery_mode_key) wp-includes/class-wp-recovery-mode-key-service.php | Verifies if the recovery mode key is correct. |
| [WP\_Recovery\_Mode\_Email\_Service::maybe\_send\_recovery\_mode\_email()](../wp_recovery_mode_email_service/maybe_send_recovery_mode_email) wp-includes/class-wp-recovery-mode-email-service.php | Sends the recovery mode email if the rate limit has not been sent. |
| [WP\_Recovery\_Mode\_Cookie\_Service::validate\_cookie()](../wp_recovery_mode_cookie_service/validate_cookie) wp-includes/class-wp-recovery-mode-cookie-service.php | Validates the recovery mode cookie. |
| [WP\_Recovery\_Mode\_Cookie\_Service::get\_session\_id\_from\_cookie()](../wp_recovery_mode_cookie_service/get_session_id_from_cookie) wp-includes/class-wp-recovery-mode-cookie-service.php | Gets the session identifier from the cookie. |
| [WP\_Recovery\_Mode\_Cookie\_Service::parse\_cookie()](../wp_recovery_mode_cookie_service/parse_cookie) wp-includes/class-wp-recovery-mode-cookie-service.php | Parses the cookie into its four parts. |
| [WP\_Fatal\_Error\_Handler::display\_default\_error\_template()](../wp_fatal_error_handler/display_default_error_template) wp-includes/class-wp-fatal-error-handler.php | Displays the default PHP error template. |
| [verify\_file\_signature()](../../functions/verify_file_signature) wp-admin/includes/file.php | Verifies the contents of a file against its ED25519 signature. |
| [resume\_theme()](../../functions/resume_theme) wp-admin/includes/theme.php | Tries to resume a single theme. |
| [WP\_Site\_Health::get\_cron\_tasks()](../wp_site_health/get_cron_tasks) wp-admin/includes/class-wp-site-health.php | Populates the list of cron events and store them to a class-wide variable. |
| [resume\_plugin()](../../functions/resume_plugin) wp-admin/includes/plugin.php | Tries to resume a single plugin. |
| [validate\_plugin\_requirements()](../../functions/validate_plugin_requirements) wp-admin/includes/plugin.php | Validates the plugin requirements for WordPress version and PHP version. |
| [wp\_initialize\_site()](../../functions/wp_initialize_site) wp-includes/ms-site.php | Runs the initialization routine for a given site. |
| [wp\_uninitialize\_site()](../../functions/wp_uninitialize_site) wp-includes/ms-site.php | Runs the uninitialization routine for a given site. |
| [wp\_prepare\_site\_data()](../../functions/wp_prepare_site_data) wp-includes/ms-site.php | Prepares site data for insertion or update in the database. |
| [wp\_insert\_site()](../../functions/wp_insert_site) wp-includes/ms-site.php | Inserts a new site into the database. |
| [wp\_update\_site()](../../functions/wp_update_site) wp-includes/ms-site.php | Updates a site in the database. |
| [wp\_delete\_site()](../../functions/wp_delete_site) wp-includes/ms-site.php | Deletes a site from the database. |
| [Language\_Pack\_Upgrader::clear\_destination()](../language_pack_upgrader/clear_destination) wp-admin/includes/class-language-pack-upgrader.php | Clears existing translations where this item is going to be installed into. |
| [WP\_REST\_Search\_Controller::get\_items()](../wp_rest_search_controller/get_items) wp-includes/rest-api/endpoints/class-wp-rest-search-controller.php | Retrieves a collection of search results. |
| [WP\_REST\_Search\_Controller::get\_search\_handler()](../wp_rest_search_controller/get_search_handler) wp-includes/rest-api/endpoints/class-wp-rest-search-controller.php | Gets the search handler to handle the current request. |
| [WP\_REST\_Themes\_Controller::get\_items\_permissions\_check()](../wp_rest_themes_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Checks if a given request has access to read the theme. |
| [WP\_REST\_Autosaves\_Controller::get\_items\_permissions\_check()](../wp_rest_autosaves_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Checks if a given request has access to get autosaves. |
| [WP\_REST\_Autosaves\_Controller::create\_item\_permissions\_check()](../wp_rest_autosaves_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Checks if a given request has access to create an autosave revision. |
| [WP\_REST\_Autosaves\_Controller::get\_item()](../wp_rest_autosaves_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Get the autosave, if the ID is valid. |
| [WP\_REST\_Autosaves\_Controller::create\_post\_autosave()](../wp_rest_autosaves_controller/create_post_autosave) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Creates autosave for the specified post. |
| [WP\_REST\_Block\_Renderer\_Controller::get\_item\_permissions\_check()](../wp_rest_block_renderer_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-block-renderer-controller.php | Checks if a given request has access to read blocks. |
| [WP\_REST\_Block\_Renderer\_Controller::get\_item()](../wp_rest_block_renderer_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-block-renderer-controller.php | Returns block output from block’s registered render\_callback. |
| [WP\_REST\_Attachments\_Controller::check\_upload\_size()](../wp_rest_attachments_controller/check_upload_size) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Determine if uploaded file exceeds space quota on multisite. |
| [wp\_validate\_user\_request\_key()](../../functions/wp_validate_user_request_key) wp-includes/user.php | Validates a user request by comparing the key with the request’s key. |
| [wp\_create\_user\_request()](../../functions/wp_create_user_request) wp-includes/user.php | Creates and logs a user request to perform a specific action. |
| [wp\_send\_user\_request()](../../functions/wp_send_user_request) wp-includes/user.php | Send a confirmation request email to confirm an action. |
| [wp\_privacy\_send\_personal\_data\_export\_email()](../../functions/wp_privacy_send_personal_data_export_email) wp-admin/includes/privacy-tools.php | Send an email to the user with a link to the personal data export file |
| [\_wp\_privacy\_resend\_request()](../../functions/_wp_privacy_resend_request) wp-admin/includes/privacy-tools.php | Resend an existing request and return the result. |
| [\_wp\_privacy\_completed\_request()](../../functions/_wp_privacy_completed_request) wp-admin/includes/privacy-tools.php | Marks a request as completed by the admin and logs the current timestamp. |
| [wp\_unschedule\_hook()](../../functions/wp_unschedule_hook) wp-includes/cron.php | Unschedules all events attached to the hook. |
| [WP\_REST\_Posts\_Controller::check\_template()](../wp_rest_posts_controller/check_template) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks whether the template is valid for the given post. |
| [wp\_edit\_theme\_plugin\_file()](../../functions/wp_edit_theme_plugin_file) wp-admin/includes/file.php | Attempts to edit a file for a theme or plugin. |
| [WP\_REST\_Users\_Controller::get\_user()](../wp_rest_users_controller/get_user) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Get the user, if the ID is valid. |
| [WP\_REST\_Revisions\_Controller::get\_revision()](../wp_rest_revisions_controller/get_revision) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Get the revision, if the ID is valid. |
| [WP\_REST\_Revisions\_Controller::get\_parent()](../wp_rest_revisions_controller/get_parent) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Get the parent post, if the ID is valid. |
| [WP\_REST\_Terms\_Controller::get\_term()](../wp_rest_terms_controller/get_term) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Get the term, if the ID is valid. |
| [WP\_REST\_Posts\_Controller::get\_post()](../wp_rest_posts_controller/get_post) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Gets the post, if the ID is valid. |
| [WP\_REST\_Comments\_Controller::get\_comment()](../wp_rest_comments_controller/get_comment) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Get the comment, if the ID is valid. |
| [WP\_oEmbed\_Controller::get\_proxy\_item\_permissions\_check()](../wp_oembed_controller/get_proxy_item_permissions_check) wp-includes/class-wp-oembed-controller.php | Checks if current user can make a proxy oEmbed request. |
| [WP\_oEmbed\_Controller::get\_proxy\_item()](../wp_oembed_controller/get_proxy_item) wp-includes/class-wp-oembed-controller.php | Callback for the proxy API endpoint. |
| [WP\_Community\_Events::get\_events()](../wp_community_events/get_events) wp-admin/includes/class-wp-community-events.php | Gets data about events near a particular location. |
| [rest\_sanitize\_value\_from\_schema()](../../functions/rest_sanitize_value_from_schema) wp-includes/rest-api.php | Sanitize a value based on a schema. |
| [rest\_validate\_value\_from\_schema()](../../functions/rest_validate_value_from_schema) wp-includes/rest-api.php | Validate a value based on a schema. |
| [WP\_Customize\_Manager::\_sanitize\_background\_setting()](../wp_customize_manager/_sanitize_background_setting) wp-includes/class-wp-customize-manager.php | Callback for validating a background setting value. |
| [WP\_Customize\_Manager::save\_changeset\_post()](../wp_customize_manager/save_changeset_post) wp-includes/class-wp-customize-manager.php | Saves the post for the loaded changeset. |
| [WP\_Customize\_Manager::get\_changeset\_post\_data()](../wp_customize_manager/get_changeset_post_data) wp-includes/class-wp-customize-manager.php | Gets the data stored in a changeset post. |
| [WP\_Image\_Editor\_Imagick::pdf\_setup()](../wp_image_editor_imagick/pdf_setup) wp-includes/class-wp-image-editor-imagick.php | Sets up Imagick for PDF processing. |
| [WP\_REST\_Meta\_Fields::delete\_meta\_value()](../wp_rest_meta_fields/delete_meta_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Deletes a meta value for an object. |
| [WP\_REST\_Meta\_Fields::update\_multi\_meta\_value()](../wp_rest_meta_fields/update_multi_meta_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates multiple meta values for an object. |
| [WP\_REST\_Meta\_Fields::update\_meta\_value()](../wp_rest_meta_fields/update_meta_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates a meta value for an object. |
| [WP\_REST\_Meta\_Fields::update\_value()](../wp_rest_meta_fields/update_value) wp-includes/rest-api/fields/class-wp-rest-meta-fields.php | Updates meta values. |
| [WP\_REST\_Users\_Controller::check\_username()](../wp_rest_users_controller/check_username) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Check a username for the REST API. |
| [WP\_REST\_Users\_Controller::check\_user\_password()](../wp_rest_users_controller/check_user_password) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Check a user password for the REST API. |
| [WP\_REST\_Users\_Controller::check\_role\_update()](../wp_rest_users_controller/check_role_update) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Determines if the current user is allowed to make the desired roles change. |
| [WP\_REST\_Users\_Controller::delete\_item\_permissions\_check()](../wp_rest_users_controller/delete_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Checks if a given request has access delete a user. |
| [WP\_REST\_Users\_Controller::delete\_item()](../wp_rest_users_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Deletes a single user. |
| [WP\_REST\_Users\_Controller::get\_current\_item()](../wp_rest_users_controller/get_current_item) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Retrieves the current user. |
| [WP\_REST\_Users\_Controller::create\_item\_permissions\_check()](../wp_rest_users_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Checks if a given request has access create users. |
| [WP\_REST\_Users\_Controller::create\_item()](../wp_rest_users_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Creates a single user. |
| [WP\_REST\_Users\_Controller::update\_item\_permissions\_check()](../wp_rest_users_controller/update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Checks if a given request has access to update a user. |
| [WP\_REST\_Users\_Controller::update\_item()](../wp_rest_users_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Updates a single user. |
| [WP\_REST\_Users\_Controller::check\_reassign()](../wp_rest_users_controller/check_reassign) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Checks for a valid value for the reassign parameter when deleting users. |
| [WP\_REST\_Users\_Controller::get\_items\_permissions\_check()](../wp_rest_users_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Permissions check for getting all users. |
| [WP\_REST\_Users\_Controller::get\_item\_permissions\_check()](../wp_rest_users_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php | Checks if a given request has access to read a user. |
| [WP\_REST\_Revisions\_Controller::delete\_item\_permissions\_check()](../wp_rest_revisions_controller/delete_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Checks if a given request has access to delete a revision. |
| [WP\_REST\_Revisions\_Controller::delete\_item()](../wp_rest_revisions_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Deletes a single revision. |
| [WP\_REST\_Attachments\_Controller::upload\_from\_file()](../wp_rest_attachments_controller/upload_from_file) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Handles an upload via multipart/form-data ($\_FILES). |
| [WP\_REST\_Revisions\_Controller::get\_items\_permissions\_check()](../wp_rest_revisions_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Checks if a given request has access to get revisions. |
| [WP\_REST\_Revisions\_Controller::get\_items()](../wp_rest_revisions_controller/get_items) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Gets a collection of revisions. |
| [WP\_REST\_Attachments\_Controller::upload\_from\_data()](../wp_rest_attachments_controller/upload_from_data) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Handles an upload via raw POST data. |
| [WP\_REST\_Attachments\_Controller::create\_item()](../wp_rest_attachments_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Creates a single attachment. |
| [WP\_REST\_Attachments\_Controller::update\_item()](../wp_rest_attachments_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Updates a single attachment. |
| [WP\_REST\_Attachments\_Controller::create\_item\_permissions\_check()](../wp_rest_attachments_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Checks if a given request has access to create an attachment. |
| [WP\_REST\_Post\_Statuses\_Controller::get\_item\_permissions\_check()](../wp_rest_post_statuses_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-post-statuses-controller.php | Checks if a given request has access to read a post status. |
| [WP\_REST\_Post\_Statuses\_Controller::get\_item()](../wp_rest_post_statuses_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-post-statuses-controller.php | Retrieves a specific post status. |
| [WP\_REST\_Post\_Statuses\_Controller::get\_items\_permissions\_check()](../wp_rest_post_statuses_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-post-statuses-controller.php | Checks whether a given request has permission to read post statuses. |
| [WP\_REST\_Settings\_Controller::update\_item()](../wp_rest_settings_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-settings-controller.php | Updates settings for the settings object. |
| [WP\_REST\_Terms\_Controller::delete\_item()](../wp_rest_terms_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Deletes a single term from a taxonomy. |
| [WP\_REST\_Terms\_Controller::create\_item\_permissions\_check()](../wp_rest_terms_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks if a request has access to create a term. |
| [WP\_REST\_Terms\_Controller::create\_item()](../wp_rest_terms_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Creates a single term in a taxonomy. |
| [WP\_REST\_Terms\_Controller::update\_item\_permissions\_check()](../wp_rest_terms_controller/update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks if a request has access to update the specified term. |
| [WP\_REST\_Terms\_Controller::update\_item()](../wp_rest_terms_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Updates a single term from a taxonomy. |
| [WP\_REST\_Terms\_Controller::delete\_item\_permissions\_check()](../wp_rest_terms_controller/delete_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks if a request has access to delete the specified term. |
| [WP\_REST\_Terms\_Controller::get\_items\_permissions\_check()](../wp_rest_terms_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks if a request has access to read terms in the specified taxonomy. |
| [WP\_REST\_Terms\_Controller::get\_item\_permissions\_check()](../wp_rest_terms_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php | Checks if a request has access to read or edit the specified term. |
| [WP\_REST\_Posts\_Controller::sanitize\_post\_statuses()](../wp_rest_posts_controller/sanitize_post_statuses) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Sanitizes and validates the list of post statuses, including whether the user can query private statuses. |
| [WP\_REST\_Posts\_Controller::handle\_status\_param()](../wp_rest_posts_controller/handle_status_param) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Determines validity and normalizes the given status parameter. |
| [WP\_REST\_Posts\_Controller::handle\_featured\_media()](../wp_rest_posts_controller/handle_featured_media) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Determines the featured media based on a request param. |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_database()](../wp_rest_posts_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post for create or update. |
| [WP\_REST\_Posts\_Controller::create\_item()](../wp_rest_posts_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Creates a single post. |
| [WP\_REST\_Posts\_Controller::update\_item\_permissions\_check()](../wp_rest_posts_controller/update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to update a post. |
| [WP\_REST\_Posts\_Controller::delete\_item\_permissions\_check()](../wp_rest_posts_controller/delete_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to delete a post. |
| [WP\_REST\_Posts\_Controller::delete\_item()](../wp_rest_posts_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Deletes a single post. |
| [WP\_REST\_Posts\_Controller::get\_item\_permissions\_check()](../wp_rest_posts_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to read a post. |
| [WP\_REST\_Posts\_Controller::create\_item\_permissions\_check()](../wp_rest_posts_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to create a post. |
| [WP\_REST\_Posts\_Controller::get\_items\_permissions\_check()](../wp_rest_posts_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to read posts. |
| [WP\_REST\_Posts\_Controller::get\_items()](../wp_rest_posts_controller/get_items) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves a collection of posts. |
| [WP\_REST\_Taxonomies\_Controller::get\_item\_permissions\_check()](../wp_rest_taxonomies_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Checks if a given request has access to a taxonomy. |
| [WP\_REST\_Taxonomies\_Controller::get\_item()](../wp_rest_taxonomies_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Retrieves a specific taxonomy. |
| [WP\_REST\_Taxonomies\_Controller::get\_items\_permissions\_check()](../wp_rest_taxonomies_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-taxonomies-controller.php | Checks whether a given request has permission to read taxonomies. |
| [WP\_REST\_Post\_Types\_Controller::get\_items\_permissions\_check()](../wp_rest_post_types_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php | Checks whether a given request has permission to read types. |
| [WP\_REST\_Post\_Types\_Controller::get\_item()](../wp_rest_post_types_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-post-types-controller.php | Retrieves a specific post type. |
| [WP\_REST\_Controller::delete\_item()](../wp_rest_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Deletes one item from the collection. |
| [WP\_REST\_Controller::prepare\_item\_for\_database()](../wp_rest_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Prepares one item for create or update operation. |
| [WP\_REST\_Controller::prepare\_item\_for\_response()](../wp_rest_controller/prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Prepares the item for the REST response. |
| [WP\_REST\_Controller::delete\_item\_permissions\_check()](../wp_rest_controller/delete_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Checks if a given request has access to delete a specific item. |
| [WP\_REST\_Controller::get\_item()](../wp_rest_controller/get_item) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves one item from the collection. |
| [WP\_REST\_Controller::create\_item\_permissions\_check()](../wp_rest_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Checks if a given request has access to create items. |
| [WP\_REST\_Controller::create\_item()](../wp_rest_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Creates one item from the collection. |
| [WP\_REST\_Controller::update\_item\_permissions\_check()](../wp_rest_controller/update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Checks if a given request has access to update a specific item. |
| [WP\_REST\_Controller::update\_item()](../wp_rest_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Updates one item from the collection. |
| [WP\_REST\_Controller::get\_items\_permissions\_check()](../wp_rest_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Checks if a given request has access to get items. |
| [WP\_REST\_Controller::get\_items()](../wp_rest_controller/get_items) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves a collection of items. |
| [WP\_REST\_Controller::get\_item\_permissions\_check()](../wp_rest_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Checks if a given request has access to get a specific item. |
| [WP\_REST\_Comments\_Controller::prepare\_item\_for\_database()](../wp_rest_comments_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Prepares a single comment to be inserted into the database. |
| [WP\_REST\_Comments\_Controller::update\_item\_permissions\_check()](../wp_rest_comments_controller/update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Checks if a given REST request has access to update a comment. |
| [WP\_REST\_Comments\_Controller::update\_item()](../wp_rest_comments_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Updates a comment. |
| [WP\_REST\_Comments\_Controller::delete\_item\_permissions\_check()](../wp_rest_comments_controller/delete_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Checks if a given request has access to delete a comment. |
| [WP\_REST\_Comments\_Controller::delete\_item()](../wp_rest_comments_controller/delete_item) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Deletes a comment. |
| [WP\_REST\_Comments\_Controller::get\_item\_permissions\_check()](../wp_rest_comments_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Checks if a given request has access to read the comment. |
| [WP\_REST\_Comments\_Controller::create\_item\_permissions\_check()](../wp_rest_comments_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Checks if a given request has access to create a comment. |
| [WP\_REST\_Comments\_Controller::create\_item()](../wp_rest_comments_controller/create_item) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Creates a comment. |
| [WP\_REST\_Comments\_Controller::get\_items\_permissions\_check()](../wp_rest_comments_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Checks if a given request has access to read comments. |
| [wp\_check\_comment\_data\_max\_lengths()](../../functions/wp_check_comment_data_max_lengths) wp-includes/comment.php | Compares the lengths of comment data against the maximum character limits. |
| [WP\_Customize\_Nav\_Menus::insert\_auto\_draft\_post()](../wp_customize_nav_menus/insert_auto_draft_post) wp-includes/class-wp-customize-nav-menus.php | Adds a new `auto-draft` post. |
| [WP\_Customize\_Custom\_CSS\_Setting::validate()](../wp_customize_custom_css_setting/validate) wp-includes/customize/class-wp-customize-custom-css-setting.php | Validate a received value for being valid CSS. |
| [WP\_Customize\_Manager::validate\_setting\_values()](../wp_customize_manager/validate_setting_values) wp-includes/class-wp-customize-manager.php | Validates setting values. |
| [WP\_Customize\_Setting::validate()](../wp_customize_setting/validate) wp-includes/class-wp-customize-setting.php | Validates an input. |
| [WP\_Ajax\_Upgrader\_Skin::\_\_construct()](../wp_ajax_upgrader_skin/__construct) wp-admin/includes/class-wp-ajax-upgrader-skin.php | Constructor. |
| [WP\_Metadata\_Lazyloader::reset\_queue()](../wp_metadata_lazyloader/reset_queue) wp-includes/class-wp-metadata-lazyloader.php | Resets lazy-load queue for a given object type. |
| [WP\_Metadata\_Lazyloader::queue\_objects()](../wp_metadata_lazyloader/queue_objects) wp-includes/class-wp-metadata-lazyloader.php | Adds objects to the metadata lazy-load queue. |
| [WP\_Image\_Editor\_Imagick::strip\_meta()](../wp_image_editor_imagick/strip_meta) wp-includes/class-wp-image-editor-imagick.php | Strips all image meta except color profiles from an image. |
| [WP\_Image\_Editor\_Imagick::thumbnail\_image()](../wp_image_editor_imagick/thumbnail_image) wp-includes/class-wp-image-editor-imagick.php | Efficiently resize the current image |
| [unregister\_taxonomy()](../../functions/unregister_taxonomy) wp-includes/taxonomy.php | Unregisters a taxonomy. |
| [wp\_authenticate\_email\_password()](../../functions/wp_authenticate_email_password) wp-includes/user.php | Authenticates a user using the email and password. |
| [unregister\_post\_type()](../../functions/unregister_post_type) wp-includes/post.php | Unregisters a post type. |
| [rest\_cookie\_check\_errors()](../../functions/rest_cookie_check_errors) wp-includes/rest-api.php | Checks for errors when using cookie-based authentication. |
| [add\_term\_meta()](../../functions/add_term_meta) wp-includes/taxonomy.php | Adds metadata to a term. |
| [update\_term\_meta()](../../functions/update_term_meta) wp-includes/taxonomy.php | Updates term metadata. |
| [WP\_REST\_Request::sanitize\_params()](../wp_rest_request/sanitize_params) wp-includes/rest-api/class-wp-rest-request.php | Sanitizes (where possible) the params on the request. |
| [WP\_REST\_Request::has\_valid\_params()](../wp_rest_request/has_valid_params) wp-includes/rest-api/class-wp-rest-request.php | Checks whether this request is valid according to its attributes. |
| [WP\_REST\_Request::parse\_json\_params()](../wp_rest_request/parse_json_params) wp-includes/rest-api/class-wp-rest-request.php | Parses the JSON parameters. |
| [WP\_REST\_Response::as\_error()](../wp_rest_response/as_error) wp-includes/rest-api/class-wp-rest-response.php | Retrieves a [WP\_Error](../wp_error) object from the response. |
| [WP\_REST\_Server::dispatch()](../wp_rest_server/dispatch) wp-includes/rest-api/class-wp-rest-server.php | Matches the request to a callback and call it. |
| [WP\_REST\_Server::get\_namespace\_index()](../wp_rest_server/get_namespace_index) wp-includes/rest-api/class-wp-rest-server.php | Retrieves the index for a namespace. |
| [WP\_REST\_Server::serve\_request()](../wp_rest_server/serve_request) wp-includes/rest-api/class-wp-rest-server.php | Handles serving a REST API request. |
| [WP\_oEmbed\_Controller::get\_item()](../wp_oembed_controller/get_item) wp-includes/class-wp-oembed-controller.php | Callback for the embed API endpoint. |
| [get\_password\_reset\_key()](../../functions/get_password_reset_key) wp-includes/user.php | Creates, stores, then returns a password reset key for user. |
| [WP\_Term::get\_instance()](../wp_term/get_instance) wp-includes/class-wp-term.php | Retrieve [WP\_Term](../wp_term) instance. |
| [wp\_handle\_comment\_submission()](../../functions/wp_handle_comment_submission) wp-includes/comment.php | Handles the submission of a comment, usually posted to wp-comments-post.php via a comment form. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::sanitize()](../wp_customize_nav_menu_item_setting/sanitize) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Sanitize an input. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::update()](../wp_customize_nav_menu_item_setting/update) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Creates/updates the nav\_menu\_item post for this setting. |
| [WP\_Customize\_Nav\_Menus::load\_available\_items\_query()](../wp_customize_nav_menus/load_available_items_query) wp-includes/class-wp-customize-nav-menus.php | Performs the post\_type and taxonomy queries for loading available menu items. |
| [WP\_Upgrader::clear\_destination()](../wp_upgrader/clear_destination) wp-admin/includes/class-wp-upgrader.php | Clears the directory where this item is going to be installed into. |
| [wpdb::get\_table\_charset()](../wpdb/get_table_charset) wp-includes/class-wpdb.php | Retrieves the character set for the given table. |
| [wpdb::strip\_invalid\_text()](../wpdb/strip_invalid_text) wp-includes/class-wpdb.php | Strips any invalid characters based on value/charset pairs. |
| [translations\_api()](../../functions/translations_api) wp-admin/includes/translation-install.php | Retrieve translations from WordPress Translation API. |
| [retrieve\_password()](../../functions/retrieve_password) wp-includes/user.php | Handles sending a password retrieval email to a user. |
| [login\_header()](../../functions/login_header) wp-login.php | Output the login page header. |
| [show\_user\_form()](../../functions/show_user_form) wp-signup.php | Displays the fields for the new user account registration form. |
| [signup\_another\_blog()](../../functions/signup_another_blog) wp-signup.php | Shows a form for returning users to sign up for another site. |
| [signup\_user()](../../functions/signup_user) wp-signup.php | Shows a form for a visitor to sign up for a new user account. |
| [signup\_blog()](../../functions/signup_blog) wp-signup.php | Shows a form for a user or visitor to sign up for a new site. |
| [show\_blog\_form()](../../functions/show_blog_form) wp-signup.php | Generates and displays the Sign-up and Create Site forms. |
| [WP\_Automatic\_Updater::update()](../wp_automatic_updater/update) wp-admin/includes/class-wp-automatic-updater.php | Updates an item, if appropriate. |
| [Core\_Upgrader::upgrade()](../core_upgrader/upgrade) wp-admin/includes/class-core-upgrader.php | Upgrade WordPress core. |
| [Language\_Pack\_Upgrader::bulk\_upgrade()](../language_pack_upgrader/bulk_upgrade) wp-admin/includes/class-language-pack-upgrader.php | Bulk upgrade language packs. |
| [Language\_Pack\_Upgrader::check\_package()](../language_pack_upgrader/check_package) wp-admin/includes/class-language-pack-upgrader.php | Checks that the package source contains .mo and .po files. |
| [Plugin\_Upgrader::check\_package()](../plugin_upgrader/check_package) wp-admin/includes/class-plugin-upgrader.php | Checks that the source package contains a valid plugin. |
| [Plugin\_Upgrader::deactivate\_plugin\_before\_upgrade()](../plugin_upgrader/deactivate_plugin_before_upgrade) wp-admin/includes/class-plugin-upgrader.php | Deactivates a plugin before it is upgraded. |
| [Plugin\_Upgrader::delete\_old\_plugin()](../plugin_upgrader/delete_old_plugin) wp-admin/includes/class-plugin-upgrader.php | Deletes the old plugin during an upgrade. |
| [Theme\_Upgrader::check\_package()](../theme_upgrader/check_package) wp-admin/includes/class-theme-upgrader.php | Checks that the package source contains a valid theme. |
| [WP\_Upgrader::fs\_connect()](../wp_upgrader/fs_connect) wp-admin/includes/class-wp-upgrader.php | Connect to the filesystem. |
| [WP\_Upgrader::download\_package()](../wp_upgrader/download_package) wp-admin/includes/class-wp-upgrader.php | Download a package. |
| [WP\_Upgrader::unpack\_package()](../wp_upgrader/unpack_package) wp-admin/includes/class-wp-upgrader.php | Unpack a compressed package file. |
| [WP\_Upgrader::install\_package()](../wp_upgrader/install_package) wp-admin/includes/class-wp-upgrader.php | Install a package. |
| [WP\_Filesystem\_SSH2::\_\_construct()](../wp_filesystem_ssh2/__construct) wp-admin/includes/class-wp-filesystem-ssh2.php | Constructor. |
| [delete\_theme()](../../functions/delete_theme) wp-admin/includes/theme.php | Removes a theme. |
| [themes\_api()](../../functions/themes_api) wp-admin/includes/theme.php | Retrieves theme installer pages from the WordPress.org Themes API. |
| [WP\_User\_Search::query()](../wp_user_search/query) wp-admin/includes/deprecated.php | Executes the user search query. |
| [send\_confirmation\_on\_profile\_email()](../../functions/send_confirmation_on_profile_email) wp-includes/user.php | Sends a confirmation request email when a change of user email address is attempted. |
| [WP\_Filesystem\_FTPext::\_\_construct()](../wp_filesystem_ftpext/__construct) wp-admin/includes/class-wp-filesystem-ftpext.php | Constructor. |
| [WP\_Filesystem\_Direct::\_\_construct()](../wp_filesystem_direct/__construct) wp-admin/includes/class-wp-filesystem-direct.php | Constructor. |
| [populate\_network()](../../functions/populate_network) wp-admin/includes/schema.php | Populate network settings. |
| [wp\_insert\_category()](../../functions/wp_insert_category) wp-admin/includes/taxonomy.php | Updates an existing Category or creates a new Category. |
| [plugins\_api()](../../functions/plugins_api) wp-admin/includes/plugin-install.php | Retrieves plugin installer pages from the WordPress.org Plugins API. |
| [validate\_plugin()](../../functions/validate_plugin) wp-admin/includes/plugin.php | Validates the plugin path. |
| [activate\_plugins()](../../functions/activate_plugins) wp-admin/includes/plugin.php | Activates multiple plugins. |
| [delete\_plugins()](../../functions/delete_plugins) wp-admin/includes/plugin.php | Removes directory and files of a plugin for a list of plugins. |
| [activate\_plugin()](../../functions/activate_plugin) wp-admin/includes/plugin.php | Attempts activation of plugin in a “sandbox” and redirects on success. |
| [edit\_user()](../../functions/edit_user) wp-admin/includes/user.php | Edit user settings based on contents of $\_POST |
| [media\_sideload\_image()](../../functions/media_sideload_image) wp-admin/includes/media.php | Downloads an image from the specified URL, saves it as an attachment, and optionally attaches it to a post. |
| [media\_handle\_upload()](../../functions/media_handle_upload) wp-admin/includes/media.php | Saves a file submitted from a POST request and create an attachment post for it. |
| [media\_handle\_sideload()](../../functions/media_handle_sideload) wp-admin/includes/media.php | Handles a side-loaded file in the same way as an uploaded file is handled by [media\_handle\_upload()](../../functions/media_handle_upload) . |
| [wp\_autosave()](../../functions/wp_autosave) wp-admin/includes/post.php | Saves a post submitted with XHR. |
| [wp\_write\_post()](../../functions/wp_write_post) wp-admin/includes/post.php | Creates a new post from the “Write Post” form using `$_POST` information. |
| [\_wp\_translate\_postdata()](../../functions/_wp_translate_postdata) wp-admin/includes/post.php | Renames `$_POST` data from form names to DB post columns. |
| [wp\_ajax\_dim\_comment()](../../functions/wp_ajax_dim_comment) wp-admin/includes/ajax-actions.php | Ajax handler to dim a comment. |
| [wp\_ajax\_add\_tag()](../../functions/wp_ajax_add_tag) wp-admin/includes/ajax-actions.php | Ajax handler to add a tag. |
| [update\_core()](../../functions/update_core) wp-admin/includes/update-core.php | Upgrades the core of WordPress. |
| [wp\_insert\_link()](../../functions/wp_insert_link) wp-admin/includes/bookmark.php | Inserts a link into the database, or updates an existing link. |
| [wp\_get\_nav\_menu\_to\_edit()](../../functions/wp_get_nav_menu_to_edit) wp-admin/includes/nav-menu.php | Returns the menu formatted to edit. |
| [WP\_Filesystem\_ftpsockets::\_\_construct()](../wp_filesystem_ftpsockets/__construct) wp-admin/includes/class-wp-filesystem-ftpsockets.php | Constructor. |
| [download\_url()](../../functions/download_url) wp-admin/includes/file.php | Downloads a URL to a local temporary file using the WordPress HTTP API. |
| [verify\_file\_md5()](../../functions/verify_file_md5) wp-admin/includes/file.php | Calculates and compares the MD5 of a file to its expected value. |
| [unzip\_file()](../../functions/unzip_file) wp-admin/includes/file.php | Unzips a specified ZIP file to a location on the filesystem via the WordPress Filesystem Abstraction. |
| [\_unzip\_file\_ziparchive()](../../functions/_unzip_file_ziparchive) wp-admin/includes/file.php | Attempts to unzip an archive using the ZipArchive class. |
| [\_unzip\_file\_pclzip()](../../functions/_unzip_file_pclzip) wp-admin/includes/file.php | Attempts to unzip an archive using the PclZip library. |
| [copy\_dir()](../../functions/copy_dir) wp-admin/includes/file.php | Copies a directory from one location to another via the WordPress Filesystem Abstraction. |
| [WP\_Customize\_Manager::save()](../wp_customize_manager/save) wp-includes/class-wp-customize-manager.php | Handles customize\_save WP Ajax request to save/update a changeset. |
| [wp\_schedule\_event()](../../functions/wp_schedule_event) wp-includes/cron.php | Schedules a recurring event. |
| [wp\_reschedule\_event()](../../functions/wp_reschedule_event) wp-includes/cron.php | Reschedules a recurring event. |
| [wp\_unschedule\_event()](../../functions/wp_unschedule_event) wp-includes/cron.php | Unschedule a previously scheduled event. |
| [wp\_clear\_scheduled\_hook()](../../functions/wp_clear_scheduled_hook) wp-includes/cron.php | Unschedules all events attached to the hook with the specified arguments. |
| [\_set\_cron\_array()](../../functions/_set_cron_array) wp-includes/cron.php | Updates the cron option with the new cron array. |
| [wp\_schedule\_single\_event()](../../functions/wp_schedule_single_event) wp-includes/cron.php | Schedules an event to run only once. |
| [wp\_authenticate()](../../functions/wp_authenticate) wp-includes/pluggable.php | Authenticates a user, confirming the login credentials are valid. |
| [wp\_mail()](../../functions/wp_mail) wp-includes/pluggable.php | Sends an email, similar to PHP’s mail function. |
| [WP\_Theme::\_\_construct()](../wp_theme/__construct) wp-includes/class-wp-theme.php | Constructor for [WP\_Theme](../wp_theme). |
| [WP\_Image\_Editor\_Imagick::update\_size()](../wp_image_editor_imagick/update_size) wp-includes/class-wp-image-editor-imagick.php | Sets or updates current image size. |
| [WP\_Image\_Editor\_Imagick::resize()](../wp_image_editor_imagick/resize) wp-includes/class-wp-image-editor-imagick.php | Resizes current image. |
| [WP\_Image\_Editor\_Imagick::crop()](../wp_image_editor_imagick/crop) wp-includes/class-wp-image-editor-imagick.php | Crops Image. |
| [WP\_Image\_Editor\_Imagick::rotate()](../wp_image_editor_imagick/rotate) wp-includes/class-wp-image-editor-imagick.php | Rotates current image counter-clockwise by $angle. |
| [WP\_Image\_Editor\_Imagick::flip()](../wp_image_editor_imagick/flip) wp-includes/class-wp-image-editor-imagick.php | Flips current image. |
| [WP\_Image\_Editor\_Imagick::save()](../wp_image_editor_imagick/save) wp-includes/class-wp-image-editor-imagick.php | Saves current image to file. |
| [WP\_Image\_Editor\_Imagick::\_save()](../wp_image_editor_imagick/_save) wp-includes/class-wp-image-editor-imagick.php | |
| [WP\_Image\_Editor\_Imagick::stream()](../wp_image_editor_imagick/stream) wp-includes/class-wp-image-editor-imagick.php | Streams current image to browser. |
| [WP\_Image\_Editor\_Imagick::load()](../wp_image_editor_imagick/load) wp-includes/class-wp-image-editor-imagick.php | Loads image from $this->file into new Imagick Object. |
| [WP\_Image\_Editor\_Imagick::set\_quality()](../wp_image_editor_imagick/set_quality) wp-includes/class-wp-image-editor-imagick.php | Sets Image Compression quality on a 1-100% scale. |
| [WP\_Http::handle\_redirects()](../wp_http/handle_redirects) wp-includes/class-wp-http.php | Handles an HTTP redirect and follows it if appropriate. |
| [WP\_Http\_Streams::request()](../wp_http_streams/request) wp-includes/class-wp-http-streams.php | Send a HTTP request to a URI using PHP Streams. |
| [WP\_Http\_Curl::request()](../wp_http_curl/request) wp-includes/class-wp-http-curl.php | Send a HTTP request to a URI using cURL extension. |
| [WP\_Http::\_dispatch\_request()](../wp_http/_dispatch_request) wp-includes/class-wp-http.php | Dispatches a HTTP request to a supporting transport. |
| [WP\_Http::request()](../wp_http/request) wp-includes/class-wp-http.php | Send an HTTP request to a URI. |
| [WP\_Tax\_Query::clean\_query()](../wp_tax_query/clean_query) wp-includes/class-wp-tax-query.php | Validates a single query. |
| [WP\_Tax\_Query::transform\_query()](../wp_tax_query/transform_query) wp-includes/class-wp-tax-query.php | Transforms a single query, from one field to another. |
| [get\_term\_link()](../../functions/get_term_link) wp-includes/taxonomy.php | Generates a permalink for a taxonomy term archive. |
| [is\_object\_in\_term()](../../functions/is_object_in_term) wp-includes/taxonomy.php | Determines if the given object is associated with any of the given terms. |
| [wp\_update\_term()](../../functions/wp_update_term) wp-includes/taxonomy.php | Updates term based on arguments provided. |
| [wp\_get\_object\_terms()](../../functions/wp_get_object_terms) wp-includes/taxonomy.php | Retrieves the terms associated with the given object(s), in the supplied taxonomies. |
| [wp\_set\_object\_terms()](../../functions/wp_set_object_terms) wp-includes/taxonomy.php | Creates term and taxonomy relationships. |
| [wp\_insert\_term()](../../functions/wp_insert_term) wp-includes/taxonomy.php | Adds a new term to the database. |
| [wp\_remove\_object\_terms()](../../functions/wp_remove_object_terms) wp-includes/taxonomy.php | Removes term(s) associated with a given object. |
| [get\_term\_children()](../../functions/get_term_children) wp-includes/taxonomy.php | Merges all term children into a single array of their IDs. |
| [get\_terms()](../../functions/get_terms) wp-includes/taxonomy.php | Retrieves the terms in a given taxonomy or list of taxonomies. |
| [register\_taxonomy()](../../functions/register_taxonomy) wp-includes/taxonomy.php | Creates or modifies a taxonomy object. |
| [get\_objects\_in\_term()](../../functions/get_objects_in_term) wp-includes/taxonomy.php | Retrieves object IDs of valid taxonomy and term. |
| [get\_term()](../../functions/get_term) wp-includes/taxonomy.php | Gets all term data from database by term ID. |
| [WP\_Image\_Editor::set\_quality()](../wp_image_editor/set_quality) wp-includes/class-wp-image-editor.php | Sets Image Compression quality on a 1-100% scale. |
| [WP\_oEmbed::\_fetch\_with\_format()](../wp_oembed/_fetch_with_format) wp-includes/class-wp-oembed.php | Fetches result from an oEmbed provider for a specific format and complete provider URL |
| [fetch\_feed()](../../functions/fetch_feed) wp-includes/feed.php | Builds SimplePie object based on RSS or Atom feed from URL. |
| [wp\_update\_user()](../../functions/wp_update_user) wp-includes/user.php | Updates a user in the database. |
| [check\_password\_reset\_key()](../../functions/check_password_reset_key) wp-includes/user.php | Retrieves a user row based on password reset key and login. |
| [register\_new\_user()](../../functions/register_new_user) wp-includes/user.php | Handles registering a new user. |
| [wp\_insert\_user()](../../functions/wp_insert_user) wp-includes/user.php | Inserts a user into the database. |
| [wp\_authenticate\_username\_password()](../../functions/wp_authenticate_username_password) wp-includes/user.php | Authenticates a user, confirming the username and password are valid. |
| [wp\_authenticate\_cookie()](../../functions/wp_authenticate_cookie) wp-includes/user.php | Authenticates the user using the WordPress auth cookie. |
| [wp\_authenticate\_spam\_check()](../../functions/wp_authenticate_spam_check) wp-includes/user.php | For Multisite blogs, checks if the authenticated user has been marked as a spammer, or if the user’s primary blog has been marked as spam. |
| [WP\_Image\_Editor\_GD::load()](../wp_image_editor_gd/load) wp-includes/class-wp-image-editor-gd.php | Loads image from $this->file into new GD Resource. |
| [WP\_Image\_Editor\_GD::resize()](../wp_image_editor_gd/resize) wp-includes/class-wp-image-editor-gd.php | Resizes current image. |
| [WP\_Image\_Editor\_GD::\_resize()](../wp_image_editor_gd/_resize) wp-includes/class-wp-image-editor-gd.php | |
| [WP\_Image\_Editor\_GD::crop()](../wp_image_editor_gd/crop) wp-includes/class-wp-image-editor-gd.php | Crops Image. |
| [WP\_Image\_Editor\_GD::rotate()](../wp_image_editor_gd/rotate) wp-includes/class-wp-image-editor-gd.php | Rotates current image counter-clockwise by $angle. |
| [WP\_Image\_Editor\_GD::flip()](../wp_image_editor_gd/flip) wp-includes/class-wp-image-editor-gd.php | Flips current image. |
| [WP\_Image\_Editor\_GD::\_save()](../wp_image_editor_gd/_save) wp-includes/class-wp-image-editor-gd.php | |
| [wp\_get\_image\_editor()](../../functions/wp_get_image_editor) wp-includes/media.php | Returns a [WP\_Image\_Editor](../wp_image_editor) instance and loads file into it. |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [wp\_update\_post()](../../functions/wp_update_post) wp-includes/post.php | Updates a post with new post data. |
| [register\_post\_type()](../../functions/register_post_type) wp-includes/post.php | Registers a post type. |
| [\_wp\_put\_post\_revision()](../../functions/_wp_put_post_revision) wp-includes/revision.php | Inserts post data into the posts table as a post revision. |
| [wpmu\_activate\_signup()](../../functions/wpmu_activate_signup) wp-includes/ms-functions.php | Activates a signup. |
| [wpmu\_create\_blog()](../../functions/wpmu_create_blog) wp-includes/ms-functions.php | Creates a site. |
| [wpmu\_validate\_user\_signup()](../../functions/wpmu_validate_user_signup) wp-includes/ms-functions.php | Sanitizes and validates data required for a user sign-up. |
| [wpmu\_validate\_blog\_signup()](../../functions/wpmu_validate_blog_signup) wp-includes/ms-functions.php | Processes new site registrations. |
| [add\_user\_to\_blog()](../../functions/add_user_to_blog) wp-includes/ms-functions.php | Adds a user to a blog, along with specifying the user’s role. |
| [remove\_user\_from\_blog()](../../functions/remove_user_from_blog) wp-includes/ms-functions.php | Removes a user from a blog. |
| [set\_post\_format()](../../functions/set_post_format) wp-includes/post-formats.php | Assign a format to a post |
| [wp\_update\_nav\_menu\_object()](../../functions/wp_update_nav_menu_object) wp-includes/nav-menu.php | Saves the properties of a menu or create a new menu with those properties. |
| [wp\_update\_nav\_menu\_item()](../../functions/wp_update_nav_menu_item) wp-includes/nav-menu.php | Saves the properties of a menu item or create a new one. |
| [wp\_xmlrpc\_server::login()](../wp_xmlrpc_server/login) wp-includes/class-wp-xmlrpc-server.php | Log user in. |
| [wpdb::bail()](../wpdb/bail) wp-includes/class-wpdb.php | Wraps errors in a nice header and footer and dies. |
| [wpdb::check\_database\_version()](../wpdb/check_database_version) wp-includes/class-wpdb.php | Determines whether MySQL database is at least the required minimum version. |
| [wpdb::set\_prefix()](../wpdb/set_prefix) wp-includes/class-wpdb.php | Sets the table prefix for the WordPress tables. |
| [WP\_Customize\_Widgets::call\_widget\_update()](../wp_customize_widgets/call_widget_update) wp-includes/class-wp-customize-widgets.php | Finds and invokes the widget update and control callbacks. |
| [WP\_Customize\_Widgets::parse\_widget\_setting\_id()](../wp_customize_widgets/parse_widget_setting_id) wp-includes/class-wp-customize-widgets.php | Converts a widget setting ID (option path) to its id\_base and number components. |
| [wp\_set\_comment\_status()](../../functions/wp_set_comment_status) wp-includes/comment.php | Sets the status of a comment. |
| [wp\_update\_comment()](../../functions/wp_update_comment) wp-includes/comment.php | Updates an existing comment in the database. |
| [wp\_allow\_comment()](../../functions/wp_allow_comment) wp-includes/comment.php | Validates whether this comment is allowed to be made. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
| programming_docs |
wordpress WP_Error::get_error_data( string|int $code = '' ): mixed WP\_Error::get\_error\_data( string|int $code = '' ): mixed
===========================================================
Retrieves the most recently added error data for an error code.
`$code` string|int Optional Error code. Default: `''`
mixed Error data, if it exists.
File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/)
```
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 ];
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Error::get\_error\_code()](get_error_code) wp-includes/class-wp-error.php | Retrieves the first error code available. |
| Used By | Description |
| --- | --- |
| [login\_header()](../../functions/login_header) wp-login.php | Output the login page header. |
| Version | Description |
| --- | --- |
| [2.1.0](https://developer.wordpress.org/reference/since/2.1.0/) | Introduced. |
wordpress WP_Error::has_errors(): bool WP\_Error::has\_errors(): bool
==============================
Verifies if the instance contains errors.
bool If the instance contains errors.
File: `wp-includes/class-wp-error.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-error.php/)
```
public function has_errors() {
if ( ! empty( $this->errors ) ) {
return true;
}
return false;
}
```
| Used By | Description |
| --- | --- |
| [login\_header()](../../functions/login_header) wp-login.php | Output the login page header. |
| [WP\_Error::get\_error\_codes()](get_error_codes) wp-includes/class-wp-error.php | Retrieves all error codes. |
| Version | Description |
| --- | --- |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | Introduced. |
wordpress WP_Site_Query::parse_order( string $order ): string WP\_Site\_Query::parse\_order( string $order ): string
======================================================
Parses an ‘order’ query variable and cast it to ‘ASC’ or ‘DESC’ as necessary.
`$order` string Required The `'order'` query variable. string The sanitized `'order'` query variable.
File: `wp-includes/class-wp-site-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site-query.php/)
```
protected function parse_order( $order ) {
if ( ! is_string( $order ) || empty( $order ) ) {
return 'ASC';
}
if ( 'ASC' === strtoupper( $order ) ) {
return 'ASC';
} else {
return 'DESC';
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Site\_Query::get\_site\_ids()](get_site_ids) wp-includes/class-wp-site-query.php | Used internally to get a list of site IDs matching the query vars. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Site_Query::set_found_sites() WP\_Site\_Query::set\_found\_sites()
====================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Populates 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/)
```
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 );
}
}
```
[apply\_filters( 'found\_sites\_query', string $found\_sites\_query, WP\_Site\_Query $site\_query )](../../hooks/found_sites_query)
Filters the query used to retrieve found site count.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [wpdb::get\_var()](../wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Query::get\_sites()](get_sites) wp-includes/class-wp-site-query.php | Retrieves a list of sites matching the query vars. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Site_Query::parse_orderby( string $orderby ): string|false WP\_Site\_Query::parse\_orderby( string $orderby ): string|false
================================================================
Parses and sanitizes ‘orderby’ keys passed to the site query.
`$orderby` string Required Alias for the field to order by. string|false Value to used in the ORDER clause. False otherwise.
File: `wp-includes/class-wp-site-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site-query.php/)
```
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;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Site\_Query::get\_site\_ids()](get_site_ids) wp-includes/class-wp-site-query.php | Used internally to get a list of site IDs matching the query vars. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Site_Query::query( string|array $query ): array|int WP\_Site\_Query::query( string|array $query ): array|int
========================================================
Sets up the WordPress query for retrieving sites.
`$query` string|array Required Array or URL query string of parameters. array|int List of [WP\_Site](../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.
File: `wp-includes/class-wp-site-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site-query.php/)
```
public function query( $query ) {
$this->query_vars = wp_parse_args( $query );
return $this->get_sites();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Query::get\_sites()](get_sites) wp-includes/class-wp-site-query.php | Retrieves a list of sites matching the query vars. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Query::\_\_construct()](__construct) wp-includes/class-wp-site-query.php | Sets up the site query, based on the query vars passed. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Site_Query::parse_query( string|array $query = '' ) WP\_Site\_Query::parse\_query( string|array $query = '' )
=========================================================
Parses arguments passed to the site query with default query parameters.
* [WP\_Site\_Query::\_\_construct()](../wp_site_query/__construct)
`$query` string|array Optional Array or string of [WP\_Site\_Query](../wp_site_query) arguments. See [WP\_Site\_Query::\_\_construct()](__construct). More Arguments from WP\_Site\_Query::\_\_construct( ... $query ) Array or query string of site query parameters.
* `site__in`int[]Array of site IDs to include.
* `site__not_in`int[]Array of site IDs to exclude.
* `count`boolWhether to return a site count (true) or array of site objects.
Default false.
* `date_query`arrayDate query clauses to limit sites by. See [WP\_Date\_Query](../wp_date_query).
Default null.
* `fields`stringSite fields to return. Accepts `'ids'` (returns an array of site IDs) or empty (returns an array of complete site objects).
* `ID`intA site ID to only return that site.
* `number`intMaximum number of sites to retrieve. Default 100.
* `offset`intNumber of sites to offset the query. Used to build LIMIT clause.
Default 0.
* `no_found_rows`boolWhether to disable the `SQL_CALC_FOUND_ROWS` query. Default true.
* `orderby`string|arraySite 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'`.
* `order`stringHow to order retrieved sites. Accepts `'ASC'`, `'DESC'`. Default `'ASC'`.
* `network_id`intLimit results to those affiliated with a given network ID. If 0, include all networks. Default 0.
* `network__in`int[]Array of network IDs to include affiliated sites for.
* `network__not_in`int[]Array of network IDs to exclude affiliated sites for.
* `domain`stringLimit results to those affiliated with a given domain.
* `domain__in`string[]Array of domains to include affiliated sites for.
* `domain__not_in`string[]Array of domains to exclude affiliated sites for.
* `path`stringLimit results to those affiliated with a given path.
* `path__in`string[]Array of paths to include affiliated sites for.
* `path__not_in`string[]Array of paths to exclude affiliated sites for.
* `public`intLimit results to public sites. Accepts `'1'` or `'0'`.
* `archived`intLimit results to archived sites. Accepts `'1'` or `'0'`.
* `mature`intLimit results to mature sites. Accepts `'1'` or `'0'`.
* `spam`intLimit results to spam sites. Accepts `'1'` or `'0'`.
* `deleted`intLimit results to deleted sites. Accepts `'1'` or `'0'`.
* `lang_id`intLimit results to a language ID.
* `lang__in`string[]Array of language IDs to include affiliated sites for.
* `lang__not_in`string[]Array of language IDs to exclude affiliated sites for.
* `search`stringSearch term(s) to retrieve matching sites for.
* `search_columns`string[]Array of column names to be searched. Accepts `'domain'` and `'path'`.
Default empty array.
* `update_site_cache`boolWhether to prime the cache for found sites. Default true.
* `update_site_meta_cache`boolWhether to prime the metadata cache for found sites. Default true.
* `meta_key`string|string[]Meta key or keys to filter by.
* `meta_value`string|string[]Meta value or values to filter by.
* `meta_compare`stringMySQL operator used for comparing the meta value.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_compare_key`stringMySQL operator used for comparing the meta key.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_type`stringMySQL data type that the meta\_value column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_type_key`stringMySQL data type that the meta\_key column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_query`arrayAn associative array of [WP\_Meta\_Query](../wp_meta_query) arguments.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values.
Default: `''`
File: `wp-includes/class-wp-site-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site-query.php/)
```
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 ) );
}
```
[do\_action\_ref\_array( 'parse\_site\_query', WP\_Site\_Query $query )](../../hooks/parse_site_query)
Fires after the site query vars have been parsed.
| Uses | Description |
| --- | --- |
| [do\_action\_ref\_array()](../../functions/do_action_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook, specifying arguments in an array. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Query::get\_sites()](get_sites) wp-includes/class-wp-site-query.php | Retrieves a list of sites matching the query vars. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Site_Query::get_search_sql( string $search, string[] $columns ): string WP\_Site\_Query::get\_search\_sql( string $search, string[] $columns ): string
==============================================================================
Used internally to generate an SQL string for searching across multiple columns.
`$search` string Required Search string. `$columns` string[] Required Array of columns to search. string Search SQL.
File: `wp-includes/class-wp-site-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site-query.php/)
```
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 ) . ')';
}
```
| Uses | Description |
| --- | --- |
| [wpdb::esc\_like()](../wpdb/esc_like) wp-includes/class-wpdb.php | First half of escaping for `LIKE` special characters `%` and `_` before preparing for SQL. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Query::get\_site\_ids()](get_site_ids) wp-includes/class-wp-site-query.php | Used internally to get a list of site IDs matching the query vars. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Site_Query::get_site_ids(): int|array WP\_Site\_Query::get\_site\_ids(): int|array
============================================
Used internally to get a list of site IDs matching the query vars.
int|array A single count of site IDs if a count query. An array of site IDs if a full query.
File: `wp-includes/class-wp-site-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site-query.php/)
```
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 );
}
```
[apply\_filters\_ref\_array( 'sites\_clauses', string[] $clauses, WP\_Site\_Query $query )](../../hooks/sites_clauses)
Filters the site query clauses.
[apply\_filters( 'site\_search\_columns', string[] $search\_columns, string $search, WP\_Site\_Query $query )](../../hooks/site_search_columns)
Filters the columns to search in a [WP\_Site\_Query](../wp_site_query) search.
| Uses | Description |
| --- | --- |
| [WP\_Site\_Query::parse\_order()](parse_order) wp-includes/class-wp-site-query.php | Parses an ‘order’ query variable and cast it to ‘ASC’ or ‘DESC’ as necessary. |
| [WP\_Site\_Query::parse\_orderby()](parse_orderby) wp-includes/class-wp-site-query.php | Parses and sanitizes ‘orderby’ keys passed to the site query. |
| [WP\_Site\_Query::get\_search\_sql()](get_search_sql) wp-includes/class-wp-site-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| [wp\_parse\_id\_list()](../../functions/wp_parse_id_list) wp-includes/functions.php | Cleans up an array, comma- or space-separated list of IDs. |
| [WP\_Date\_Query::\_\_construct()](../wp_date_query/__construct) wp-includes/class-wp-date-query.php | Constructor. |
| [apply\_filters\_ref\_array()](../../functions/apply_filters_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook, specifying arguments in an array. |
| [wpdb::get\_col()](../wpdb/get_col) wp-includes/class-wpdb.php | Retrieves one column from the database. |
| [wpdb::\_escape()](../wpdb/_escape) wp-includes/class-wpdb.php | Escapes data. Works on arrays. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [wpdb::get\_var()](../wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Query::get\_sites()](get_sites) wp-includes/class-wp-site-query.php | Retrieves a list of sites matching the query vars. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
| programming_docs |
wordpress WP_Site_Query::__construct( string|array $query = '' ) WP\_Site\_Query::\_\_construct( string|array $query = '' )
==========================================================
Sets up the site query, based on the query vars passed.
`$query` string|array Optional Array or query string of site query parameters.
* `site__in`int[]Array of site IDs to include.
* `site__not_in`int[]Array of site IDs to exclude.
* `count`boolWhether to return a site count (true) or array of site objects.
Default false.
* `date_query`arrayDate query clauses to limit sites by. See [WP\_Date\_Query](../wp_date_query).
Default null.
* `fields`stringSite fields to return. Accepts `'ids'` (returns an array of site IDs) or empty (returns an array of complete site objects).
* `ID`intA site ID to only return that site.
* `number`intMaximum number of sites to retrieve. Default 100.
* `offset`intNumber of sites to offset the query. Used to build LIMIT clause.
Default 0.
* `no_found_rows`boolWhether to disable the `SQL_CALC_FOUND_ROWS` query. Default true.
* `orderby`string|arraySite 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'`.
* `order`stringHow to order retrieved sites. Accepts `'ASC'`, `'DESC'`. Default `'ASC'`.
* `network_id`intLimit results to those affiliated with a given network ID. If 0, include all networks. Default 0.
* `network__in`int[]Array of network IDs to include affiliated sites for.
* `network__not_in`int[]Array of network IDs to exclude affiliated sites for.
* `domain`stringLimit results to those affiliated with a given domain.
* `domain__in`string[]Array of domains to include affiliated sites for.
* `domain__not_in`string[]Array of domains to exclude affiliated sites for.
* `path`stringLimit results to those affiliated with a given path.
* `path__in`string[]Array of paths to include affiliated sites for.
* `path__not_in`string[]Array of paths to exclude affiliated sites for.
* `public`intLimit results to public sites. Accepts `'1'` or `'0'`.
* `archived`intLimit results to archived sites. Accepts `'1'` or `'0'`.
* `mature`intLimit results to mature sites. Accepts `'1'` or `'0'`.
* `spam`intLimit results to spam sites. Accepts `'1'` or `'0'`.
* `deleted`intLimit results to deleted sites. Accepts `'1'` or `'0'`.
* `lang_id`intLimit results to a language ID.
* `lang__in`string[]Array of language IDs to include affiliated sites for.
* `lang__not_in`string[]Array of language IDs to exclude affiliated sites for.
* `search`stringSearch term(s) to retrieve matching sites for.
* `search_columns`string[]Array of column names to be searched. Accepts `'domain'` and `'path'`.
Default empty array.
* `update_site_cache`boolWhether to prime the cache for found sites. Default true.
* `update_site_meta_cache`boolWhether to prime the metadata cache for found sites. Default true.
* `meta_key`string|string[]Meta key or keys to filter by.
* `meta_value`string|string[]Meta value or values to filter by.
* `meta_compare`stringMySQL operator used for comparing the meta value.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_compare_key`stringMySQL operator used for comparing the meta key.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_type`stringMySQL data type that the meta\_value column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_type_key`stringMySQL data type that the meta\_key column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_query`arrayAn associative array of [WP\_Meta\_Query](../wp_meta_query) arguments.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values.
Default: `''`
File: `wp-includes/class-wp-site-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site-query.php/)
```
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 );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Site\_Query::query()](query) wp-includes/class-wp-site-query.php | Sets up the WordPress query for retrieving sites. |
| Used By | Description |
| --- | --- |
| [wp\_count\_sites()](../../functions/wp_count_sites) wp-includes/ms-blogs.php | Count number of sites grouped by site status. |
| [get\_sites()](../../functions/get_sites) wp-includes/ms-site.php | Retrieves a list of sites matching requested arguments. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced the `'meta_type_key'` parameter. |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | Introduced the `'update_site_meta_cache'`, `'meta_query'`, `'meta_key'`, `'meta_compare_key'`, `'meta_value'`, `'meta_type'`, and `'meta_compare'` parameters. |
| [4.8.0](https://developer.wordpress.org/reference/since/4.8.0/) | Introduced the `'lang_id'`, `'lang__in'`, and `'lang__not_in'` parameters. |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Site_Query::get_sites(): array|int WP\_Site\_Query::get\_sites(): array|int
========================================
Retrieves a list of sites matching the query vars.
array|int List of [WP\_Site](../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.
File: `wp-includes/class-wp-site-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-site-query.php/)
```
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;
}
```
[do\_action\_ref\_array( 'pre\_get\_sites', WP\_Site\_Query $query )](../../hooks/pre_get_sites)
Fires before sites are retrieved.
[apply\_filters\_ref\_array( 'sites\_pre\_query', array|int|null $site\_data, WP\_Site\_Query $query )](../../hooks/sites_pre_query)
Filters the site data before the get\_sites query takes place.
[apply\_filters\_ref\_array( 'the\_sites', WP\_Site[] $\_sites, WP\_Site\_Query $query )](../../hooks/the_sites)
Filters the site query results.
| Uses | Description |
| --- | --- |
| [wp\_cache\_get\_last\_changed()](../../functions/wp_cache_get_last_changed) wp-includes/functions.php | Gets last changed date for the specified cache group. |
| [\_prime\_site\_caches()](../../functions/_prime_site_caches) wp-includes/ms-site.php | Adds any sites from the given IDs to the cache that do not already exist in cache. |
| [get\_site()](../../functions/get_site) wp-includes/ms-site.php | Retrieves site data given a site ID or site object. |
| [WP\_Site\_Query::get\_site\_ids()](get_site_ids) wp-includes/class-wp-site-query.php | Used internally to get a list of site IDs matching the query vars. |
| [WP\_Site\_Query::set\_found\_sites()](set_found_sites) wp-includes/class-wp-site-query.php | Populates found\_sites and max\_num\_pages properties for the current query if the limit clause was used. |
| [WP\_Site\_Query::parse\_query()](parse_query) wp-includes/class-wp-site-query.php | Parses arguments passed to the site query with default query parameters. |
| [wp\_cache\_add()](../../functions/wp_cache_add) wp-includes/cache.php | Adds data to the cache, if the cache key doesn’t already exist. |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| [do\_action\_ref\_array()](../../functions/do_action_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook, specifying arguments in an array. |
| [apply\_filters\_ref\_array()](../../functions/apply_filters_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook, specifying arguments in an array. |
| [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) wp-includes/class-wp-meta-query.php | Constructor. |
| [wp\_cache\_get()](../../functions/wp_cache_get) wp-includes/cache.php | Retrieves the cache contents from the cache by key and group. |
| Used By | Description |
| --- | --- |
| [WP\_Site\_Query::query()](query) wp-includes/class-wp-site-query.php | Sets up the WordPress query for retrieving sites. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Location_Control::to_json() WP\_Customize\_Nav\_Menu\_Location\_Control::to\_json()
=======================================================
Refresh the parameters passed to JavaScript via JSON.
* [WP\_Customize\_Control::to\_json()](../wp_customize_control/to_json)
File: `wp-includes/customize/class-wp-customize-nav-menu-location-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-location-control.php/)
```
public function to_json() {
parent::to_json();
$this->json['locationId'] = $this->location_id;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Control::to\_json()](../wp_customize_control/to_json) wp-includes/class-wp-customize-control.php | Refresh the parameters passed to the JavaScript via JSON. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Location_Control::render_content() WP\_Customize\_Nav\_Menu\_Location\_Control::render\_content()
==============================================================
Render content just like a normal select control.
File: `wp-includes/customize/class-wp-customize-nav-menu-location-control.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/customize/class-wp-customize-nav-menu-location-control.php/)
```
public function render_content() {
if ( empty( $this->choices ) ) {
return;
}
$value_hidden_class = '';
$no_value_hidden_class = '';
if ( $this->value() ) {
$value_hidden_class = ' hidden';
} else {
$no_value_hidden_class = ' hidden';
}
?>
<label>
<?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 class="description customize-control-description"><?php echo $this->description; ?></span>
<?php endif; ?>
<select <?php $this->link(); ?>>
<?php
foreach ( $this->choices as $value => $label ) :
echo '<option value="' . esc_attr( $value ) . '"' . selected( $this->value(), $value, false ) . '>' . $label . '</option>';
endforeach;
?>
</select>
</label>
<button type="button" class="button-link create-menu<?php echo $value_hidden_class; ?>" data-location-id="<?php echo esc_attr( $this->location_id ); ?>" aria-label="<?php esc_attr_e( 'Create a menu for this location' ); ?>"><?php _e( '+ Create New Menu' ); ?></button>
<button type="button" class="button-link edit-menu<?php echo $no_value_hidden_class; ?>" aria-label="<?php esc_attr_e( 'Edit selected menu' ); ?>"><?php _e( 'Edit Menu' ); ?></button>
<?php
}
```
| Uses | Description |
| --- | --- |
| [esc\_attr\_e()](../../functions/esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [selected()](../../functions/selected) wp-includes/general-template.php | Outputs the HTML selected attribute. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Added a button to create menus. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Item_Setting::preview(): bool WP\_Customize\_Nav\_Menu\_Item\_Setting::preview(): bool
========================================================
Handle previewing the setting.
* [WP\_Customize\_Manager::post\_value()](../wp_customize_manager/post_value)
bool False if method short-circuited due to no-op.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::value()](value) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get the instance data for a given nav\_menu\_item setting. |
| [has\_filter()](../../functions/has_filter) wp-includes/plugin.php | Checks if any filter has been registered for a hook. |
| [get\_current\_blog\_id()](../../functions/get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Added boolean return value. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Nav_Menu_Item_Setting::update( array|false $value ): null|void WP\_Customize\_Nav\_Menu\_Item\_Setting::update( array|false $value ): null|void
================================================================================
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 [‘customize\_save\_response’](../../hooks/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.
* [wp\_update\_nav\_menu\_item()](../../functions/wp_update_nav_menu_item)
`$value` array|false Required 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. null|void
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/)
```
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';
}
}
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_delete\_post()](../../functions/wp_delete_post) wp-includes/post.php | Trashes or deletes a post or page. |
| [wp\_update\_nav\_menu\_item()](../../functions/wp_update_nav_menu_item) wp-includes/nav-menu.php | Saves the properties of a menu item or create a new one. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Item_Setting::get_type_label( object $item ): string WP\_Customize\_Nav\_Menu\_Item\_Setting::get\_type\_label( object $item ): string
=================================================================================
Get type label.
`$item` object Required Nav menu item. string The type label.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_taxonomy()](../../functions/get_taxonomy) wp-includes/taxonomy.php | Retrieves the taxonomy object of $taxonomy. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::value\_as\_wp\_post\_nav\_menu\_item()](value_as_wp_post_nav_menu_item) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get the value emulated into a [WP\_Post](../wp_post) and set up as a nav\_menu\_item. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::value()](value) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get the instance data for a given nav\_menu\_item setting. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Item_Setting::value_as_wp_post_nav_menu_item(): WP_Post WP\_Customize\_Nav\_Menu\_Item\_Setting::value\_as\_wp\_post\_nav\_menu\_item(): WP\_Post
=========================================================================================
Get the value emulated into a [WP\_Post](../wp_post) and set up as a nav\_menu\_item.
[WP\_Post](../wp_post) With [wp\_setup\_nav\_menu\_item()](../../functions/wp_setup_nav_menu_item) applied.
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/)
```
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;
}
```
[apply\_filters( 'nav\_menu\_attr\_title', string $item\_title )](../../hooks/nav_menu_attr_title)
Filters a navigation menu item’s title attribute.
[apply\_filters( 'nav\_menu\_description', string $description )](../../hooks/nav_menu_description)
Filters a navigation menu item’s description.
[apply\_filters( 'wp\_setup\_nav\_menu\_item', object $menu\_item )](../../hooks/wp_setup_nav_menu_item)
Filters a navigation menu item object.
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::get\_original\_title()](get_original_title) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get original title. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::get\_type\_label()](get_type_label) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get type label. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::value()](value) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get the instance data for a given nav\_menu\_item setting. |
| [wp\_trim\_words()](../../functions/wp_trim_words) wp-includes/formatting.php | Trims text to a certain number of words. |
| [get\_term\_link()](../../functions/get_term_link) wp-includes/taxonomy.php | Generates a permalink for a taxonomy term archive. |
| [get\_post\_type\_archive\_link()](../../functions/get_post_type_archive_link) wp-includes/link-template.php | Retrieves the permalink for a post type archive. |
| [WP\_Post::\_\_construct()](../wp_post/__construct) wp-includes/class-wp-post.php | Constructor. |
| [get\_permalink()](../../functions/get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::filter\_wp\_get\_nav\_menu\_items()](filter_wp_get_nav_menu_items) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Filters the [wp\_get\_nav\_menu\_items()](../../functions/wp_get_nav_menu_items) result to supply the previewed menu items. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Item_Setting::sanitize( array $value ): array|false|null|WP_Error WP\_Customize\_Nav\_Menu\_Item\_Setting::sanitize( array $value ): array|false|null|WP\_Error
=============================================================================================
Sanitize an input.
Note that parent::sanitize() erroneously does [wp\_unslash()](../../functions/wp_unslash) on $value, but we remove that in this override.
`$value` array Required The menu item value to sanitize. array|false|null|[WP\_Error](../wp_error) Null or [WP\_Error](../wp_error) if an input isn't valid. False if it is marked for deletion.
Otherwise the sanitized value.
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/)
```
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 );
}
```
[apply\_filters( "customize\_sanitize\_{$this->id}", mixed $value, WP\_Customize\_Setting $setting )](../../hooks/customize_sanitize_this-id)
Filters a Customize setting value in un-slashed form.
| Uses | Description |
| --- | --- |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [sanitize\_url()](../../functions/sanitize_url) wp-includes/formatting.php | Sanitizes a URL for database or redirect usage. |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [sanitize\_key()](../../functions/sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$menu_item_value` to `$value` for PHP 8 named parameter support. |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Item_Setting::flush_cached_value( int $menu_id, int $menu_item_id ) WP\_Customize\_Nav\_Menu\_Item\_Setting::flush\_cached\_value( int $menu\_id, int $menu\_item\_id )
===================================================================================================
Clear the cached value when this nav menu item is updated.
`$menu_id` int Required The term ID for the menu. `$menu_item_id` int Required The post ID for the 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/)
```
public function flush_cached_value( $menu_id, $menu_item_id ) {
unset( $menu_id );
if ( $menu_item_id === $this->post_id ) {
$this->value = null;
}
}
```
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Nav_Menu_Item_Setting::sort_wp_get_nav_menu_items( WP_Post[] $items, WP_Term $menu, array $args ): WP_Post[] WP\_Customize\_Nav\_Menu\_Item\_Setting::sort\_wp\_get\_nav\_menu\_items( WP\_Post[] $items, WP\_Term $menu, array $args ): WP\_Post[]
======================================================================================================================================
Re-apply the tail logic also applied on $items by [wp\_get\_nav\_menu\_items()](../../functions/wp_get_nav_menu_items) .
* [wp\_get\_nav\_menu\_items()](../../functions/wp_get_nav_menu_items)
`$items` [WP\_Post](../wp_post)[] Required An array of menu item post objects. `$menu` [WP\_Term](../wp_term) Required The menu object. `$args` array Required An array of arguments used to retrieve menu item objects. [WP\_Post](../wp_post)[] Array of menu item objects.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [wp\_list\_sort()](../../functions/wp_list_sort) wp-includes/functions.php | Sorts an array of objects or arrays based on one or more orderby arguments. |
| [is\_admin()](../../functions/is_admin) wp-includes/load.php | Determines whether the current request is for an administrative interface page. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Item_Setting::populate_value() WP\_Customize\_Nav\_Menu\_Item\_Setting::populate\_value()
==========================================================
Ensure that the value is fully populated with the necessary properties.
Translates some properties added by [wp\_setup\_nav\_menu\_item()](../../functions/wp_setup_nav_menu_item) and removes others.
* [WP\_Customize\_Nav\_Menu\_Item\_Setting::value()](../wp_customize_nav_menu_item_setting/value)
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/)
```
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 ] );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::get\_original\_title()](get_original_title) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get original title. |
| [taxonomy\_exists()](../../functions/taxonomy_exists) wp-includes/taxonomy.php | Determines whether the taxonomy name exists. |
| [wp\_get\_post\_terms()](../../functions/wp_get_post_terms) wp-includes/post.php | Retrieves the terms for a post. |
| [post\_type\_exists()](../../functions/post_type_exists) wp-includes/post.php | Determines whether a post type is registered. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::value()](value) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get the instance data for a given nav\_menu\_item setting. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::\_\_construct()](__construct) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Item_Setting::amend_customize_save_response( array $data ): array WP\_Customize\_Nav\_Menu\_Item\_Setting::amend\_customize\_save\_response( array $data ): array
===============================================================================================
Export data for the JS client.
* [WP\_Customize\_Nav\_Menu\_Item\_Setting::update()](../wp_customize_nav_menu_item_setting/update)
`$data` array Required Additional information passed back to the `'saved'` event on `wp.customize`. array Save response data.
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/)
```
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;
}
```
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Item_Setting::filter_wp_get_nav_menu_items( WP_Post[] $items, WP_Term $menu, array $args ): WP_Post[] WP\_Customize\_Nav\_Menu\_Item\_Setting::filter\_wp\_get\_nav\_menu\_items( WP\_Post[] $items, WP\_Term $menu, array $args ): WP\_Post[]
========================================================================================================================================
Filters the [wp\_get\_nav\_menu\_items()](../../functions/wp_get_nav_menu_items) result to supply the previewed menu items.
* [wp\_get\_nav\_menu\_items()](../../functions/wp_get_nav_menu_items)
`$items` [WP\_Post](../wp_post)[] Required An array of menu item post objects. `$menu` [WP\_Term](../wp_term) Required The menu object. `$args` array Required An array of arguments used to retrieve menu item objects. [WP\_Post](../wp_post)[] Array of menu item objects.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::value\_as\_wp\_post\_nav\_menu\_item()](value_as_wp_post_nav_menu_item) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get the value emulated into a [WP\_Post](../wp_post) and set up as a nav\_menu\_item. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::value()](value) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get the instance data for a given nav\_menu\_item setting. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Item_Setting::value(): array|false WP\_Customize\_Nav\_Menu\_Item\_Setting::value(): array|false
=============================================================
Get the instance data for a given nav\_menu\_item setting.
* [wp\_setup\_nav\_menu\_item()](../../functions/wp_setup_nav_menu_item)
array|false Instance data array, or false if the item is marked for deletion.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::get\_original\_title()](get_original_title) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get original title. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::get\_type\_label()](get_type_label) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get type label. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::populate\_value()](populate_value) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Ensure that the value is fully populated with the necessary properties. |
| [wp\_setup\_nav\_menu\_item()](../../functions/wp_setup_nav_menu_item) wp-includes/nav-menu.php | Decorates a menu item object with the shared navigation menu item properties. |
| [get\_current\_blog\_id()](../../functions/get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::filter\_wp\_get\_nav\_menu\_items()](filter_wp_get_nav_menu_items) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Filters the [wp\_get\_nav\_menu\_items()](../../functions/wp_get_nav_menu_items) result to supply the previewed menu items. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::value\_as\_wp\_post\_nav\_menu\_item()](value_as_wp_post_nav_menu_item) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get the value emulated into a [WP\_Post](../wp_post) and set up as a nav\_menu\_item. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::preview()](preview) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Handle previewing the setting. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Item_Setting::__construct( WP_Customize_Manager $manager, string $id, array $args = array() ) WP\_Customize\_Nav\_Menu\_Item\_Setting::\_\_construct( WP\_Customize\_Manager $manager, string $id, array $args = array() )
============================================================================================================================
Constructor.
Any supplied $args override class property defaults.
`$manager` [WP\_Customize\_Manager](../wp_customize_manager) Required Customizer bootstrap instance. `$id` string Required A specific ID of the setting.
Can be a theme mod or option name. `$args` array Optional Setting arguments. Default: `array()`
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/)
```
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" );
}
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::populate\_value()](populate_value) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Ensure that the value is fully populated with the necessary properties. |
| [WP\_Customize\_Setting::\_\_construct()](../wp_customize_setting/__construct) wp-includes/class-wp-customize-setting.php | Constructor. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menus::enqueue\_scripts()](../wp_customize_nav_menus/enqueue_scripts) wp-includes/class-wp-customize-nav-menus.php | Enqueues scripts and styles for Customizer pane. |
| [WP\_Customize\_Nav\_Menus::customize\_register()](../wp_customize_nav_menus/customize_register) wp-includes/class-wp-customize-nav-menus.php | Adds the customizer settings and controls. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Item_Setting::get_original_title( object $item ): string WP\_Customize\_Nav\_Menu\_Item\_Setting::get\_original\_title( object $item ): string
=====================================================================================
Get original title.
`$item` object Required Nav menu item. string The original title.
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/)
```
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;
}
```
[apply\_filters( 'the\_title', string $post\_title, int $post\_id )](../../hooks/the_title)
Filters the post title.
| Uses | Description |
| --- | --- |
| [get\_term\_field()](../../functions/get_term_field) wp-includes/taxonomy.php | Gets sanitized term field. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::value\_as\_wp\_post\_nav\_menu\_item()](value_as_wp_post_nav_menu_item) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get the value emulated into a [WP\_Post](../wp_post) and set up as a nav\_menu\_item. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::value()](value) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Get the instance data for a given nav\_menu\_item setting. |
| [WP\_Customize\_Nav\_Menu\_Item\_Setting::populate\_value()](populate_value) wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Ensure that the value is fully populated with the necessary properties. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_Block_Type::prepare_attributes_for_render( array $attributes ): array WP\_Block\_Type::prepare\_attributes\_for\_render( array $attributes ): array
=============================================================================
Validates attributes against the current block schema, populating defaulted and missing values.
`$attributes` array Required Original block attributes. array Prepared block attributes.
File: `wp-includes/class-wp-block-type.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [rest\_validate\_value\_from\_schema()](../../functions/rest_validate_value_from_schema) wp-includes/rest-api.php | Validate a value based on a schema. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_Block\_Type::render()](render) wp-includes/class-wp-block-type.php | Renders the block type output for given attributes. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_Block_Type::__set( string $name, mixed $value ) WP\_Block\_Type::\_\_set( string $name, mixed $value )
======================================================
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.
`$name` string Required Property name. `$value` mixed Required Property value. File: `wp-includes/class-wp-block-type.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type.php/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_doing\_it\_wrong()](../../functions/_doing_it_wrong) wp-includes/functions.php | Marks something as being incorrectly called. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Block_Type::__get( string $name ): string|string[]|null|void WP\_Block\_Type::\_\_get( string $name ): string|string[]|null|void
===================================================================
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.
`$name` string Required Deprecated property name. 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.
File: `wp-includes/class-wp-block-type.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type.php/)
```
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;
}
```
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Block_Type::is_dynamic(): bool WP\_Block\_Type::is\_dynamic(): bool
====================================
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.
bool Whether block type is dynamic.
File: `wp-includes/class-wp-block-type.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type.php/)
```
public function is_dynamic() {
return is_callable( $this->render_callback );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Block\_Type::render()](render) wp-includes/class-wp-block-type.php | Renders the block type output for given attributes. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_Block_Type::__isset( string $name ): boolean WP\_Block\_Type::\_\_isset( string $name ): boolean
===================================================
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.
`$name` string Required Deprecated property name. boolean Returns true when for the new property the first item in the array exists, or false otherwise.
File: `wp-includes/class-wp-block-type.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type.php/)
```
public function __isset( $name ) {
if ( ! in_array( $name, $this->deprecated_properties ) ) {
return false;
}
$new_name = $name . '_handles';
return isset( $this->{$new_name}[0] );
}
```
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Block_Type::get_attributes(): array WP\_Block\_Type::get\_attributes(): array
=========================================
Get all available block attributes including possible layout attribute from Columns block.
array Array of attributes.
File: `wp-includes/class-wp-block-type.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type.php/)
```
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. |
wordpress WP_Block_Type::__construct( string $block_type, array|string $args = array() ) WP\_Block\_Type::\_\_construct( string $block\_type, array|string $args = array() )
===================================================================================
Constructor.
Will populate object properties from the provided arguments.
* [register\_block\_type()](../../functions/register_block_type)
`$block_type` string Required Block type name including namespace. `$args` array|string 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.
* `api_version`stringBlock API version.
* `title`stringHuman-readable block type label.
* `category`string|nullBlock type category classification, used in search interfaces to arrange block types by category.
* `parent`string[]|nullSetting parent lets a block require that it is only available when nested within the specified blocks.
* `ancestor`string[]|nullSetting ancestor makes a block available only inside the specified block types at any position of the ancestor's block subtree.
* `icon`string|nullBlock type icon.
* `description`stringA detailed block type description.
* `keywords`string[]Additional keywords to produce block type as result in search interfaces.
* `textdomain`string|nullThe translation textdomain.
* `styles`array[]Alternative block styles.
* `variations`array[]Block variations.
* `supports`array|nullSupported features.
* `example`array|nullStructured data for the block preview.
* `render_callback`callable|nullBlock type render callback.
* `attributes`array|nullBlock type attributes property schemas.
* `uses_context`string[]Context values inherited by blocks of this type.
* `provides_context`string[]|nullContext provided by blocks of this type.
* `editor_script_handles`string[]Block type editor only script handles.
* `script_handles`string[]Block type front end and editor script handles.
* `view_script_handles`string[]Block type front end only script handles.
* `editor_style_handles`string[]Block type editor only style handles.
* `style_handles`string[]Block type front end and editor style handles.
Default: `array()`
File: `wp-includes/class-wp-block-type.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type.php/)
```
public function __construct( $block_type, $args = array() ) {
$this->name = $block_type;
$this->set_props( $args );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Block\_Type::set\_props()](set_props) wp-includes/class-wp-block-type.php | Sets block type properties. |
| Used By | Description |
| --- | --- |
| [WP\_Block\_Type\_Registry::register()](../wp_block_type_registry/register) wp-includes/class-wp-block-type-registry.php | Registers a block type. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/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. |
| [6.0.0](https://developer.wordpress.org/reference/since/6.0.0/) | Added the `ancestor` property. |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Added the `view_script` property. |
| [5.8.0](https://developer.wordpress.org/reference/since/5.8.0/) | Added the `variations` property. |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Added the `api_version` property. |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Added the `title`, `category`, `parent`, `icon`, `description`, `keywords`, `textdomain`, `styles`, `supports`, `example`, `uses_context`, and `provides_context` properties. |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_Block_Type::render( array $attributes = array(), string $content = '' ): string WP\_Block\_Type::render( array $attributes = array(), string $content = '' ): string
====================================================================================
Renders the block type output for given attributes.
`$attributes` array Optional Block attributes. Default: `array()`
`$content` string Optional Block content. Default: `''`
string Rendered block type output.
File: `wp-includes/class-wp-block-type.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type.php/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Block\_Type::is\_dynamic()](is_dynamic) wp-includes/class-wp-block-type.php | 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. |
| [WP\_Block\_Type::prepare\_attributes\_for\_render()](prepare_attributes_for_render) wp-includes/class-wp-block-type.php | Validates attributes against the current block schema, populating defaulted and missing values. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_Block_Type::set_props( array|string $args ) WP\_Block\_Type::set\_props( array|string $args )
=================================================
Sets block type properties.
`$args` array|string Required Array or string of arguments for registering a block type.
See [WP\_Block\_Type::\_\_construct()](__construct) for information on accepted arguments. More Arguments from WP\_Block\_Type::\_\_construct( ... $args ) Array or string of arguments for registering a block type. Any arguments may be defined, however the ones described below are supported by default.
* `api_version`stringBlock API version.
* `title`stringHuman-readable block type label.
* `category`string|nullBlock type category classification, used in search interfaces to arrange block types by category.
* `parent`string[]|nullSetting parent lets a block require that it is only available when nested within the specified blocks.
* `ancestor`string[]|nullSetting ancestor makes a block available only inside the specified block types at any position of the ancestor's block subtree.
* `icon`string|nullBlock type icon.
* `description`stringA detailed block type description.
* `keywords`string[]Additional keywords to produce block type as result in search interfaces.
* `textdomain`string|nullThe translation textdomain.
* `styles`array[]Alternative block styles.
* `variations`array[]Block variations.
* `supports`array|nullSupported features.
* `example`array|nullStructured data for the block preview.
* `render_callback`callable|nullBlock type render callback.
* `attributes`array|nullBlock type attributes property schemas.
* `uses_context`string[]Context values inherited by blocks of this type.
* `provides_context`string[]|nullContext provided by blocks of this type.
* `editor_script_handles`string[]Block type editor only script handles.
* `script_handles`string[]Block type front end and editor script handles.
* `view_script_handles`string[]Block type front end only script handles.
* `editor_style_handles`string[]Block type editor only style handles.
* `style_handles`string[]Block type front end and editor style handles.
File: `wp-includes/class-wp-block-type.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-block-type.php/)
```
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;
}
}
```
[apply\_filters( 'register\_block\_type\_args', array $args, string $block\_type )](../../hooks/register_block_type_args)
Filters the arguments for registering a block type.
| Uses | Description |
| --- | --- |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_Block\_Type::\_\_construct()](__construct) wp-includes/class-wp-block-type.php | Constructor. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Setting::filter_nav_menu_options_value( array $nav_menu_options, int $menu_id, bool $auto_add ): array WP\_Customize\_Nav\_Menu\_Setting::filter\_nav\_menu\_options\_value( array $nav\_menu\_options, int $menu\_id, bool $auto\_add ): array
========================================================================================================================================
Updates a nav\_menu\_options array.
* [WP\_Customize\_Nav\_Menu\_Setting::filter\_nav\_menu\_options()](../wp_customize_nav_menu_setting/filter_nav_menu_options)
* [WP\_Customize\_Nav\_Menu\_Setting::update()](../wp_customize_nav_menu_setting/update)
`$nav_menu_options` array Required Array as returned by get\_option( `'nav_menu_options'` ). `$menu_id` int Required The term ID for the given menu. `$auto_add` bool Required Whether to auto-add or not. array (Maybe) modified nav\_menu\_options array.
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/)
```
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;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Setting::filter\_nav\_menu\_options()](filter_nav_menu_options) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Filters the nav\_menu\_options option to include this menu’s auto\_add preference. |
| [WP\_Customize\_Nav\_Menu\_Setting::update()](update) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Create/update the nav\_menu term for this setting. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Nav_Menu_Setting::preview(): bool WP\_Customize\_Nav\_Menu\_Setting::preview(): bool
==================================================
Handle previewing the setting.
* [WP\_Customize\_Manager::post\_value()](../wp_customize_manager/post_value)
bool False if method short-circuited due to no-op.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Setting::value()](value) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Get the instance data for a given widget setting. |
| [get\_current\_blog\_id()](../../functions/get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Added boolean return value |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Setting::update( array|false $value ): null|void WP\_Customize\_Nav\_Menu\_Setting::update( array|false $value ): null|void
==========================================================================
Create/update the nav\_menu term for this setting.
Any created menus will have their assigned term IDs exported to the client via the [‘customize\_save\_response’](../../hooks/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.
* [wp\_update\_nav\_menu\_object()](../../functions/wp_update_nav_menu_object)
`$value` array|false Required The value to update. Note that slug cannot be updated via [wp\_update\_nav\_menu\_object()](../../functions/wp_update_nav_menu_object) .
If false, then the menu will be deleted entirely.
* `name`stringThe name of the menu to save.
* `description`stringThe term description. Default empty string.
* `parent`intThe id of the parent term. Default 0.
* `auto_add`boolWhether pages will auto\_add to this menu. Default false.
null|void
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/)
```
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;
}
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Setting::filter\_nav\_menu\_options\_value()](filter_nav_menu_options_value) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Updates a nav\_menu\_options array. |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| [wp\_delete\_nav\_menu()](../../functions/wp_delete_nav_menu) wp-includes/nav-menu.php | Deletes a navigation menu. |
| [wp\_update\_nav\_menu\_object()](../../functions/wp_update_nav_menu_object) wp-includes/nav-menu.php | Saves the properties of a menu or create a new menu with those properties. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [update\_option()](../../functions/update_option) wp-includes/option.php | Updates the value of an option that was already added. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Setting::filter_wp_get_nav_menu_object( object|null $menu_obj, string $menu_id ): object|null WP\_Customize\_Nav\_Menu\_Setting::filter\_wp\_get\_nav\_menu\_object( object|null $menu\_obj, string $menu\_id ): object|null
==============================================================================================================================
Filters the [wp\_get\_nav\_menu\_object()](../../functions/wp_get_nav_menu_object) result to supply the previewed menu object.
Requesting a nav\_menu object by anything but ID is not supported.
* [wp\_get\_nav\_menu\_object()](../../functions/wp_get_nav_menu_object)
`$menu_obj` object|null Required Object returned by [wp\_get\_nav\_menu\_object()](../../functions/wp_get_nav_menu_object) . `$menu_id` string Required ID of the nav\_menu term. Requests by slug or name will be ignored. object|null
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Setting::value()](value) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Get the instance data for a given widget setting. |
| [sanitize\_title()](../../functions/sanitize_title) wp-includes/formatting.php | Sanitizes a string into a slug, which can be used in URLs or HTML attributes. |
| [get\_current\_blog\_id()](../../functions/get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Setting::_sort_menus_by_orderby( object $menu1, object $menu2 ): int WP\_Customize\_Nav\_Menu\_Setting::\_sort\_menus\_by\_orderby( object $menu1, object $menu2 ): int
==================================================================================================
This method has been deprecated. Use [WP\_Customize\_Nav\_Menu\_Setting::filter\_wp\_get\_nav\_menus()](../wp_customize_nav_menu_setting/filter_wp_get_nav_menus) instead.
Sort menu objects by the class-supplied orderby property.
This is a workaround for a lack of closures.
* [WP\_Customize\_Nav\_Menu\_Setting::filter\_wp\_get\_nav\_menus()](../wp_customize_nav_menu_setting/filter_wp_get_nav_menus)
`$menu1` object Required `$menu2` object Required int
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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Use [wp\_list\_sort()](../../functions/wp_list_sort) |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Setting::sanitize( array $value ): array|false|null WP\_Customize\_Nav\_Menu\_Setting::sanitize( array $value ): array|false|null
=============================================================================
Sanitize an input.
Note that parent::sanitize() erroneously does [wp\_unslash()](../../functions/wp_unslash) on $value, but we remove that in this override.
`$value` array Required The menu value to sanitize. array|false|null Null if an input isn't valid. False if it is marked for deletion.
Otherwise the sanitized value.
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/)
```
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 );
}
```
[apply\_filters( "customize\_sanitize\_{$this->id}", mixed $value, WP\_Customize\_Setting $setting )](../../hooks/customize_sanitize_this-id)
Filters a Customize setting value in un-slashed form.
| Uses | Description |
| --- | --- |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Setting::filter_nav_menu_options( array $nav_menu_options ): array WP\_Customize\_Nav\_Menu\_Setting::filter\_nav\_menu\_options( array $nav\_menu\_options ): array
=================================================================================================
Filters the nav\_menu\_options option to include this menu’s auto\_add preference.
`$nav_menu_options` array Required Nav menu options including auto\_add. array (Maybe) modified nav menu options.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Setting::filter\_nav\_menu\_options\_value()](filter_nav_menu_options_value) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Updates a nav\_menu\_options array. |
| [WP\_Customize\_Nav\_Menu\_Setting::value()](value) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Get the instance data for a given widget setting. |
| [get\_current\_blog\_id()](../../functions/get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Setting::amend_customize_save_response( array $data ): array WP\_Customize\_Nav\_Menu\_Setting::amend\_customize\_save\_response( array $data ): array
=========================================================================================
Export data for the JS client.
* [WP\_Customize\_Nav\_Menu\_Setting::update()](../wp_customize_nav_menu_setting/update)
`$data` array Required Additional information passed back to the `'saved'` event on `wp.customize`. array Export data.
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/)
```
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\_Nav\_Menu\_Setting::value()](value) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Get the instance data for a given widget setting. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Setting::value(): array WP\_Customize\_Nav\_Menu\_Setting::value(): array
=================================================
Get the instance data for a given widget setting.
* [wp\_get\_nav\_menu\_object()](../../functions/wp_get_nav_menu_object)
array Instance data.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| [wp\_get\_nav\_menu\_object()](../../functions/wp_get_nav_menu_object) wp-includes/nav-menu.php | Returns a navigation menu object. |
| [get\_current\_blog\_id()](../../functions/get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menu\_Setting::filter\_nav\_menu\_options()](filter_nav_menu_options) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Filters the nav\_menu\_options option to include this menu’s auto\_add preference. |
| [WP\_Customize\_Nav\_Menu\_Setting::amend\_customize\_save\_response()](amend_customize_save_response) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Export data for the JS client. |
| [WP\_Customize\_Nav\_Menu\_Setting::preview()](preview) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Handle previewing the setting. |
| [WP\_Customize\_Nav\_Menu\_Setting::filter\_wp\_get\_nav\_menus()](filter_wp_get_nav_menus) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Filters the [wp\_get\_nav\_menus()](../../functions/wp_get_nav_menus) result to ensure the inserted menu object is included, and the deleted one is removed. |
| [WP\_Customize\_Nav\_Menu\_Setting::filter\_wp\_get\_nav\_menu\_object()](filter_wp_get_nav_menu_object) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Filters the [wp\_get\_nav\_menu\_object()](../../functions/wp_get_nav_menu_object) result to supply the previewed menu object. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
| programming_docs |
wordpress WP_Customize_Nav_Menu_Setting::__construct( WP_Customize_Manager $manager, string $id, array $args = array() ) WP\_Customize\_Nav\_Menu\_Setting::\_\_construct( WP\_Customize\_Manager $manager, string $id, array $args = array() )
======================================================================================================================
Constructor.
Any supplied $args override class property defaults.
`$manager` [WP\_Customize\_Manager](../wp_customize_manager) Required Customizer bootstrap instance. `$id` string Required A specific ID of the setting.
Can be a theme mod or option name. `$args` array Optional Setting arguments. Default: `array()`
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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Customize\_Setting::\_\_construct()](../wp_customize_setting/__construct) wp-includes/class-wp-customize-setting.php | Constructor. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Nav\_Menus::enqueue\_scripts()](../wp_customize_nav_menus/enqueue_scripts) wp-includes/class-wp-customize-nav-menus.php | Enqueues scripts and styles for Customizer pane. |
| [WP\_Customize\_Nav\_Menus::customize\_register()](../wp_customize_nav_menus/customize_register) wp-includes/class-wp-customize-nav-menus.php | Adds the customizer settings and controls. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_Customize_Nav_Menu_Setting::filter_wp_get_nav_menus( WP_Term[] $menus, array $args ): WP_Term[] WP\_Customize\_Nav\_Menu\_Setting::filter\_wp\_get\_nav\_menus( WP\_Term[] $menus, array $args ): WP\_Term[]
============================================================================================================
Filters the [wp\_get\_nav\_menus()](../../functions/wp_get_nav_menus) result to ensure the inserted menu object is included, and the deleted one is removed.
* [wp\_get\_nav\_menus()](../../functions/wp_get_nav_menus)
`$menus` [WP\_Term](../wp_term)[] Required An array of menu objects. `$args` array Required An array of arguments used to retrieve menu objects. [WP\_Term](../wp_term)[] Array of menu objects.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [wp\_list\_sort()](../../functions/wp_list_sort) wp-includes/functions.php | Sorts an array of objects or arrays based on one or more orderby arguments. |
| [WP\_Customize\_Nav\_Menu\_Setting::value()](value) wp-includes/customize/class-wp-customize-nav-menu-setting.php | Get the instance data for a given widget setting. |
| [sanitize\_title()](../../functions/sanitize_title) wp-includes/formatting.php | Sanitizes a string into a slug, which can be used in URLs or HTML attributes. |
| [get\_current\_blog\_id()](../../functions/get_current_blog_id) wp-includes/load.php | Retrieve the current site ID. |
| Version | Description |
| --- | --- |
| [4.3.0](https://developer.wordpress.org/reference/since/4.3.0/) | Introduced. |
wordpress WP_REST_Themes_Controller::get_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Themes\_Controller::get\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
===================================================================================================
Retrieves a single theme.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Themes\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Prepares a single theme output for response. |
| [WP\_Theme::exists()](../wp_theme/exists) wp-includes/class-wp-theme.php | Determines whether the theme exists. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Introduced. |
wordpress WP_REST_Themes_Controller::prepare_theme_support( mixed $support, array $args, string $feature, WP_REST_Request $request ): mixed WP\_REST\_Themes\_Controller::prepare\_theme\_support( mixed $support, array $args, string $feature, WP\_REST\_Request $request ): mixed
========================================================================================================================================
Prepares the theme support value for inclusion in the REST API response.
`$support` mixed Required The raw value from [get\_theme\_support()](../../functions/get_theme_support) . More Arguments from get\_theme\_support( ... $args ) extra arguments to be checked against certain features. `$args` array Required The feature's registration args. `$feature` string Required The feature name. `$request` [WP\_REST\_Request](../wp_rest_request) Required The request object. mixed The prepared support value.
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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [rest\_sanitize\_value\_from\_schema()](../../functions/rest_sanitize_value_from_schema) wp-includes/rest-api.php | Sanitize a value based on a schema. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Themes_Controller::is_same_theme( WP_Theme $theme_a, WP_Theme $theme_b ): bool WP\_REST\_Themes\_Controller::is\_same\_theme( WP\_Theme $theme\_a, WP\_Theme $theme\_b ): bool
===============================================================================================
Helper function to compare two themes.
`$theme_a` [WP\_Theme](../wp_theme) Required First theme to compare. `$theme_b` [WP\_Theme](../wp_theme) Required Second theme to compare. bool
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/)
```
protected function is_same_theme( $theme_a, $theme_b ) {
return $theme_a->get_stylesheet() === $theme_b->get_stylesheet();
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Themes\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Checks if a given request has access to read the theme. |
| [WP\_REST\_Themes\_Controller::prepare\_links()](prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Prepares links for the request. |
| [WP\_REST\_Themes\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Retrieves a collection of themes. |
| [WP\_REST\_Themes\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Prepares a single theme output for response. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Introduced. |
wordpress WP_REST_Themes_Controller::prepare_item_for_response( WP_Theme $item, WP_REST_Request $request ): WP_REST_Response WP\_REST\_Themes\_Controller::prepare\_item\_for\_response( WP\_Theme $item, WP\_REST\_Request $request ): WP\_REST\_Response
=============================================================================================================================
Prepares a single theme output for response.
`$item` [WP\_Theme](../wp_theme) Required Theme object. `$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. [WP\_REST\_Response](../wp_rest_response) Response object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php/)
```
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 );
}
```
[apply\_filters( 'rest\_prepare\_theme', WP\_REST\_Response $response, WP\_Theme $theme, WP\_REST\_Request $request )](../../hooks/rest_prepare_theme)
Filters theme data returned from the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Themes\_Controller::is\_same\_theme()](is_same_theme) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Helper function to compare two themes. |
| [WP\_REST\_Themes\_Controller::prepare\_links()](prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Prepares links for the request. |
| [get\_registered\_theme\_features()](../../functions/get_registered_theme_features) wp-includes/theme.php | Gets the list of registered theme features. |
| [rest\_is\_field\_included()](../../functions/rest_is_field_included) wp-includes/rest-api.php | Given an array of fields to include in a response, some of which may be `nested.fields`, determine whether the provided field should be included in the response body. |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Themes\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Retrieves a single theme. |
| [WP\_REST\_Themes\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Retrieves a collection of themes. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$theme` to `$item` to match parent class for PHP 8 named parameter support. |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Themes_Controller::prepare_links( WP_Theme $theme ): array WP\_REST\_Themes\_Controller::prepare\_links( WP\_Theme $theme ): array
=======================================================================
Prepares links for the request.
`$theme` [WP\_Theme](../wp_theme) Required Theme data. array Links for the given block type.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme\_JSON\_Resolver::get\_user\_global\_styles\_post\_id()](../wp_theme_json_resolver/get_user_global_styles_post_id) wp-includes/class-wp-theme-json-resolver.php | Returns the ID of the custom post type that stores user data. |
| [WP\_Theme\_JSON\_Resolver::get\_user\_data\_from\_wp\_global\_styles()](../wp_theme_json_resolver/get_user_data_from_wp_global_styles) wp-includes/class-wp-theme-json-resolver.php | Returns the custom post type that contains the user’s origin config for the active theme or a void array if none are found. |
| [WP\_REST\_Themes\_Controller::is\_same\_theme()](is_same_theme) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Helper function to compare two themes. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Themes\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Prepares a single theme output for response. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Themes_Controller::get_items( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Themes\_Controller::get\_items( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
====================================================================================================
Retrieves a collection of themes.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Themes\_Controller::is\_same\_theme()](is_same_theme) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Helper function to compare two themes. |
| [WP\_REST\_Themes\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Prepares a single theme output for response. |
| [wp\_get\_themes()](../../functions/wp_get_themes) wp-includes/theme.php | Returns an array of [WP\_Theme](../wp_theme) objects based on the arguments. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Themes_Controller::get_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Themes\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
==========================================================================================================
Checks if a given request has access to read the theme.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access for the item, otherwise [WP\_Error](../wp_error) object.
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/)
```
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() )
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Themes\_Controller::check\_read\_active\_theme\_permission()](check_read_active_theme_permission) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Checks if a theme can be read. |
| [WP\_REST\_Themes\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Retrieves the search params for the themes collection. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Themes_Controller::register_routes() WP\_REST\_Themes\_Controller::register\_routes()
================================================
Registers the routes for themes.
* [register\_rest\_route()](../../functions/register_rest_route)
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/)
```
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' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Themes\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Retrieves the search params for the themes collection. |
| [register\_rest\_route()](../../functions/register_rest_route) wp-includes/rest-api.php | Registers a REST API route. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Themes_Controller::sanitize_theme_status( string|array $statuses, WP_REST_Request $request, string $parameter ): array|WP_Error WP\_REST\_Themes\_Controller::sanitize\_theme\_status( string|array $statuses, WP\_REST\_Request $request, string $parameter ): array|WP\_Error
===============================================================================================================================================
This method has been deprecated.
Sanitizes and validates the list of theme status.
`$statuses` string|array Required One or more theme statuses. `$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. `$parameter` string Required Additional parameter to pass to validation. array|[WP\_Error](../wp_error) A list of valid statuses, otherwise [WP\_Error](../wp_error) object.
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/)
```
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 |
| --- | --- |
| [rest\_validate\_request\_arg()](../../functions/rest_validate_request_arg) wp-includes/rest-api.php | Validate a request argument based on details registered to the route. |
| [wp\_parse\_slug\_list()](../../functions/wp_parse_slug_list) wp-includes/functions.php | Cleans up an array, comma- or space-separated list of slugs. |
| [\_deprecated\_function()](../../functions/_deprecated_function) wp-includes/functions.php | Marks a function as deprecated and inform when it has been used. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | This method has been deprecated. |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Themes_Controller::get_collection_params(): array WP\_REST\_Themes\_Controller::get\_collection\_params(): array
==============================================================
Retrieves the search params for the themes collection.
array Collection parameters.
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/)
```
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 );
}
```
[apply\_filters( 'rest\_themes\_collection\_params', array $query\_params )](../../hooks/rest_themes_collection_params)
Filters REST API collection parameters for the themes controller.
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Themes\_Controller::register\_routes()](register_routes) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Registers the routes for themes. |
| [WP\_REST\_Themes\_Controller::get\_items\_permissions\_check()](get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Checks if a given request has access to read the theme. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Themes_Controller::__construct() WP\_REST\_Themes\_Controller::\_\_construct()
=============================================
Constructor.
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/)
```
public function __construct() {
$this->namespace = 'wp/v2';
$this->rest_base = 'themes';
}
```
| Used By | Description |
| --- | --- |
| [create\_initial\_rest\_routes()](../../functions/create_initial_rest_routes) wp-includes/rest-api.php | Registers default REST API routes. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
wordpress WP_REST_Themes_Controller::get_item_permissions_check( WP_REST_Request $request ): bool|WP_Error WP\_REST\_Themes\_Controller::get\_item\_permissions\_check( WP\_REST\_Request $request ): bool|WP\_Error
=========================================================================================================
Checks if a given request has access to read the theme.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. bool|[WP\_Error](../wp_error) True if the request has read access for the item, otherwise [WP\_Error](../wp_error) object.
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/)
```
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() )
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Themes\_Controller::is\_same\_theme()](is_same_theme) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Helper function to compare two themes. |
| [WP\_REST\_Themes\_Controller::check\_read\_active\_theme\_permission()](check_read_active_theme_permission) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Checks if a theme can be read. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Introduced. |
wordpress WP_REST_Themes_Controller::check_read_active_theme_permission(): bool|WP_Error WP\_REST\_Themes\_Controller::check\_read\_active\_theme\_permission(): bool|WP\_Error
======================================================================================
Checks if a theme can be read.
bool|[WP\_Error](../wp_error) Whether the theme can be read.
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/)
```
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() )
);
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_post\_types()](../../functions/get_post_types) wp-includes/post.php | Gets a list of all registered post type objects. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Themes\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Checks if a given request has access to read the theme. |
| [WP\_REST\_Themes\_Controller::get\_items\_permissions\_check()](get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-themes-controller.php | Checks if a given request has access to read the theme. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Introduced. |
wordpress WP_REST_Themes_Controller::get_item_schema(): array WP\_REST\_Themes\_Controller::get\_item\_schema(): array
========================================================
Retrieves the theme’s schema, conforming to JSON Schema.
array Item schema data.
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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [get\_registered\_theme\_features()](../../functions/get_registered_theme_features) wp-includes/theme.php | Gets the list of registered theme features. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.0.0](https://developer.wordpress.org/reference/since/5.0.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Themes_Controller::_sanitize_stylesheet_callback( string $stylesheet ): string WP\_REST\_Themes\_Controller::\_sanitize\_stylesheet\_callback( string $stylesheet ): string
============================================================================================
Sanitize the stylesheet to decode endpoint.
`$stylesheet` string Required The stylesheet name. string Sanitized stylesheet.
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/)
```
public function _sanitize_stylesheet_callback( $stylesheet ) {
return urldecode( $stylesheet );
}
```
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Introduced. |
wordpress WP_Plugin_Install_List_Table::prepare_items() WP\_Plugin\_Install\_List\_Table::prepare\_items()
==================================================
File: `wp-admin/includes/class-wp-plugin-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugin-install-list-table.php/)
```
public function prepare_items() {
include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
global $tabs, $tab, $paged, $type, $term;
wp_reset_vars( array( 'tab' ) );
$paged = $this->get_pagenum();
$per_page = 36;
// These are the tabs which are shown on the page.
$tabs = array();
if ( 'search' === $tab ) {
$tabs['search'] = __( 'Search Results' );
}
if ( 'beta' === $tab || false !== strpos( get_bloginfo( 'version' ), '-' ) ) {
$tabs['beta'] = _x( 'Beta Testing', 'Plugin Installer' );
}
$tabs['featured'] = _x( 'Featured', 'Plugin Installer' );
$tabs['popular'] = _x( 'Popular', 'Plugin Installer' );
$tabs['recommended'] = _x( 'Recommended', 'Plugin Installer' );
$tabs['favorites'] = _x( 'Favorites', 'Plugin Installer' );
if ( current_user_can( 'upload_plugins' ) ) {
// No longer a real tab. Here for filter compatibility.
// Gets skipped in get_views().
$tabs['upload'] = __( 'Upload Plugin' );
}
$nonmenu_tabs = array( 'plugin-information' ); // Valid actions to perform which do not have a Menu item.
/**
* Filters the tabs shown on the Add Plugins screen.
*
* @since 2.7.0
*
* @param string[] $tabs The tabs shown on the Add Plugins screen. Defaults include
* 'featured', 'popular', 'recommended', 'favorites', and 'upload'.
*/
$tabs = apply_filters( 'install_plugins_tabs', $tabs );
/**
* Filters tabs not associated with a menu item on the Add Plugins screen.
*
* @since 2.7.0
*
* @param string[] $nonmenu_tabs The tabs that don't have a menu item on the Add Plugins screen.
*/
$nonmenu_tabs = apply_filters( 'install_plugins_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 );
}
$installed_plugins = $this->get_installed_plugins();
$args = array(
'page' => $paged,
'per_page' => $per_page,
// Send the locale to the API so it can provide context-sensitive results.
'locale' => get_user_locale(),
);
switch ( $tab ) {
case 'search':
$type = isset( $_REQUEST['type'] ) ? wp_unslash( $_REQUEST['type'] ) : 'term';
$term = isset( $_REQUEST['s'] ) ? wp_unslash( $_REQUEST['s'] ) : '';
switch ( $type ) {
case 'tag':
$args['tag'] = sanitize_title_with_dashes( $term );
break;
case 'term':
$args['search'] = $term;
break;
case 'author':
$args['author'] = $term;
break;
}
break;
case 'featured':
case 'popular':
case 'new':
case 'beta':
$args['browse'] = $tab;
break;
case 'recommended':
$args['browse'] = $tab;
// Include the list of installed plugins so we can get relevant results.
$args['installed_plugins'] = array_keys( $installed_plugins );
break;
case 'favorites':
$action = 'save_wporg_username_' . get_current_user_id();
if ( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( wp_unslash( $_GET['_wpnonce'] ), $action ) ) {
$user = isset( $_GET['user'] ) ? wp_unslash( $_GET['user'] ) : get_user_option( 'wporg_favorites' );
// If the save url parameter is passed with a falsey value, don't save the favorite user.
if ( ! isset( $_GET['save'] ) || $_GET['save'] ) {
update_user_meta( get_current_user_id(), 'wporg_favorites', $user );
}
} else {
$user = get_user_option( 'wporg_favorites' );
}
if ( $user ) {
$args['user'] = $user;
} else {
$args = false;
}
add_action( 'install_plugins_favorites', 'install_plugins_favorites_form', 9, 0 );
break;
default:
$args = false;
break;
}
/**
* Filters API request arguments for each Add Plugins screen tab.
*
* The dynamic portion of the hook name, `$tab`, refers to the plugin install tabs.
*
* Possible hook names include:
*
* - `install_plugins_table_api_args_favorites`
* - `install_plugins_table_api_args_featured`
* - `install_plugins_table_api_args_popular`
* - `install_plugins_table_api_args_recommended`
* - `install_plugins_table_api_args_upload`
* - `install_plugins_table_api_args_search`
* - `install_plugins_table_api_args_beta`
*
* @since 3.7.0
*
* @param array|false $args Plugin install API arguments.
*/
$args = apply_filters( "install_plugins_table_api_args_{$tab}", $args );
if ( ! $args ) {
return;
}
$api = plugins_api( 'query_plugins', $args );
if ( is_wp_error( $api ) ) {
$this->error = $api;
return;
}
$this->items = $api->plugins;
if ( $this->orderby ) {
uasort( $this->items, array( $this, 'order_callback' ) );
}
$this->set_pagination_args(
array(
'total_items' => $api->info['results'],
'per_page' => $args['per_page'],
)
);
if ( isset( $api->info['groups'] ) ) {
$this->groups = $api->info['groups'];
}
if ( $installed_plugins ) {
$js_plugins = array_fill_keys(
array( 'all', 'search', 'active', 'inactive', 'recently_activated', 'mustuse', 'dropins' ),
array()
);
$js_plugins['all'] = array_values( wp_list_pluck( $installed_plugins, 'plugin' ) );
$upgrade_plugins = wp_filter_object_list( $installed_plugins, array( 'upgrade' => true ), 'and', 'plugin' );
if ( $upgrade_plugins ) {
$js_plugins['upgrade'] = array_values( $upgrade_plugins );
}
wp_localize_script(
'updates',
'_wpUpdatesItemCounts',
array(
'plugins' => $js_plugins,
'totals' => wp_get_update_data(),
)
);
}
}
```
[apply\_filters( 'install\_plugins\_nonmenu\_tabs', string[] $nonmenu\_tabs )](../../hooks/install_plugins_nonmenu_tabs)
Filters tabs not associated with a menu item on the Add Plugins screen.
[apply\_filters( "install\_plugins\_table\_api\_args\_{$tab}", array|false $args )](../../hooks/install_plugins_table_api_args_tab)
Filters API request arguments for each Add Plugins screen tab.
[apply\_filters( 'install\_plugins\_tabs', string[] $tabs )](../../hooks/install_plugins_tabs)
Filters the tabs shown on the Add Plugins screen.
| Uses | Description |
| --- | --- |
| [WP\_Plugin\_Install\_List\_Table::get\_installed\_plugins()](get_installed_plugins) wp-admin/includes/class-wp-plugin-install-list-table.php | Return the list of known plugins. |
| [wp\_get\_update\_data()](../../functions/wp_get_update_data) wp-includes/update.php | Collects counts and UI strings for available updates. |
| [wp\_reset\_vars()](../../functions/wp_reset_vars) wp-admin/includes/misc.php | Resets global variables based on $\_GET and $\_POST. |
| [plugins\_api()](../../functions/plugins_api) wp-admin/includes/plugin-install.php | Retrieves plugin installer pages from the WordPress.org Plugins API. |
| [get\_user\_option()](../../functions/get_user_option) wp-includes/user.php | Retrieves user option that can be either per Site or per Network. |
| [update\_user\_meta()](../../functions/update_user_meta) wp-includes/user.php | Updates user meta field based on user ID. |
| [sanitize\_title\_with\_dashes()](../../functions/sanitize_title_with_dashes) wp-includes/formatting.php | Sanitizes a title, replacing whitespace and a few other characters with dashes. |
| [wp\_verify\_nonce()](../../functions/wp_verify_nonce) wp-includes/pluggable.php | Verifies that a correct security nonce was used with time limit. |
| [get\_user\_locale()](../../functions/get_user_locale) wp-includes/l10n.php | Retrieves the locale of a user. |
| [wp\_localize\_script()](../../functions/wp_localize_script) wp-includes/functions.wp-scripts.php | Localize a script. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [wp\_filter\_object\_list()](../../functions/wp_filter_object_list) wp-includes/functions.php | Filters a list of objects, based on a set of key => value arguments. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [wp\_unslash()](../../functions/wp_unslash) wp-includes/formatting.php | Removes slashes from a string or recursively removes slashes from strings within an array. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
wordpress WP_Plugin_Install_List_Table::ajax_user_can(): bool WP\_Plugin\_Install\_List\_Table::ajax\_user\_can(): bool
=========================================================
bool
File: `wp-admin/includes/class-wp-plugin-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugin-install-list-table.php/)
```
public function ajax_user_can() {
return current_user_can( 'install_plugins' );
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
wordpress WP_Plugin_Install_List_Table::display_rows() WP\_Plugin\_Install\_List\_Table::display\_rows()
=================================================
File: `wp-admin/includes/class-wp-plugin-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugin-install-list-table.php/)
```
public function display_rows() {
$plugins_allowedtags = array(
'a' => array(
'href' => array(),
'title' => array(),
'target' => array(),
),
'abbr' => array( 'title' => array() ),
'acronym' => array( 'title' => array() ),
'code' => array(),
'pre' => array(),
'em' => array(),
'strong' => array(),
'ul' => array(),
'ol' => array(),
'li' => array(),
'p' => array(),
'br' => array(),
);
$plugins_group_titles = array(
'Performance' => _x( 'Performance', 'Plugin installer group title' ),
'Social' => _x( 'Social', 'Plugin installer group title' ),
'Tools' => _x( 'Tools', 'Plugin installer group title' ),
);
$group = null;
foreach ( (array) $this->items as $plugin ) {
if ( is_object( $plugin ) ) {
$plugin = (array) $plugin;
}
// Display the group heading if there is one.
if ( isset( $plugin['group'] ) && $plugin['group'] !== $group ) {
if ( isset( $this->groups[ $plugin['group'] ] ) ) {
$group_name = $this->groups[ $plugin['group'] ];
if ( isset( $plugins_group_titles[ $group_name ] ) ) {
$group_name = $plugins_group_titles[ $group_name ];
}
} else {
$group_name = $plugin['group'];
}
// Starting a new group, close off the divs of the last one.
if ( ! empty( $group ) ) {
echo '</div></div>';
}
echo '<div class="plugin-group"><h3>' . esc_html( $group_name ) . '</h3>';
// Needs an extra wrapping div for nth-child selectors to work.
echo '<div class="plugin-items">';
$group = $plugin['group'];
}
$title = wp_kses( $plugin['name'], $plugins_allowedtags );
// Remove any HTML from the description.
$description = strip_tags( $plugin['short_description'] );
/**
* Filters the plugin card description on the Add Plugins screen.
*
* @since 6.0.0
*
* @param string $description Plugin card description.
* @param array $plugin An array of plugin data. See {@see plugins_api()}
* for the list of possible values.
*/
$description = apply_filters( 'plugin_install_description', $description, $plugin );
$version = wp_kses( $plugin['version'], $plugins_allowedtags );
$name = strip_tags( $title . ' ' . $version );
$author = wp_kses( $plugin['author'], $plugins_allowedtags );
if ( ! empty( $author ) ) {
/* translators: %s: Plugin author. */
$author = ' <cite>' . sprintf( __( 'By %s' ), $author ) . '</cite>';
}
$requires_php = isset( $plugin['requires_php'] ) ? $plugin['requires_php'] : null;
$requires_wp = isset( $plugin['requires'] ) ? $plugin['requires'] : null;
$compatible_php = is_php_version_compatible( $requires_php );
$compatible_wp = is_wp_version_compatible( $requires_wp );
$tested_wp = ( empty( $plugin['tested'] ) || version_compare( get_bloginfo( 'version' ), $plugin['tested'], '<=' ) );
$action_links = array();
if ( current_user_can( 'install_plugins' ) || current_user_can( 'update_plugins' ) ) {
$status = install_plugin_install_status( $plugin );
switch ( $status['status'] ) {
case 'install':
if ( $status['url'] ) {
if ( $compatible_php && $compatible_wp ) {
$action_links[] = sprintf(
'<a class="install-now button" data-slug="%s" href="%s" aria-label="%s" data-name="%s">%s</a>',
esc_attr( $plugin['slug'] ),
esc_url( $status['url'] ),
/* translators: %s: Plugin name and version. */
esc_attr( sprintf( _x( 'Install %s now', 'plugin' ), $name ) ),
esc_attr( $name ),
__( 'Install Now' )
);
} else {
$action_links[] = sprintf(
'<button type="button" class="button button-disabled" disabled="disabled">%s</button>',
_x( 'Cannot Install', 'plugin' )
);
}
}
break;
case 'update_available':
if ( $status['url'] ) {
if ( $compatible_php && $compatible_wp ) {
$action_links[] = sprintf(
'<a class="update-now button aria-button-if-js" data-plugin="%s" data-slug="%s" href="%s" aria-label="%s" data-name="%s">%s</a>',
esc_attr( $status['file'] ),
esc_attr( $plugin['slug'] ),
esc_url( $status['url'] ),
/* translators: %s: Plugin name and version. */
esc_attr( sprintf( _x( 'Update %s now', 'plugin' ), $name ) ),
esc_attr( $name ),
__( 'Update Now' )
);
} else {
$action_links[] = sprintf(
'<button type="button" class="button button-disabled" disabled="disabled">%s</button>',
_x( 'Cannot Update', 'plugin' )
);
}
}
break;
case 'latest_installed':
case 'newer_installed':
if ( is_plugin_active( $status['file'] ) ) {
$action_links[] = sprintf(
'<button type="button" class="button button-disabled" disabled="disabled">%s</button>',
_x( 'Active', 'plugin' )
);
} elseif ( current_user_can( 'activate_plugin', $status['file'] ) ) {
if ( $compatible_php && $compatible_wp ) {
$button_text = __( 'Activate' );
/* translators: %s: Plugin name. */
$button_label = _x( 'Activate %s', 'plugin' );
$activate_url = add_query_arg(
array(
'_wpnonce' => wp_create_nonce( 'activate-plugin_' . $status['file'] ),
'action' => 'activate',
'plugin' => $status['file'],
),
network_admin_url( 'plugins.php' )
);
if ( is_network_admin() ) {
$button_text = __( 'Network Activate' );
/* translators: %s: Plugin name. */
$button_label = _x( 'Network Activate %s', 'plugin' );
$activate_url = add_query_arg( array( 'networkwide' => 1 ), $activate_url );
}
$action_links[] = sprintf(
'<a href="%1$s" class="button activate-now" aria-label="%2$s">%3$s</a>',
esc_url( $activate_url ),
esc_attr( sprintf( $button_label, $plugin['name'] ) ),
$button_text
);
} else {
$action_links[] = sprintf(
'<button type="button" class="button button-disabled" disabled="disabled">%s</button>',
_x( 'Cannot Activate', 'plugin' )
);
}
} else {
$action_links[] = sprintf(
'<button type="button" class="button button-disabled" disabled="disabled">%s</button>',
_x( 'Installed', 'plugin' )
);
}
break;
}
}
$details_link = self_admin_url(
'plugin-install.php?tab=plugin-information&plugin=' . $plugin['slug'] .
'&TB_iframe=true&width=600&height=550'
);
$action_links[] = sprintf(
'<a href="%s" class="thickbox open-plugin-details-modal" aria-label="%s" data-title="%s">%s</a>',
esc_url( $details_link ),
/* translators: %s: Plugin name and version. */
esc_attr( sprintf( __( 'More information about %s' ), $name ) ),
esc_attr( $name ),
__( 'More Details' )
);
if ( ! empty( $plugin['icons']['svg'] ) ) {
$plugin_icon_url = $plugin['icons']['svg'];
} elseif ( ! empty( $plugin['icons']['2x'] ) ) {
$plugin_icon_url = $plugin['icons']['2x'];
} elseif ( ! empty( $plugin['icons']['1x'] ) ) {
$plugin_icon_url = $plugin['icons']['1x'];
} else {
$plugin_icon_url = $plugin['icons']['default'];
}
/**
* Filters the install action links for a plugin.
*
* @since 2.7.0
*
* @param string[] $action_links An array of plugin action links.
* Defaults are links to Details and Install Now.
* @param array $plugin An array of plugin data. See {@see plugins_api()}
* for the list of possible values.
*/
$action_links = apply_filters( 'plugin_install_action_links', $action_links, $plugin );
$last_updated_timestamp = strtotime( $plugin['last_updated'] );
?>
<div class="plugin-card plugin-card-<?php echo sanitize_html_class( $plugin['slug'] ); ?>">
<?php
if ( ! $compatible_php || ! $compatible_wp ) {
echo '<div class="notice inline notice-error notice-alt"><p>';
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>';
}
?>
<div class="plugin-card-top">
<div class="name column-name">
<h3>
<a href="<?php echo esc_url( $details_link ); ?>" class="thickbox open-plugin-details-modal">
<?php echo $title; ?>
<img src="<?php echo esc_url( $plugin_icon_url ); ?>" class="plugin-icon" alt="" />
</a>
</h3>
</div>
<div class="action-links">
<?php
if ( $action_links ) {
echo '<ul class="plugin-action-buttons"><li>' . implode( '</li><li>', $action_links ) . '</li></ul>';
}
?>
</div>
<div class="desc column-description">
<p><?php echo $description; ?></p>
<p class="authors"><?php echo $author; ?></p>
</div>
</div>
<div class="plugin-card-bottom">
<div class="vers column-rating">
<?php
wp_star_rating(
array(
'rating' => $plugin['rating'],
'type' => 'percent',
'number' => $plugin['num_ratings'],
)
);
?>
<span class="num-ratings" aria-hidden="true">(<?php echo number_format_i18n( $plugin['num_ratings'] ); ?>)</span>
</div>
<div class="column-updated">
<strong><?php _e( 'Last Updated:' ); ?></strong>
<?php
/* translators: %s: Human-readable time difference. */
printf( __( '%s ago' ), human_time_diff( $last_updated_timestamp ) );
?>
</div>
<div class="column-downloaded">
<?php
if ( $plugin['active_installs'] >= 1000000 ) {
$active_installs_millions = floor( $plugin['active_installs'] / 1000000 );
$active_installs_text = sprintf(
/* translators: %s: Number of millions. */
_nx( '%s+ Million', '%s+ Million', $active_installs_millions, 'Active plugin installations' ),
number_format_i18n( $active_installs_millions )
);
} elseif ( 0 === $plugin['active_installs'] ) {
$active_installs_text = _x( 'Less Than 10', 'Active plugin installations' );
} else {
$active_installs_text = number_format_i18n( $plugin['active_installs'] ) . '+';
}
/* translators: %s: Number of installations. */
printf( __( '%s Active Installations' ), $active_installs_text );
?>
</div>
<div class="column-compatibility">
<?php
if ( ! $tested_wp ) {
echo '<span class="compatibility-untested">' . __( 'Untested with your version of WordPress' ) . '</span>';
} elseif ( ! $compatible_wp ) {
echo '<span class="compatibility-incompatible">' . __( '<strong>Incompatible</strong> with your version of WordPress' ) . '</span>';
} else {
echo '<span class="compatibility-compatible">' . __( '<strong>Compatible</strong> with your version of WordPress' ) . '</span>';
}
?>
</div>
</div>
</div>
<?php
}
// Close off the group divs of the last one.
if ( ! empty( $group ) ) {
echo '</div></div>';
}
}
```
[apply\_filters( 'plugin\_install\_action\_links', string[] $action\_links, array $plugin )](../../hooks/plugin_install_action_links)
Filters the install action links for a plugin.
[apply\_filters( 'plugin\_install\_description', string $description, array $plugin )](../../hooks/plugin_install_description)
Filters the plugin card description on the Add Plugins screen.
| Uses | Description |
| --- | --- |
| [is\_php\_version\_compatible()](../../functions/is_php_version_compatible) wp-includes/functions.php | Checks compatibility with the current PHP version. |
| [wp\_create\_nonce()](../../functions/wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| [human\_time\_diff()](../../functions/human_time_diff) wp-includes/formatting.php | Determines the difference between two timestamps. |
| [wp\_kses()](../../functions/wp_kses) wp-includes/kses.php | Filters text content and strips out disallowed HTML. |
| [is\_wp\_version\_compatible()](../../functions/is_wp_version_compatible) wp-includes/functions.php | Checks compatibility with the current WordPress version. |
| [is\_network\_admin()](../../functions/is_network_admin) wp-includes/load.php | Determines whether the current request is for the network administrative interface. |
| [\_nx()](../../functions/_nx) wp-includes/l10n.php | Translates and retrieves the singular or plural form based on the supplied number, with gettext context. |
| [self\_admin\_url()](../../functions/self_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for either the current site or the network depending on context. |
| [network\_admin\_url()](../../functions/network_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for the network. |
| [wp\_star\_rating()](../../functions/wp_star_rating) wp-admin/includes/template.php | Outputs a HTML element with a star rating for a given rating. |
| [is\_plugin\_active()](../../functions/is_plugin_active) wp-admin/includes/plugin.php | Determines whether a plugin is active. |
| [install\_plugin\_install\_status()](../../functions/install_plugin_install_status) wp-admin/includes/plugin-install.php | Determines the status we can perform on a plugin. |
| [wp\_update\_php\_annotation()](../../functions/wp_update_php_annotation) wp-includes/functions.php | Prints the default annotation for the web host altering the “Update PHP” page URL. |
| [wp\_get\_update\_php\_url()](../../functions/wp_get_update_php_url) wp-includes/functions.php | Gets the URL to learn more about updating the PHP version the site is running on. |
| [sanitize\_html\_class()](../../functions/sanitize_html_class) wp-includes/formatting.php | Sanitizes an HTML classname to ensure it only contains valid characters. |
| [number\_format\_i18n()](../../functions/number_format_i18n) wp-includes/functions.php | Converts float number to format based on the locale. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [get\_bloginfo()](../../functions/get_bloginfo) wp-includes/general-template.php | Retrieves information about the current site. |
| [esc\_url()](../../functions/esc_url) wp-includes/formatting.php | Checks and cleans a URL. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [\_x()](../../functions/_x) wp-includes/l10n.php | Retrieves translated string with gettext context. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| programming_docs |
wordpress WP_Plugin_Install_List_Table::get_installed_plugins(): array WP\_Plugin\_Install\_List\_Table::get\_installed\_plugins(): array
==================================================================
Return the list of known plugins.
Uses the transient data from the updates API to determine the known installed plugins.
array
File: `wp-admin/includes/class-wp-plugin-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugin-install-list-table.php/)
```
protected function get_installed_plugins() {
$plugins = array();
$plugin_info = get_site_transient( 'update_plugins' );
if ( isset( $plugin_info->no_update ) ) {
foreach ( $plugin_info->no_update as $plugin ) {
if ( isset( $plugin->slug ) ) {
$plugin->upgrade = false;
$plugins[ $plugin->slug ] = $plugin;
}
}
}
if ( isset( $plugin_info->response ) ) {
foreach ( $plugin_info->response as $plugin ) {
if ( isset( $plugin->slug ) ) {
$plugin->upgrade = true;
$plugins[ $plugin->slug ] = $plugin;
}
}
}
return $plugins;
}
```
| Uses | Description |
| --- | --- |
| [get\_site\_transient()](../../functions/get_site_transient) wp-includes/option.php | Retrieves the value of a site transient. |
| Used By | Description |
| --- | --- |
| [WP\_Plugin\_Install\_List\_Table::get\_installed\_plugin\_slugs()](get_installed_plugin_slugs) wp-admin/includes/class-wp-plugin-install-list-table.php | Returns a list of slugs of installed plugins, if known. |
| [WP\_Plugin\_Install\_List\_Table::prepare\_items()](prepare_items) wp-admin/includes/class-wp-plugin-install-list-table.php | |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Plugin_Install_List_Table::no_items() WP\_Plugin\_Install\_List\_Table::no\_items()
=============================================
File: `wp-admin/includes/class-wp-plugin-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugin-install-list-table.php/)
```
public function no_items() {
if ( isset( $this->error ) ) { ?>
<div class="inline error"><p><?php echo $this->error->get_error_message(); ?></p>
<p class="hide-if-no-js"><button class="button try-again"><?php _e( 'Try Again' ); ?></button></p>
</div>
<?php } else { ?>
<div class="no-plugin-results"><?php _e( 'No plugins found. Try a different search.' ); ?></div>
<?php
}
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
wordpress WP_Plugin_Install_List_Table::get_views(): array WP\_Plugin\_Install\_List\_Table::get\_views(): array
=====================================================
array
File: `wp-admin/includes/class-wp-plugin-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugin-install-list-table.php/)
```
protected function get_views() {
global $tabs, $tab;
$display_tabs = array();
foreach ( (array) $tabs as $action => $text ) {
$display_tabs[ 'plugin-install-' . $action ] = array(
'url' => self_admin_url( 'plugin-install.php?tab=' . $action ),
'label' => $text,
'current' => $action === $tab,
);
}
// No longer a real tab.
unset( $display_tabs['plugin-install-upload'] );
return $this->get_views_links( $display_tabs );
}
```
| Uses | Description |
| --- | --- |
| [self\_admin\_url()](../../functions/self_admin_url) wp-includes/link-template.php | Retrieves the URL to the admin area for either the current site or the network depending on context. |
| Used By | Description |
| --- | --- |
| [WP\_Plugin\_Install\_List\_Table::views()](views) wp-admin/includes/class-wp-plugin-install-list-table.php | Overrides parent views so we can use the filter bar display. |
wordpress WP_Plugin_Install_List_Table::display() WP\_Plugin\_Install\_List\_Table::display()
===========================================
Displays the plugin install table.
Overrides the parent display() method to provide a different container.
File: `wp-admin/includes/class-wp-plugin-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugin-install-list-table.php/)
```
public function display() {
$singular = $this->_args['singular'];
$data_attr = '';
if ( $singular ) {
$data_attr = " data-wp-lists='list:$singular'";
}
$this->display_tablenav( 'top' );
?>
<div class="wp-list-table <?php echo implode( ' ', $this->get_table_classes() ); ?>">
<?php
$this->screen->render_screen_reader_content( 'heading_list' );
?>
<div id="the-list"<?php echo $data_attr; ?>>
<?php $this->display_rows_or_placeholder(); ?>
</div>
</div>
<?php
$this->display_tablenav( 'bottom' );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Plugin\_Install\_List\_Table::get\_table\_classes()](get_table_classes) wp-admin/includes/class-wp-plugin-install-list-table.php | |
| [WP\_Plugin\_Install\_List\_Table::display\_tablenav()](display_tablenav) wp-admin/includes/class-wp-plugin-install-list-table.php | |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Plugin_Install_List_Table::display_tablenav( string $which ) WP\_Plugin\_Install\_List\_Table::display\_tablenav( string $which )
====================================================================
`$which` string Required File: `wp-admin/includes/class-wp-plugin-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugin-install-list-table.php/)
```
protected function display_tablenav( $which ) {
if ( 'featured' === $GLOBALS['tab'] ) {
return;
}
if ( 'top' === $which ) {
wp_referer_field();
?>
<div class="tablenav top">
<div class="alignleft actions">
<?php
/**
* Fires before the Plugin Install table header pagination is displayed.
*
* @since 2.7.0
*/
do_action( 'install_plugins_table_header' );
?>
</div>
<?php $this->pagination( $which ); ?>
<br class="clear" />
</div>
<?php } else { ?>
<div class="tablenav bottom">
<?php $this->pagination( $which ); ?>
<br class="clear" />
</div>
<?php
}
}
```
[do\_action( 'install\_plugins\_table\_header' )](../../hooks/install_plugins_table_header)
Fires before the Plugin Install table header pagination is displayed.
| Uses | Description |
| --- | --- |
| [wp\_referer\_field()](../../functions/wp_referer_field) wp-includes/functions.php | Retrieves or displays referer hidden field for forms. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Plugin\_Install\_List\_Table::display()](display) wp-admin/includes/class-wp-plugin-install-list-table.php | Displays the plugin install table. |
wordpress WP_Plugin_Install_List_Table::get_table_classes(): array WP\_Plugin\_Install\_List\_Table::get\_table\_classes(): array
==============================================================
array
File: `wp-admin/includes/class-wp-plugin-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugin-install-list-table.php/)
```
protected function get_table_classes() {
return array( 'widefat', $this->_args['plural'] );
}
```
| Used By | Description |
| --- | --- |
| [WP\_Plugin\_Install\_List\_Table::display()](display) wp-admin/includes/class-wp-plugin-install-list-table.php | Displays the plugin install table. |
wordpress WP_Plugin_Install_List_Table::order_callback( object $plugin_a, object $plugin_b ): int WP\_Plugin\_Install\_List\_Table::order\_callback( object $plugin\_a, object $plugin\_b ): int
==============================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
`$plugin_a` object Required `$plugin_b` object Required int
File: `wp-admin/includes/class-wp-plugin-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugin-install-list-table.php/)
```
private function order_callback( $plugin_a, $plugin_b ) {
$orderby = $this->orderby;
if ( ! isset( $plugin_a->$orderby, $plugin_b->$orderby ) ) {
return 0;
}
$a = $plugin_a->$orderby;
$b = $plugin_b->$orderby;
if ( $a === $b ) {
return 0;
}
if ( 'DESC' === $this->order ) {
return ( $a < $b ) ? 1 : -1;
} else {
return ( $a < $b ) ? -1 : 1;
}
}
```
wordpress WP_Plugin_Install_List_Table::get_columns(): array WP\_Plugin\_Install\_List\_Table::get\_columns(): array
=======================================================
array
File: `wp-admin/includes/class-wp-plugin-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugin-install-list-table.php/)
```
public function get_columns() {
return array();
}
```
wordpress WP_Plugin_Install_List_Table::get_installed_plugin_slugs(): array WP\_Plugin\_Install\_List\_Table::get\_installed\_plugin\_slugs(): array
========================================================================
Returns a list of slugs of installed plugins, if known.
Uses the transient data from the updates API to determine the slugs of known installed plugins. This might be better elsewhere, perhaps even within [get\_plugins()](../../functions/get_plugins) .
array
File: `wp-admin/includes/class-wp-plugin-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugin-install-list-table.php/)
```
protected function get_installed_plugin_slugs() {
return array_keys( $this->get_installed_plugins() );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Plugin\_Install\_List\_Table::get\_installed\_plugins()](get_installed_plugins) wp-admin/includes/class-wp-plugin-install-list-table.php | Return the list of known plugins. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Plugin_Install_List_Table::views() WP\_Plugin\_Install\_List\_Table::views()
=========================================
Overrides parent views so we can use the filter bar display.
File: `wp-admin/includes/class-wp-plugin-install-list-table.php`. [View all references](https://developer.wordpress.org/reference/files/wp-admin/includes/class-wp-plugin-install-list-table.php/)
```
public function views() {
$views = $this->get_views();
/** This filter is documented in wp-admin/inclues/class-wp-list-table.php */
$views = apply_filters( "views_{$this->screen->id}", $views );
$this->screen->render_screen_reader_content( 'heading_views' );
?>
<div class="wp-filter">
<ul class="filter-links">
<?php
if ( ! empty( $views ) ) {
foreach ( $views as $class => $view ) {
$views[ $class ] = "\t<li class='$class'>$view";
}
echo implode( " </li>\n", $views ) . "</li>\n";
}
?>
</ul>
<?php install_search_form(); ?>
</div>
<?php
}
```
[apply\_filters( "views\_{$this->screen->id}", string[] $views )](../../hooks/views_this-screen-id)
Filters the list of available list table views.
| Uses | Description |
| --- | --- |
| [install\_search\_form()](../../functions/install_search_form) wp-admin/includes/plugin-install.php | Displays a search form for searching plugins. |
| [WP\_Plugin\_Install\_List\_Table::get\_views()](get_views) wp-admin/includes/class-wp-plugin-install-list-table.php | |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
wordpress WP_Customize_Themes_Panel::content_template() WP\_Customize\_Themes\_Panel::content\_template()
=================================================
An Underscore (JS) template for this panel’s content (but not its container).
Class variables for this panel class are available in the `data` JS object; export custom variables by overriding [WP\_Customize\_Panel::json()](../wp_customize_panel/json).
* [WP\_Customize\_Panel::print\_template()](../wp_customize_panel/print_template)
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/)
```
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 |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Customize_Themes_Panel::render_template() WP\_Customize\_Themes\_Panel::render\_template()
================================================
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.
* [WP\_Customize\_Panel::print\_template()](../wp_customize_panel/print_template)
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/)
```
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
}
```
| Uses | Description |
| --- | --- |
| [esc\_attr\_e()](../../functions/esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [\_ex()](../../functions/_ex) wp-includes/l10n.php | Displays translated string with gettext context. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_Style_Engine_CSS_Declarations::add_declaration( string $property, string $value ): WP_Style_Engine_CSS_Declarations WP\_Style\_Engine\_CSS\_Declarations::add\_declaration( string $property, string $value ): WP\_Style\_Engine\_CSS\_Declarations
===============================================================================================================================
Adds a single declaration.
`$property` string Required The CSS property. `$value` string Required The CSS value. [WP\_Style\_Engine\_CSS\_Declarations](../wp_style_engine_css_declarations) Returns the object to allow chaining methods.
File: `wp-includes/style-engine/class-wp-style-engine-css-declarations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-css-declarations.php/)
```
public function add_declaration( $property, $value ) {
// Sanitizes the property.
$property = $this->sanitize_property( $property );
// Bails early if the property is empty.
if ( empty( $property ) ) {
return $this;
}
// Trims the value. If empty, bail early.
$value = trim( $value );
if ( '' === $value ) {
return $this;
}
// Adds the declaration property/value pair.
$this->declarations[ $property ] = $value;
return $this;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Declarations::sanitize\_property()](sanitize_property) wp-includes/style-engine/class-wp-style-engine-css-declarations.php | Sanitizes property names. |
| Used By | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Declarations::add\_declarations()](add_declarations) wp-includes/style-engine/class-wp-style-engine-css-declarations.php | Adds multiple declarations. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine_CSS_Declarations::add_declarations( array $declarations ): WP_Style_Engine_CSS_Declarations WP\_Style\_Engine\_CSS\_Declarations::add\_declarations( array $declarations ): WP\_Style\_Engine\_CSS\_Declarations
====================================================================================================================
Adds multiple declarations.
`$declarations` array Required An array of declarations. [WP\_Style\_Engine\_CSS\_Declarations](../wp_style_engine_css_declarations) Returns the object to allow chaining methods.
File: `wp-includes/style-engine/class-wp-style-engine-css-declarations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-css-declarations.php/)
```
public function add_declarations( $declarations ) {
foreach ( $declarations as $property => $value ) {
$this->add_declaration( $property, $value );
}
return $this;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Declarations::add\_declaration()](add_declaration) wp-includes/style-engine/class-wp-style-engine-css-declarations.php | Adds a single declaration. |
| Used By | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Declarations::\_\_construct()](__construct) wp-includes/style-engine/class-wp-style-engine-css-declarations.php | Constructor for this object. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
| programming_docs |
wordpress WP_Style_Engine_CSS_Declarations::remove_declarations( array $properties = array() ): WP_Style_Engine_CSS_Declarations WP\_Style\_Engine\_CSS\_Declarations::remove\_declarations( array $properties = array() ): WP\_Style\_Engine\_CSS\_Declarations
===============================================================================================================================
Removes multiple declarations.
`$properties` array Optional An array of properties. Default: `array()`
[WP\_Style\_Engine\_CSS\_Declarations](../wp_style_engine_css_declarations) Returns the object to allow chaining methods.
File: `wp-includes/style-engine/class-wp-style-engine-css-declarations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-css-declarations.php/)
```
public function remove_declarations( $properties = array() ) {
foreach ( $properties as $property ) {
$this->remove_declaration( $property );
}
return $this;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Declarations::remove\_declaration()](remove_declaration) wp-includes/style-engine/class-wp-style-engine-css-declarations.php | Removes a single declaration. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine_CSS_Declarations::filter_declaration( string $property, string $value, string $spacer = '' ): string WP\_Style\_Engine\_CSS\_Declarations::filter\_declaration( string $property, string $value, string $spacer = '' ): string
=========================================================================================================================
Filters a CSS property + value pair.
`$property` string Required The CSS property. `$value` string Required The value to be filtered. `$spacer` string Optional The spacer between the colon and the value. Defaults to an empty string. Default: `''`
string The filtered declaration or an empty string.
File: `wp-includes/style-engine/class-wp-style-engine-css-declarations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-css-declarations.php/)
```
protected static function filter_declaration( $property, $value, $spacer = '' ) {
$filtered_value = wp_strip_all_tags( $value, true );
if ( '' !== $filtered_value ) {
return safecss_filter_attr( "{$property}:{$spacer}{$filtered_value}" );
}
return '';
}
```
| Uses | Description |
| --- | --- |
| [wp\_strip\_all\_tags()](../../functions/wp_strip_all_tags) wp-includes/formatting.php | Properly strips all HTML tags including script and style |
| [safecss\_filter\_attr()](../../functions/safecss_filter_attr) wp-includes/kses.php | Filters an inline style attribute and removes disallowed rules. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine_CSS_Declarations::get_declarations(): array WP\_Style\_Engine\_CSS\_Declarations::get\_declarations(): array
================================================================
Gets the declarations array.
array
File: `wp-includes/style-engine/class-wp-style-engine-css-declarations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-css-declarations.php/)
```
public function get_declarations() {
return $this->declarations;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Declarations::get\_declarations\_string()](get_declarations_string) wp-includes/style-engine/class-wp-style-engine-css-declarations.php | Filters and compiles the CSS declarations. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine_CSS_Declarations::get_declarations_string( bool $should_prettify = false, number $indent_count ): string WP\_Style\_Engine\_CSS\_Declarations::get\_declarations\_string( bool $should\_prettify = false, number $indent\_count ): string
================================================================================================================================
Filters and compiles the CSS declarations.
`$should_prettify` bool Optional Whether to add spacing, new lines and indents. Default: `false`
`$indent_count` number Required The number of tab indents to apply to the rule. Applies if `prettify` is `true`. string The CSS declarations.
File: `wp-includes/style-engine/class-wp-style-engine-css-declarations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-css-declarations.php/)
```
public function get_declarations_string( $should_prettify = false, $indent_count = 0 ) {
$declarations_array = $this->get_declarations();
$declarations_output = '';
$indent = $should_prettify ? str_repeat( "\t", $indent_count ) : '';
$suffix = $should_prettify ? ' ' : '';
$suffix = $should_prettify && $indent_count > 0 ? "\n" : $suffix;
$spacer = $should_prettify ? ' ' : '';
foreach ( $declarations_array as $property => $value ) {
$filtered_declaration = static::filter_declaration( $property, $value, $spacer );
if ( $filtered_declaration ) {
$declarations_output .= "{$indent}{$filtered_declaration};$suffix";
}
}
return rtrim( $declarations_output );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Declarations::get\_declarations()](get_declarations) wp-includes/style-engine/class-wp-style-engine-css-declarations.php | Gets the declarations array. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine_CSS_Declarations::remove_declaration( string $property ): WP_Style_Engine_CSS_Declarations WP\_Style\_Engine\_CSS\_Declarations::remove\_declaration( string $property ): WP\_Style\_Engine\_CSS\_Declarations
===================================================================================================================
Removes a single declaration.
`$property` string Required The CSS property. [WP\_Style\_Engine\_CSS\_Declarations](../wp_style_engine_css_declarations) Returns the object to allow chaining methods.
File: `wp-includes/style-engine/class-wp-style-engine-css-declarations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-css-declarations.php/)
```
public function remove_declaration( $property ) {
unset( $this->declarations[ $property ] );
return $this;
}
```
| Used By | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Declarations::remove\_declarations()](remove_declarations) wp-includes/style-engine/class-wp-style-engine-css-declarations.php | Removes multiple declarations. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine_CSS_Declarations::__construct( string[] $declarations = array() ) WP\_Style\_Engine\_CSS\_Declarations::\_\_construct( string[] $declarations = array() )
=======================================================================================
Constructor for this object.
If a `$declarations` array is passed, it will be used to populate the initial $declarations prop of the object by calling add\_declarations().
`$declarations` string[] Optional An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ). Default: `array()`
File: `wp-includes/style-engine/class-wp-style-engine-css-declarations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-css-declarations.php/)
```
public function __construct( $declarations = array() ) {
$this->add_declarations( $declarations );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Declarations::add\_declarations()](add_declarations) wp-includes/style-engine/class-wp-style-engine-css-declarations.php | Adds multiple declarations. |
| Used By | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Rule::add\_declarations()](../wp_style_engine_css_rule/add_declarations) wp-includes/style-engine/class-wp-style-engine-css-rule.php | Sets the declarations. |
| [WP\_Style\_Engine::compile\_css()](../wp_style_engine/compile_css) wp-includes/style-engine/class-wp-style-engine.php | Returns compiled CSS from css\_declarations. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress WP_Style_Engine_CSS_Declarations::sanitize_property( string $property ): string WP\_Style\_Engine\_CSS\_Declarations::sanitize\_property( string $property ): string
====================================================================================
Sanitizes property names.
`$property` string Required The CSS property. string The sanitized property name.
File: `wp-includes/style-engine/class-wp-style-engine-css-declarations.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/style-engine/class-wp-style-engine-css-declarations.php/)
```
protected function sanitize_property( $property ) {
return sanitize_key( $property );
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_key()](../../functions/sanitize_key) wp-includes/formatting.php | Sanitizes a string key. |
| Used By | Description |
| --- | --- |
| [WP\_Style\_Engine\_CSS\_Declarations::add\_declaration()](add_declaration) wp-includes/style-engine/class-wp-style-engine-css-declarations.php | Adds a single declaration. |
| Version | Description |
| --- | --- |
| [6.1.0](https://developer.wordpress.org/reference/since/6.1.0/) | Introduced. |
wordpress IXR_Message::cdata( $parser, $cdata ) IXR\_Message::cdata( $parser, $cdata )
======================================
File: `wp-includes/IXR/class-IXR-message.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-message.php/)
```
function cdata($parser, $cdata)
{
$this->_currentTagContents .= $cdata;
}
```
wordpress IXR_Message::IXR_Message( $message ) IXR\_Message::IXR\_Message( $message )
======================================
PHP4 constructor.
File: `wp-includes/IXR/class-IXR-message.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-message.php/)
```
public function IXR_Message( $message ) {
self::__construct( $message );
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Message::\_\_construct()](__construct) wp-includes/IXR/class-IXR-message.php | PHP5 constructor. |
wordpress IXR_Message::tag_open( $parser, $tag, $attr ) IXR\_Message::tag\_open( $parser, $tag, $attr )
===============================================
File: `wp-includes/IXR/class-IXR-message.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-message.php/)
```
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;
}
}
```
wordpress IXR_Message::__construct( $message ) IXR\_Message::\_\_construct( $message )
=======================================
PHP5 constructor.
File: `wp-includes/IXR/class-IXR-message.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-message.php/)
```
function __construct( $message )
{
$this->message =& $message;
}
```
| Used By | Description |
| --- | --- |
| [IXR\_Server::serve()](../ixr_server/serve) wp-includes/IXR/class-IXR-server.php | |
| [IXR\_Client::query()](../ixr_client/query) wp-includes/IXR/class-IXR-client.php | |
| [IXR\_Message::IXR\_Message()](ixr_message) wp-includes/IXR/class-IXR-message.php | PHP4 constructor. |
| [WP\_HTTP\_IXR\_Client::query()](../wp_http_ixr_client/query) wp-includes/class-wp-http-ixr-client.php | |
wordpress IXR_Message::tag_close( $parser, $tag ) IXR\_Message::tag\_close( $parser, $tag )
=========================================
File: `wp-includes/IXR/class-IXR-message.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-message.php/)
```
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 = '';
}
```
| Uses | Description |
| --- | --- |
| [IXR\_Date::\_\_construct()](../ixr_date/__construct) wp-includes/IXR/class-IXR-date.php | PHP5 constructor. |
wordpress IXR_Message::parse() IXR\_Message::parse()
=====================
File: `wp-includes/IXR/class-IXR-message.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/ixr/class-ixr-message.php/)
```
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;
}
```
[apply\_filters( 'xmlrpc\_chunk\_parsing\_size', int $chunk\_size )](../../hooks/xmlrpc_chunk_parsing_size)
Filters the chunk size that can be used to parse an XML-RPC response message.
[apply\_filters( 'xmlrpc\_element\_limit', int $element\_limit )](../../hooks/xmlrpc_element_limit)
Filters the number of elements to parse in an XML-RPC response.
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| programming_docs |
wordpress WP_Comment_Query::parse_order( string $order ): string WP\_Comment\_Query::parse\_order( string $order ): string
=========================================================
Parse an ‘order’ query variable and cast it to ASC or DESC as necessary.
`$order` string Required The `'order'` query variable. string The sanitized `'order'` query variable.
File: `wp-includes/class-wp-comment-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment-query.php/)
```
protected function parse_order( $order ) {
if ( ! is_string( $order ) || empty( $order ) ) {
return 'DESC';
}
if ( 'ASC' === strtoupper( $order ) ) {
return 'ASC';
} else {
return 'DESC';
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Comment\_Query::get\_comment\_ids()](get_comment_ids) wp-includes/class-wp-comment-query.php | Used internally to get a list of comment IDs matching the query vars. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_Comment_Query::__call( string $name, array $arguments ): mixed|false WP\_Comment\_Query::\_\_call( string $name, array $arguments ): mixed|false
===========================================================================
Make private/protected methods readable for backward compatibility.
`$name` string Required Method to call. `$arguments` array Required Arguments to pass when calling. mixed|false Return value of the callback, false otherwise.
File: `wp-includes/class-wp-comment-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment-query.php/)
```
public function __call( $name, $arguments ) {
if ( 'get_search_sql' === $name ) {
return $this->get_search_sql( ...$arguments );
}
return false;
}
```
| Uses | Description |
| --- | --- |
| [WP\_Comment\_Query::get\_search\_sql()](get_search_sql) wp-includes/class-wp-comment-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| Version | Description |
| --- | --- |
| [4.0.0](https://developer.wordpress.org/reference/since/4.0.0/) | Introduced. |
wordpress WP_Comment_Query::parse_orderby( string $orderby ): string|false WP\_Comment\_Query::parse\_orderby( string $orderby ): string|false
===================================================================
Parse and sanitize ‘orderby’ keys passed to the comment query.
`$orderby` string Required Alias for the field to order by. string|false Value to used in the ORDER clause. False otherwise.
File: `wp-includes/class-wp-comment-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment-query.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [esc\_sql()](../../functions/esc_sql) wp-includes/formatting.php | Escapes data for use in a MySQL query. |
| Used By | Description |
| --- | --- |
| [WP\_Comment\_Query::get\_comment\_ids()](get_comment_ids) wp-includes/class-wp-comment-query.php | Used internally to get a list of comment IDs matching the query vars. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_Comment_Query::get_comment_ids(): int|array WP\_Comment\_Query::get\_comment\_ids(): int|array
==================================================
Used internally to get a list of comment IDs matching the query vars.
int|array A single count of comment IDs if a count query. An array of comment IDs if a full query.
File: `wp-includes/class-wp-comment-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment-query.php/)
```
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 );
}
}
```
[apply\_filters\_ref\_array( 'comments\_clauses', string[] $clauses, WP\_Comment\_Query $query )](../../hooks/comments_clauses)
Filters the comment query clauses.
| Uses | Description |
| --- | --- |
| [wp\_parse\_list()](../../functions/wp_parse_list) wp-includes/functions.php | Converts a comma- or space-separated list of scalar values to an array. |
| [WP\_Comment\_Query::parse\_orderby()](parse_orderby) wp-includes/class-wp-comment-query.php | Parse and sanitize ‘orderby’ keys passed to the comment query. |
| [WP\_Comment\_Query::parse\_order()](parse_order) wp-includes/class-wp-comment-query.php | Parse an ‘order’ query variable and cast it to ASC or DESC as necessary. |
| [wp\_parse\_id\_list()](../../functions/wp_parse_id_list) wp-includes/functions.php | Cleans up an array, comma- or space-separated list of IDs. |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| [WP\_Date\_Query::\_\_construct()](../wp_date_query/__construct) wp-includes/class-wp-date-query.php | Constructor. |
| [apply\_filters\_ref\_array()](../../functions/apply_filters_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook, specifying arguments in an array. |
| [wpdb::get\_col()](../wpdb/get_col) wp-includes/class-wpdb.php | Retrieves one column from the database. |
| [WP\_Comment\_Query::get\_search\_sql()](get_search_sql) wp-includes/class-wp-comment-query.php | Used internally to generate an SQL string for searching across multiple columns. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| [wpdb::get\_var()](../wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_Comment\_Query::get\_comments()](get_comments) wp-includes/class-wp-comment-query.php | Get a list of comments matching the query vars. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
| programming_docs |
wordpress WP_Comment_Query::query( string|array $query ): array|int WP\_Comment\_Query::query( string|array $query ): array|int
===========================================================
Sets up the WordPress query for retrieving comments.
`$query` string|array Required Array or URL query string of parameters. array|int List of comments, or number of comments when `'count'` is passed as a query var.
File: `wp-includes/class-wp-comment-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment-query.php/)
```
public function query( $query ) {
$this->query_vars = wp_parse_args( $query );
return $this->get_comments();
}
```
| Uses | Description |
| --- | --- |
| [WP\_Comment\_Query::get\_comments()](get_comments) wp-includes/class-wp-comment-query.php | Get a list of comments matching the query vars. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Used By | Description |
| --- | --- |
| [WP\_Comment\_Query::\_\_construct()](__construct) wp-includes/class-wp-comment-query.php | Constructor. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Moved parsing to [WP\_Comment\_Query::parse\_query()](parse_query). |
| [4.1.0](https://developer.wordpress.org/reference/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. |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
wordpress WP_Comment_Query::parse_query( string|array $query = '' ) WP\_Comment\_Query::parse\_query( string|array $query = '' )
============================================================
Parse arguments passed to the comment query with default query parameters.
`$query` string|array Optional [WP\_Comment\_Query](../wp_comment_query) arguments. See [WP\_Comment\_Query::\_\_construct()](__construct) More Arguments from WP\_Comment\_Query::\_\_construct( ... $query ) Array or query string of comment query parameters.
* `author_email`stringComment author email address.
* `author_url`stringComment author URL.
* `author__in`int[]Array of author IDs to include comments for.
* `author__not_in`int[]Array of author IDs to exclude comments for.
* `comment__in`int[]Array of comment IDs to include.
* `comment__not_in`int[]Array of comment IDs to exclude.
* `count`boolWhether to return a comment count (true) or array of comment objects (false). Default false.
* `date_query`arrayDate query clauses to limit comments by. See [WP\_Date\_Query](../wp_date_query).
Default null.
* `fields`stringComment fields to return. Accepts `'ids'` for comment IDs only or empty for all fields.
* `include_unapproved`arrayArray of IDs or email addresses of users whose unapproved comments will be returned by the query regardless of `$status`.
* `karma`intKarma score to retrieve matching comments for.
* `meta_key`string|string[]Meta key or keys to filter by.
* `meta_value`string|string[]Meta value or values to filter by.
* `meta_compare`stringMySQL operator used for comparing the meta value.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_compare_key`stringMySQL operator used for comparing the meta key.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_type`stringMySQL data type that the meta\_value column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_type_key`stringMySQL data type that the meta\_key column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_query`arrayAn associative array of [WP\_Meta\_Query](../wp_meta_query) arguments.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values.
* `number`intMaximum number of comments to retrieve.
Default empty (no limit).
* `paged`intWhen used with `$number`, defines the page of results to return.
When used with `$offset`, `$offset` takes precedence. Default 1.
* `offset`intNumber of comments to offset the query. Used to build LIMIT clause. Default 0.
* `no_found_rows`boolWhether to disable the `SQL_CALC_FOUND_ROWS` query.
Default: true.
* `orderby`string|arrayComment status or array of statuses. To use `'meta_value'` or `'meta_value_num'`, `$meta_key` must also be defined.
To sort by a specific `$meta_query` clause, use that clause's array key. Accepts:
+ `'comment_agent'`
+ `'comment_approved'`
+ `'comment_author'`
+ `'comment_author_email'`
+ `'comment_author_IP'`
+ `'comment_author_url'`
+ `'comment_content'`
+ `'comment_date'`
+ `'comment_date_gmt'`
+ `'comment_ID'`
+ `'comment_karma'`
+ `'comment_parent'`
+ `'comment_post_ID'`
+ `'comment_type'`
+ `'user_id'`
+ `'comment__in'`
+ `'meta_value'`
+ `'meta_value_num'`
+ The value of `$meta_key`
+ The array keys of `$meta_query`
+ false, an empty array, or `'none'` to disable `ORDER BY` clause. Default: `'comment_date_gmt'`.
* `order`stringHow to order retrieved comments. Accepts `'ASC'`, `'DESC'`.
Default: `'DESC'`.
* `parent`intParent ID of comment to retrieve children of.
* `parent__in`int[]Array of parent IDs of comments to retrieve children for.
* `parent__not_in`int[]Array of parent IDs of comments \*not\* to retrieve children for.
* `post_author__in`int[]Array of author IDs to retrieve comments for.
* `post_author__not_in`int[]Array of author IDs \*not\* to retrieve comments for.
* `post_id`intLimit results to those affiliated with a given post ID.
Default 0.
* `post__in`int[]Array of post IDs to include affiliated comments for.
* `post__not_in`int[]Array of post IDs to exclude affiliated comments for.
* `post_author`intPost author ID to limit results by.
* `post_status`string|string[]Post status or array of post statuses to retrieve affiliated comments for. Pass `'any'` to match any value.
* `post_type`string|string[]Post type or array of post types to retrieve affiliated comments for. Pass `'any'` to match any value.
* `post_name`stringPost name to retrieve affiliated comments for.
* `post_parent`intPost parent ID to retrieve affiliated comments for.
* `search`stringSearch term(s) to retrieve matching comments for.
* `status`string|arrayComment statuses to limit results by. Accepts an array or space/comma-separated list of `'hold'` (`comment_status=0`), `'approve'` (`comment_status=1`), `'all'`, or a custom comment status. Default `'all'`.
* `type`string|string[]Include comments of a given type, or array of types.
Accepts `'comment'`, `'pings'` (includes `'pingback'` and `'trackback'`), or any custom type string.
* `type__in`string[]Include comments from a given array of comment types.
* `type__not_in`string[]Exclude comments from a given array of comment types.
* `user_id`intInclude comments for a specific user ID.
* `hierarchical`bool|stringWhether to include comment descendants in the results.
+ `'threaded'` returns a tree, with each comment's children stored in a `children` property on the `WP_Comment` object.
+ `'flat'` returns a flat array of found comments plus their children.
+ Boolean `false` leaves out descendants. The parameter is ignored (forced to `false`) when `$fields` is `'ids'` or `'counts'`. Accepts `'threaded'`, `'flat'`, or false. Default: false.
* `cache_domain`stringUnique cache key to be produced when this query is stored in an object cache. Default is `'core'`.
* `update_comment_meta_cache`boolWhether to prime the metadata cache for found comments.
Default true.
* `update_comment_post_cache`boolWhether to prime the cache for comment posts.
Default false.
Default: `''`
File: `wp-includes/class-wp-comment-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment-query.php/)
```
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 ) );
}
```
[do\_action\_ref\_array( 'parse\_comment\_query', WP\_Comment\_Query $query )](../../hooks/parse_comment_query)
Fires after the comment query vars have been parsed.
| Uses | Description |
| --- | --- |
| [do\_action\_ref\_array()](../../functions/do_action_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook, specifying arguments in an array. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Used By | Description |
| --- | --- |
| [WP\_Comment\_Query::get\_comments()](get_comments) wp-includes/class-wp-comment-query.php | Get a list of comments matching the query vars. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_Comment_Query::get_comments(): int|int[]|WP_Comment[] WP\_Comment\_Query::get\_comments(): int|int[]|WP\_Comment[]
============================================================
Get a list of comments matching the query vars.
int|int[]|[WP\_Comment](../wp_comment)[] List of comments or number of found comments if `$count` argument is true.
File: `wp-includes/class-wp-comment-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment-query.php/)
```
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;
}
```
[apply\_filters\_ref\_array( 'comments\_pre\_query', array|int|null $comment\_data, WP\_Comment\_Query $query )](../../hooks/comments_pre_query)
Filters the comments data before the query takes place.
[do\_action\_ref\_array( 'pre\_get\_comments', WP\_Comment\_Query $query )](../../hooks/pre_get_comments)
Fires before comments are retrieved.
[apply\_filters\_ref\_array( 'the\_comments', WP\_Comment[] $\_comments, WP\_Comment\_Query $query )](../../hooks/the_comments)
Filters the comment query results.
| Uses | Description |
| --- | --- |
| [wp\_cache\_get\_last\_changed()](../../functions/wp_cache_get_last_changed) wp-includes/functions.php | Gets last changed date for the specified cache group. |
| [WP\_Comment\_Query::set\_found\_comments()](set_found_comments) wp-includes/class-wp-comment-query.php | Populates found\_comments and max\_num\_pages properties for the current query if the limit clause was used. |
| [WP\_Comment\_Query::get\_comment\_ids()](get_comment_ids) wp-includes/class-wp-comment-query.php | Used internally to get a list of comment IDs matching the query vars. |
| [WP\_Comment\_Query::fill\_descendants()](fill_descendants) wp-includes/class-wp-comment-query.php | Fetch descendants for located comments. |
| [\_prime\_comment\_caches()](../../functions/_prime_comment_caches) wp-includes/comment.php | Adds any comments from the given IDs to the cache that do not already exist in cache. |
| [WP\_Comment\_Query::parse\_query()](parse_query) wp-includes/class-wp-comment-query.php | Parse arguments passed to the comment query with default query parameters. |
| [wp\_cache\_add()](../../functions/wp_cache_add) wp-includes/cache.php | Adds data to the cache, if the cache key doesn’t already exist. |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| [do\_action\_ref\_array()](../../functions/do_action_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook, specifying arguments in an array. |
| [apply\_filters\_ref\_array()](../../functions/apply_filters_ref_array) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook, specifying arguments in an array. |
| [\_prime\_post\_caches()](../../functions/_prime_post_caches) wp-includes/post.php | Adds any posts from the given IDs to the cache that do not already exist in cache. |
| [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) wp-includes/class-wp-meta-query.php | Constructor. |
| [wp\_cache\_get()](../../functions/wp_cache_get) wp-includes/cache.php | Retrieves the cache contents from the cache by key and group. |
| [get\_comment()](../../functions/get_comment) wp-includes/comment.php | Retrieves comment data given a comment ID or comment object. |
| Used By | Description |
| --- | --- |
| [WP\_Comment\_Query::query()](query) wp-includes/class-wp-comment-query.php | Sets up the WordPress query for retrieving comments. |
| Version | Description |
| --- | --- |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_Comment_Query::get_search_sql( string $search, string[] $columns ): string WP\_Comment\_Query::get\_search\_sql( string $search, string[] $columns ): string
=================================================================================
Used internally to generate an SQL string for searching across multiple columns.
`$search` string Required Search string. `$columns` string[] Required Array of columns to search. string Search SQL.
File: `wp-includes/class-wp-comment-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment-query.php/)
```
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 ) . ')';
}
```
| Uses | Description |
| --- | --- |
| [wpdb::esc\_like()](../wpdb/esc_like) wp-includes/class-wpdb.php | First half of escaping for `LIKE` special characters `%` and `_` before preparing for SQL. |
| [wpdb::prepare()](../wpdb/prepare) wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
| Used By | Description |
| --- | --- |
| [WP\_Comment\_Query::get\_comment\_ids()](get_comment_ids) wp-includes/class-wp-comment-query.php | Used internally to get a list of comment IDs matching the query vars. |
| [WP\_Comment\_Query::\_\_call()](__call) wp-includes/class-wp-comment-query.php | Make private/protected methods readable for backward compatibility. |
| Version | Description |
| --- | --- |
| [3.1.0](https://developer.wordpress.org/reference/since/3.1.0/) | Introduced. |
| programming_docs |
wordpress WP_Comment_Query::set_found_comments() WP\_Comment\_Query::set\_found\_comments()
==========================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Populates 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/)
```
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 );
}
}
```
[apply\_filters( 'found\_comments\_query', string $found\_comments\_query, WP\_Comment\_Query $comment\_query )](../../hooks/found_comments_query)
Filters the query used to retrieve found comment count.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [wpdb::get\_var()](../wpdb/get_var) wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| Used By | Description |
| --- | --- |
| [WP\_Comment\_Query::get\_comments()](get_comments) wp-includes/class-wp-comment-query.php | Get a list of comments matching the query vars. |
| Version | Description |
| --- | --- |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced. |
wordpress WP_Comment_Query::__construct( string|array $query = '' ) WP\_Comment\_Query::\_\_construct( string|array $query = '' )
=============================================================
Constructor.
Sets up the comment query, based on the query vars passed.
`$query` string|array Optional Array or query string of comment query parameters.
* `author_email`stringComment author email address.
* `author_url`stringComment author URL.
* `author__in`int[]Array of author IDs to include comments for.
* `author__not_in`int[]Array of author IDs to exclude comments for.
* `comment__in`int[]Array of comment IDs to include.
* `comment__not_in`int[]Array of comment IDs to exclude.
* `count`boolWhether to return a comment count (true) or array of comment objects (false). Default false.
* `date_query`arrayDate query clauses to limit comments by. See [WP\_Date\_Query](../wp_date_query).
Default null.
* `fields`stringComment fields to return. Accepts `'ids'` for comment IDs only or empty for all fields.
* `include_unapproved`arrayArray of IDs or email addresses of users whose unapproved comments will be returned by the query regardless of `$status`.
* `karma`intKarma score to retrieve matching comments for.
* `meta_key`string|string[]Meta key or keys to filter by.
* `meta_value`string|string[]Meta value or values to filter by.
* `meta_compare`stringMySQL operator used for comparing the meta value.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_compare_key`stringMySQL operator used for comparing the meta key.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_type`stringMySQL data type that the meta\_value column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_type_key`stringMySQL data type that the meta\_key column will be CAST to for comparisons.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values and default value.
* `meta_query`arrayAn associative array of [WP\_Meta\_Query](../wp_meta_query) arguments.
See [WP\_Meta\_Query::\_\_construct()](../wp_meta_query/__construct) for accepted values.
* `number`intMaximum number of comments to retrieve.
Default empty (no limit).
* `paged`intWhen used with `$number`, defines the page of results to return.
When used with `$offset`, `$offset` takes precedence. Default 1.
* `offset`intNumber of comments to offset the query. Used to build LIMIT clause. Default 0.
* `no_found_rows`boolWhether to disable the `SQL_CALC_FOUND_ROWS` query.
Default: true.
* `orderby`string|arrayComment status or array of statuses. To use `'meta_value'` or `'meta_value_num'`, `$meta_key` must also be defined.
To sort by a specific `$meta_query` clause, use that clause's array key. Accepts:
+ `'comment_agent'`
+ `'comment_approved'`
+ `'comment_author'`
+ `'comment_author_email'`
+ `'comment_author_IP'`
+ `'comment_author_url'`
+ `'comment_content'`
+ `'comment_date'`
+ `'comment_date_gmt'`
+ `'comment_ID'`
+ `'comment_karma'`
+ `'comment_parent'`
+ `'comment_post_ID'`
+ `'comment_type'`
+ `'user_id'`
+ `'comment__in'`
+ `'meta_value'`
+ `'meta_value_num'`
+ The value of `$meta_key`
+ The array keys of `$meta_query`
+ false, an empty array, or `'none'` to disable `ORDER BY` clause. Default: `'comment_date_gmt'`.
* `order`stringHow to order retrieved comments. Accepts `'ASC'`, `'DESC'`.
Default: `'DESC'`.
* `parent`intParent ID of comment to retrieve children of.
* `parent__in`int[]Array of parent IDs of comments to retrieve children for.
* `parent__not_in`int[]Array of parent IDs of comments \*not\* to retrieve children for.
* `post_author__in`int[]Array of author IDs to retrieve comments for.
* `post_author__not_in`int[]Array of author IDs \*not\* to retrieve comments for.
* `post_id`intLimit results to those affiliated with a given post ID.
Default 0.
* `post__in`int[]Array of post IDs to include affiliated comments for.
* `post__not_in`int[]Array of post IDs to exclude affiliated comments for.
* `post_author`intPost author ID to limit results by.
* `post_status`string|string[]Post status or array of post statuses to retrieve affiliated comments for. Pass `'any'` to match any value.
* `post_type`string|string[]Post type or array of post types to retrieve affiliated comments for. Pass `'any'` to match any value.
* `post_name`stringPost name to retrieve affiliated comments for.
* `post_parent`intPost parent ID to retrieve affiliated comments for.
* `search`stringSearch term(s) to retrieve matching comments for.
* `status`string|arrayComment statuses to limit results by. Accepts an array or space/comma-separated list of `'hold'` (`comment_status=0`), `'approve'` (`comment_status=1`), `'all'`, or a custom comment status. Default `'all'`.
* `type`string|string[]Include comments of a given type, or array of types.
Accepts `'comment'`, `'pings'` (includes `'pingback'` and `'trackback'`), or any custom type string.
* `type__in`string[]Include comments from a given array of comment types.
* `type__not_in`string[]Exclude comments from a given array of comment types.
* `user_id`intInclude comments for a specific user ID.
* `hierarchical`bool|stringWhether to include comment descendants in the results.
+ `'threaded'` returns a tree, with each comment's children stored in a `children` property on the `WP_Comment` object.
+ `'flat'` returns a flat array of found comments plus their children.
+ Boolean `false` leaves out descendants. The parameter is ignored (forced to `false`) when `$fields` is `'ids'` or `'counts'`. Accepts `'threaded'`, `'flat'`, or false. Default: false.
* `cache_domain`stringUnique cache key to be produced when this query is stored in an object cache. Default is `'core'`.
* `update_comment_meta_cache`boolWhether to prime the metadata cache for found comments.
Default true.
* `update_comment_post_cache`boolWhether to prime the cache for comment posts.
Default false.
Default: `''`
File: `wp-includes/class-wp-comment-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment-query.php/)
```
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 );
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_Comment\_Query::query()](query) wp-includes/class-wp-comment-query.php | Sets up the WordPress query for retrieving comments. |
| Used By | Description |
| --- | --- |
| [build\_comment\_query\_vars\_from\_block()](../../functions/build_comment_query_vars_from_block) wp-includes/blocks.php | Helper function that constructs a comment query vars array from the passed block properties. |
| [WP\_REST\_Comments\_Controller::get\_items()](../wp_rest_comments_controller/get_items) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Retrieves a list of comment items. |
| [comments\_template()](../../functions/comments_template) wp-includes/comment-template.php | Loads the comment template specified in $file. |
| [get\_page\_of\_comment()](../../functions/get_page_of_comment) wp-includes/comment.php | Calculates what page number a comment will appear on for comment paging. |
| [get\_comments()](../../functions/get_comments) wp-includes/comment.php | Retrieves a list of comments. |
| [get\_approved\_comments()](../../functions/get_approved_comments) wp-includes/comment.php | Retrieves the approved comments for a post. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced the `$meta_type_key` argument. |
| [5.1.0](https://developer.wordpress.org/reference/since/5.1.0/) | Introduced the `$meta_compare_key` argument. |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced the `$paged` argument. |
| [4.6.0](https://developer.wordpress.org/reference/since/4.6.0/) | Introduced the `$cache_domain` argument. |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced the `$author_url` argument. |
| [4.4.0](https://developer.wordpress.org/reference/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. |
| [4.2.0](https://developer.wordpress.org/reference/since/4.2.0/) | Introduced. |
wordpress WP_Comment_Query::fill_descendants( WP_Comment[] $comments ): array WP\_Comment\_Query::fill\_descendants( WP\_Comment[] $comments ): array
=======================================================================
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.
`$comments` [WP\_Comment](../wp_comment)[] Required Array of top-level comments whose descendants should be filled in. array
File: `wp-includes/class-wp-comment-query.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/class-wp-comment-query.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [wp\_cache\_set\_multiple()](../../functions/wp_cache_set_multiple) wp-includes/cache.php | Sets multiple values to the cache in one call. |
| [wp\_cache\_get\_last\_changed()](../../functions/wp_cache_get_last_changed) wp-includes/functions.php | Gets last changed date for the specified cache group. |
| [\_prime\_comment\_caches()](../../functions/_prime_comment_caches) wp-includes/comment.php | Adds any comments from the given IDs to the cache that do not already exist in cache. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [wp\_array\_slice\_assoc()](../../functions/wp_array_slice_assoc) wp-includes/functions.php | Extracts a slice of an array, given a list of keys. |
| [get\_comments()](../../functions/get_comments) wp-includes/comment.php | Retrieves a list of comments. |
| [wp\_cache\_get()](../../functions/wp_cache_get) wp-includes/cache.php | Retrieves the cache contents from the cache by key and group. |
| [get\_comment()](../../functions/get_comment) wp-includes/comment.php | Retrieves comment data given a comment ID or comment object. |
| Used By | Description |
| --- | --- |
| [WP\_Comment\_Query::get\_comments()](get_comments) wp-includes/class-wp-comment-query.php | Get a list of comments matching the query vars. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Widget_Links::form( array $instance ) WP\_Widget\_Links::form( array $instance )
==========================================
Outputs the settings form for the Links widget.
`$instance` array Required Current settings. 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/)
```
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 |
| --- | --- |
| [\_ex()](../../functions/_ex) wp-includes/l10n.php | Displays translated string with gettext context. |
| [selected()](../../functions/selected) wp-includes/general-template.php | Outputs the HTML selected attribute. |
| [checked()](../../functions/checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [get\_terms()](../../functions/get_terms) wp-includes/taxonomy.php | Retrieves the terms in a given taxonomy or list of taxonomies. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Widget_Links::update( array $new_instance, array $old_instance ): array WP\_Widget\_Links::update( array $new\_instance, array $old\_instance ): array
==============================================================================
Handles updating settings for the current Links widget instance.
`$new_instance` array Required New settings for this instance as input by the user via [WP\_Widget::form()](../wp_widget/form). `$old_instance` array Required Old settings for this instance. array Updated settings to save.
File: `wp-includes/widgets/class-wp-widget-links.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-links.php/)
```
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;
}
```
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Links::__construct() WP\_Widget\_Links::\_\_construct()
==================================
Sets up a new 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/)
```
public function __construct() {
$widget_ops = array(
'description' => __( 'Your blogroll' ),
'customize_selective_refresh' => true,
);
parent::__construct( 'links', __( 'Links' ), $widget_ops );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget::\_\_construct()](../wp_widget/__construct) wp-includes/class-wp-widget.php | PHP5 constructor. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Links::widget( array $args, array $instance ) WP\_Widget\_Links::widget( array $args, array $instance )
=========================================================
Outputs the content for the current Links widget instance.
`$args` array Required Display arguments including `'before_title'`, `'after_title'`, `'before_widget'`, and `'after_widget'`. `$instance` array Required Settings 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/)
```
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 ) );
}
```
[apply\_filters( 'widget\_links\_args', array $widget\_links\_args, array $instance )](../../hooks/widget_links_args)
Filters the arguments for the Links widget.
| Uses | Description |
| --- | --- |
| [wp\_list\_bookmarks()](../../functions/wp_list_bookmarks) wp-includes/bookmark-template.php | Retrieves or echoes all of the bookmarks. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress File_Upload_Upgrader::cleanup(): bool File\_Upload\_Upgrader::cleanup(): bool
=======================================
Delete the attachment/uploaded file.
bool Whether the cleanup was successful.
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/)
```
public function cleanup() {
if ( $this->id ) {
wp_delete_attachment( $this->id );
} elseif ( file_exists( $this->package ) ) {
return @unlink( $this->package );
}
return true;
}
```
| Uses | Description |
| --- | --- |
| [wp\_delete\_attachment()](../../functions/wp_delete_attachment) wp-includes/post.php | Trashes or deletes an attachment. |
| Version | Description |
| --- | --- |
| [3.2.2](https://developer.wordpress.org/reference/since/3.2.2/) | Introduced. |
wordpress File_Upload_Upgrader::__construct( string $form, string $urlholder ) File\_Upload\_Upgrader::\_\_construct( string $form, string $urlholder )
========================================================================
Construct the upgrader for a form.
`$form` string Required The name of the form the file was uploaded from. `$urlholder` string Required The name of the `GET` parameter that holds the filename. 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/)
```
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' ) );
}
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_handle\_upload()](../../functions/wp_handle_upload) wp-admin/includes/file.php | Wrapper for [\_wp\_handle\_upload()](../../functions/_wp_handle_upload) . |
| [wp\_schedule\_single\_event()](../../functions/wp_schedule_single_event) wp-includes/cron.php | Schedules an event to run only once. |
| [sanitize\_file\_name()](../../functions/sanitize_file_name) wp-includes/formatting.php | Sanitizes a filename, replacing whitespace with dashes. |
| [wp\_upload\_dir()](../../functions/wp_upload_dir) wp-includes/functions.php | Returns an array containing the current upload directory’s path and URL. |
| [wp\_insert\_attachment()](../../functions/wp_insert_attachment) wp-includes/post.php | Inserts an attachment. |
| [get\_attached\_file()](../../functions/get_attached_file) wp-includes/post.php | Retrieves attached file path based on attachment ID. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [wp\_die()](../../functions/wp_die) wp-includes/functions.php | Kills WordPress execution and displays HTML page with an error message. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::upload_from_data( array $data, array $headers ): array|WP_Error WP\_REST\_Attachments\_Controller::upload\_from\_data( array $data, array $headers ): array|WP\_Error
=====================================================================================================
Handles an upload via raw POST data.
`$data` array Required Supplied file data. `$headers` array Required HTTP headers from the request. array|[WP\_Error](../wp_error) Data from [wp\_handle\_sideload()](../../functions/wp_handle_sideload) .
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::check\_upload\_size()](check_upload_size) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Determine if uploaded file exceeds space quota on multisite. |
| [WP\_REST\_Attachments\_Controller::get\_filename\_from\_disposition()](get_filename_from_disposition) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Parses filename from a Content-Disposition header value. |
| [wp\_tempnam()](../../functions/wp_tempnam) wp-admin/includes/file.php | Returns a filename of a temporary unique file. |
| [wp\_handle\_sideload()](../../functions/wp_handle_sideload) wp-admin/includes/file.php | Wrapper for [\_wp\_handle\_upload()](../../functions/_wp_handle_upload) . |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::insert\_attachment()](insert_attachment) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Inserts the attachment post in the database. Does not update the attachment meta. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::prepare_item_for_response( WP_Post $item, WP_REST_Request $request ): WP_REST_Response WP\_REST\_Attachments\_Controller::prepare\_item\_for\_response( WP\_Post $item, WP\_REST\_Request $request ): WP\_REST\_Response
=================================================================================================================================
Prepares a single attachment output for response.
`$item` [WP\_Post](../wp_post) Required Attachment object. `$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. [WP\_REST\_Response](../wp_rest_response) Response object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php/)
```
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 );
}
```
[apply\_filters( 'get\_the\_excerpt', string $post\_excerpt, WP\_Post $post )](../../hooks/get_the_excerpt)
Filters the retrieved post excerpt.
[apply\_filters( 'rest\_prepare\_attachment', WP\_REST\_Response $response, WP\_Post $post, WP\_REST\_Request $request )](../../hooks/rest_prepare_attachment)
Filters an attachment returned from the REST API.
[apply\_filters( 'the\_content', string $content )](../../hooks/the_content)
Filters the post content.
[apply\_filters( 'the\_excerpt', string $post\_excerpt )](../../hooks/the_excerpt)
Filters the displayed post excerpt.
| Uses | Description |
| --- | --- |
| [wp\_get\_missing\_image\_subsizes()](../../functions/wp_get_missing_image_subsizes) wp-admin/includes/image.php | Compare the existing image sub-sizes (as saved in the attachment meta) to the currently registered image sub-sizes, and return the difference. |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_response()](../wp_rest_posts_controller/prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post output for response. |
| [wp\_get\_attachment\_image\_src()](../../functions/wp_get_attachment_image_src) wp-includes/media.php | Retrieves an image to represent an attachment. |
| [wp\_attachment\_is\_image()](../../functions/wp_attachment_is_image) wp-includes/post.php | Determines whether an attachment is an image. |
| [wp\_get\_attachment\_metadata()](../../functions/wp_get_attachment_metadata) wp-includes/post.php | Retrieves attachment metadata for attachment ID. |
| [wp\_get\_attachment\_url()](../../functions/wp_get_attachment_url) wp-includes/post.php | Retrieves the URL for an attachment. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [wp\_basename()](../../functions/wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post\_meta()](../../functions/get_post_meta) wp-includes/post.php | Retrieves a post meta field for the given post ID. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::edit\_media\_item()](edit_media_item) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Applies edits to a media item and creates a new attachment record. |
| [WP\_REST\_Attachments\_Controller::post\_process\_item()](post_process_item) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Performs post processing on an attachment. |
| [WP\_REST\_Attachments\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Creates a single attachment. |
| [WP\_REST\_Attachments\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Updates a single attachment. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Attachments_Controller::get_filename_from_disposition( string[] $disposition_header ): string|null WP\_REST\_Attachments\_Controller::get\_filename\_from\_disposition( string[] $disposition\_header ): string|null
=================================================================================================================
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 "*">
```
`$disposition_header` string[] Required List of Content-Disposition header values. string|null Filename if available, or null if not found.
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/)
```
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;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::upload\_from\_data()](upload_from_data) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Handles an upload via raw POST data. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::check_upload_size( array $file ): true|WP_Error WP\_REST\_Attachments\_Controller::check\_upload\_size( array $file ): true|WP\_Error
=====================================================================================
Determine if uploaded file exceeds space quota on multisite.
Replicates [check\_upload\_size()](../../functions/check_upload_size) .
`$file` array Required $\_FILES array for a given file. true|[WP\_Error](../wp_error) True if can upload, error for errors.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [upload\_is\_user\_over\_quota()](../../functions/upload_is_user_over_quota) wp-admin/includes/ms.php | Check whether a site has used its allotted upload space. |
| [get\_upload\_space\_available()](../../functions/get_upload_space_available) wp-includes/ms-functions.php | Determines if there is any upload space left in the current blog’s quota. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_multisite()](../../functions/is_multisite) wp-includes/load.php | If Multisite is enabled. |
| [get\_site\_option()](../../functions/get_site_option) wp-includes/option.php | Retrieve an option value for the current network based on name of option. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::upload\_from\_file()](upload_from_file) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Handles an upload via multipart/form-data ($\_FILES). |
| [WP\_REST\_Attachments\_Controller::upload\_from\_data()](upload_from_data) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Handles an upload via raw POST data. |
| Version | Description |
| --- | --- |
| [4.9.8](https://developer.wordpress.org/reference/since/4.9.8/) | Introduced. |
wordpress WP_REST_Attachments_Controller::create_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Attachments\_Controller::create\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
===========================================================================================================
Creates a single attachment.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, [WP\_Error](../wp_error) object on failure.
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/)
```
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;
}
```
[do\_action( 'rest\_after\_insert\_attachment', WP\_Post $attachment, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_after_insert_attachment)
Fires after a single attachment is completely created or updated via the REST API.
| Uses | Description |
| --- | --- |
| [wp\_after\_insert\_post()](../../functions/wp_after_insert_post) wp-includes/post.php | Fires actions after a post, its terms and meta data has been saved. |
| [WP\_REST\_Attachments\_Controller::insert\_attachment()](insert_attachment) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Inserts the attachment post in the database. Does not update the attachment meta. |
| [WP\_REST\_Attachments\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Retrieves the attachment’s schema, conforming to JSON Schema. |
| [WP\_REST\_Attachments\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Prepares a single attachment output for response. |
| [wp\_generate\_attachment\_metadata()](../../functions/wp_generate_attachment_metadata) wp-admin/includes/image.php | Generates attachment meta data and create image sub-sizes for images. |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [wp\_update\_attachment\_metadata()](../../functions/wp_update_attachment_metadata) wp-includes/post.php | Updates metadata for an attachment. |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| [get\_post\_type()](../../functions/get_post_type) wp-includes/post.php | Retrieves the post type of the current post or of a given post. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::prepare_items_query( array $prepared_args = array(), WP_REST_Request $request = null ): array WP\_REST\_Attachments\_Controller::prepare\_items\_query( array $prepared\_args = array(), WP\_REST\_Request $request = null ): array
=====================================================================================================================================
Determines the allowed query\_vars for a get\_items() response and prepares for [WP\_Query](../wp_query).
`$prepared_args` array Optional Array of prepared arguments. Default: `array()`
`$request` [WP\_REST\_Request](../wp_rest_request) Optional Request to prepare items for. Default: `null`
array Array of query arguments.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::get\_media\_types()](get_media_types) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Retrieves the supported media types. |
| [WP\_REST\_Posts\_Controller::prepare\_items\_query()](../wp_rest_posts_controller/prepare_items_query) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Determines the allowed query\_vars for a get\_items() response and prepares them for [WP\_Query](../wp_query). |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::update_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Attachments\_Controller::update\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
===========================================================================================================
Updates a single attachment.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, [WP\_Error](../wp_error) object on failure.
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/)
```
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;
}
```
[do\_action( 'rest\_after\_insert\_attachment', WP\_Post $attachment, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_after_insert_attachment)
Fires after a single attachment is completely created or updated via the REST API.
| Uses | Description |
| --- | --- |
| [wp\_after\_insert\_post()](../../functions/wp_after_insert_post) wp-includes/post.php | Fires actions after a post, its terms and meta data has been saved. |
| [WP\_REST\_Attachments\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Prepares a single attachment output for response. |
| [WP\_REST\_Posts\_Controller::update\_item()](../wp_rest_posts_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Updates a single post. |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| [get\_post\_type()](../../functions/get_post_type) wp-includes/post.php | Retrieves the post type of the current post or of a given post. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::get_edit_media_item_args(): array WP\_REST\_Attachments\_Controller::get\_edit\_media\_item\_args(): array
========================================================================
Gets the request args for the edit item route.
array
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/)
```
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 |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::register\_routes()](register_routes) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Registers the routes for attachments. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Attachments_Controller::post_process_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Attachments\_Controller::post\_process\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
==================================================================================================================
Performs post processing on an attachment.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, [WP\_Error](../wp_error) object on failure.
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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [wp\_update\_image\_subsizes()](../../functions/wp_update_image_subsizes) wp-admin/includes/image.php | If any of the currently registered image sub-sizes are missing, create them and update the image meta data. |
| [WP\_REST\_Attachments\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Prepares a single attachment output for response. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::post_process_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Attachments\_Controller::post\_process\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
========================================================================================================================
Checks if a given request can perform post processing on an attachment.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has access to update the item, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php/)
```
public function post_process_item_permissions_check( $request ) {
return $this->update_item_permissions_check( $request );
}
```
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::prepare_item_for_database( WP_REST_Request $request ): stdClass|WP_Error WP\_REST\_Attachments\_Controller::prepare\_item\_for\_database( WP\_REST\_Request $request ): stdClass|WP\_Error
=================================================================================================================
Prepares a single attachment for create or update.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. stdClass|[WP\_Error](../wp_error) Post object.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_database()](../wp_rest_posts_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post for create or update. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::insert\_attachment()](insert_attachment) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Inserts the attachment post in the database. Does not update the attachment meta. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::get_media_types(): array WP\_REST\_Attachments\_Controller::get\_media\_types(): array
=============================================================
Retrieves the supported media types.
Media types are considered the MIME type category.
array Array of supported media types.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [get\_allowed\_mime\_types()](../../functions/get_allowed_mime_types) wp-includes/functions.php | Retrieves the list of allowed mime types and file extensions. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Retrieves the query params for collections of attachments. |
| [WP\_REST\_Attachments\_Controller::prepare\_items\_query()](prepare_items_query) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Determines the allowed query\_vars for a get\_items() response and prepares for [WP\_Query](../wp_query). |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::register_routes() WP\_REST\_Attachments\_Controller::register\_routes()
=====================================================
Registers the routes for attachments.
* [register\_rest\_route()](../../functions/register_rest_route)
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/)
```
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(),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::get\_edit\_media\_item\_args()](get_edit_media_item_args) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Gets the request args for the edit item route. |
| [WP\_REST\_Posts\_Controller::register\_routes()](../wp_rest_posts_controller/register_routes) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Registers the routes for posts. |
| [register\_rest\_route()](../../functions/register_rest_route) wp-includes/rest-api.php | Registers a REST API route. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::insert_attachment( WP_REST_Request $request ): array|WP_Error WP\_REST\_Attachments\_Controller::insert\_attachment( WP\_REST\_Request $request ): array|WP\_Error
====================================================================================================
Inserts the attachment post in the database. Does not update the attachment meta.
`$request` [WP\_REST\_Request](../wp_rest_request) Required array|[WP\_Error](../wp_error)
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/)
```
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,
);
}
```
[do\_action( 'rest\_insert\_attachment', WP\_Post $attachment, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_insert_attachment)
Fires after a single attachment is created or updated via the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::upload\_from\_file()](upload_from_file) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Handles an upload via multipart/form-data ($\_FILES). |
| [WP\_REST\_Attachments\_Controller::upload\_from\_data()](upload_from_data) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Handles an upload via raw POST data. |
| [WP\_REST\_Attachments\_Controller::prepare\_item\_for\_database()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Prepares a single attachment for create or update. |
| [wp\_read\_image\_metadata()](../../functions/wp_read_image_metadata) wp-admin/includes/image.php | Gets extended image metadata, exif or iptc as available. |
| [sanitize\_title()](../../functions/sanitize_title) wp-includes/formatting.php | Sanitizes a string into a slug, which can be used in URLs or HTML attributes. |
| [wp\_insert\_attachment()](../../functions/wp_insert_attachment) wp-includes/post.php | Inserts an attachment. |
| [wp\_basename()](../../functions/wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Creates a single attachment. |
| Version | Description |
| --- | --- |
| [5.3.0](https://developer.wordpress.org/reference/since/5.3.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::get_collection_params(): array WP\_REST\_Attachments\_Controller::get\_collection\_params(): array
===================================================================
Retrieves the query params for collections of attachments.
array Query parameters for the attachment collection as an array.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::get\_media\_types()](get_media_types) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Retrieves the supported media types. |
| [WP\_REST\_Posts\_Controller::get\_collection\_params()](../wp_rest_posts_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves the query params for the posts collection. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::edit_media_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Attachments\_Controller::edit\_media\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
======================================================================================================================
Checks if a given request has access to editing media.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::upload_from_file( array $files, array $headers ): array|WP_Error WP\_REST\_Attachments\_Controller::upload\_from\_file( array $files, array $headers ): array|WP\_Error
======================================================================================================
Handles an upload via multipart/form-data ($\_FILES).
`$files` array Required Data from the `$_FILES` superglobal. `$headers` array Required HTTP headers from the request. array|[WP\_Error](../wp_error) Data from [wp\_handle\_upload()](../../functions/wp_handle_upload) .
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::check\_upload\_size()](check_upload_size) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Determine if uploaded file exceeds space quota on multisite. |
| [wp\_handle\_upload()](../../functions/wp_handle_upload) wp-admin/includes/file.php | Wrapper for [\_wp\_handle\_upload()](../../functions/_wp_handle_upload) . |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::insert\_attachment()](insert_attachment) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Inserts the attachment post in the database. Does not update the attachment meta. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Attachments_Controller::create_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Attachments\_Controller::create\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=================================================================================================================
Checks if a given request has access to create an attachment.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) Boolean true if the attachment may be created, or a [WP\_Error](../wp_error) if not.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::create\_item\_permissions\_check()](../wp_rest_posts_controller/create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to create a post. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::get_item_schema(): array WP\_REST\_Attachments\_Controller::get\_item\_schema(): array
=============================================================
Retrieves the attachment’s schema, conforming to JSON Schema.
array Item schema as an array.
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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::get\_item\_schema()](../wp_rest_posts_controller/get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves the post’s schema, conforming to JSON Schema. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Creates a single attachment. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Attachments_Controller::edit_media_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Attachments\_Controller::edit\_media\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
================================================================================================================
Applies edits to a media item and creates a new attachment record.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, [WP\_Error](../wp_error) object on failure.
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/)
```
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;
}
```
[apply\_filters( 'wp\_edited\_image\_metadata', array $new\_image\_meta, int $new\_attachment\_id, int $attachment\_id )](../../hooks/wp_edited_image_metadata)
Filters the meta data for the new image created by editing an existing image.
| Uses | Description |
| --- | --- |
| [wp\_image\_file\_matches\_image\_meta()](../../functions/wp_image_file_matches_image_meta) wp-includes/media.php | Determines if the image meta data is for the image source file. |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| [WP\_REST\_Attachments\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Prepares a single attachment output for response. |
| [\_load\_image\_to\_edit\_path()](../../functions/_load_image_to_edit_path) wp-admin/includes/image.php | Retrieves the path or URL of an attachment’s attached file. |
| [wp\_generate\_attachment\_metadata()](../../functions/wp_generate_attachment_metadata) wp-admin/includes/image.php | Generates attachment meta data and create image sub-sizes for images. |
| [\_wp\_relative\_upload\_path()](../../functions/_wp_relative_upload_path) wp-includes/post.php | Returns relative path to an uploaded file. |
| [get\_post\_mime\_type()](../../functions/get_post_mime_type) wp-includes/post.php | Retrieves the mime type of an attachment based on the ID. |
| [wp\_upload\_dir()](../../functions/wp_upload_dir) wp-includes/functions.php | Returns an array containing the current upload directory’s path and URL. |
| [wp\_unique\_filename()](../../functions/wp_unique_filename) wp-includes/functions.php | Gets a filename that is sanitized and unique for the given directory. |
| [wp\_get\_original\_image\_path()](../../functions/wp_get_original_image_path) wp-includes/post.php | Retrieves the path to an uploaded image file. |
| [wp\_get\_image\_editor()](../../functions/wp_get_image_editor) wp-includes/media.php | Returns a [WP\_Image\_Editor](../wp_image_editor) instance and loads file into it. |
| [wp\_get\_attachment\_metadata()](../../functions/wp_get_attachment_metadata) wp-includes/post.php | Retrieves attachment metadata for attachment ID. |
| [wp\_insert\_attachment()](../../functions/wp_insert_attachment) wp-includes/post.php | Inserts an attachment. |
| [wp\_update\_attachment\_metadata()](../../functions/wp_update_attachment_metadata) wp-includes/post.php | Updates metadata for an attachment. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post\_meta()](../../functions/get_post_meta) wp-includes/post.php | Retrieves a post meta field for the given post ID. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [wp\_basename()](../../functions/wp_basename) wp-includes/formatting.php | i18n-friendly version of basename(). |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [5.5.0](https://developer.wordpress.org/reference/since/5.5.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Response::get_links(): array WP\_REST\_Response::get\_links(): array
=======================================
Retrieves links for the response.
array List of links.
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/)
```
public function get_links() {
return $this->links;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Response::set_matched_route( string $route ) WP\_REST\_Response::set\_matched\_route( string $route )
========================================================
Sets the route (regex for path) that caused the response.
`$route` string Required Route name. 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/)
```
public function set_matched_route( $route ) {
$this->matched_route = $route;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Response::link_header( string $rel, string $link, array $other = array() ) WP\_REST\_Response::link\_header( string $rel, string $link, array $other = array() )
=====================================================================================
Sets a single link header.
`$rel` string Required Link relation. Either an IANA registered type, or an absolute URL. `$link` string Required Target IRI for the link. `$other` array Optional Other parameters to send, as an associative array.
Default: `array()`
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/)
```
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 );
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Response::as_error(): WP_Error|null WP\_REST\_Response::as\_error(): WP\_Error|null
===============================================
Retrieves a [WP\_Error](../wp_error) object from the response.
[WP\_Error](../wp_error)|null [WP\_Error](../wp_error) or null on not an errored 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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Response::is\_error()](is_error) wp-includes/rest-api/class-wp-rest-response.php | Checks if the response is an error, i.e. >= 400 response code. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Response::add_links( array $links ) WP\_REST\_Response::add\_links( array $links )
==============================================
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.
`$links` array Required Map of link relation to list of links. 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/)
```
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 );
}
}
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Response::add\_link()](add_link) wp-includes/rest-api/class-wp-rest-response.php | Adds a link to the response. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Response::get_matched_handler(): null|array WP\_REST\_Response::get\_matched\_handler(): null|array
=======================================================
Retrieves the handler that was used to generate the response.
null|array The handler that was used to create 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/)
```
public function get_matched_handler() {
return $this->matched_handler;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Response::get_matched_route(): string WP\_REST\_Response::get\_matched\_route(): string
=================================================
Retrieves the route that was used.
string The matched route.
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/)
```
public function get_matched_route() {
return $this->matched_route;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Response::remove_link( string $rel, string $href = null ) WP\_REST\_Response::remove\_link( string $rel, string $href = null )
====================================================================
Removes a link from the response.
`$rel` string Required Link relation. Either an IANA registered type, or an absolute URL. `$href` string Optional Only remove links for the relation matching the given href.
Default: `null`
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/)
```
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 ] );
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_list\_filter()](../../functions/wp_list_filter) wp-includes/functions.php | Filters a list of objects, based on a set of key => value arguments. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Response::get_curies(): array WP\_REST\_Response::get\_curies(): array
========================================
Retrieves the CURIEs (compact URIs) used for relations.
array Compact URIs.
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/)
```
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 );
}
```
[apply\_filters( 'rest\_response\_link\_curies', array $additional )](../../hooks/rest_response_link_curies)
Filters extra CURIEs available on REST API responses.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [4.5.0](https://developer.wordpress.org/reference/since/4.5.0/) | Introduced. |
wordpress WP_REST_Response::set_matched_handler( array $handler ) WP\_REST\_Response::set\_matched\_handler( array $handler )
===========================================================
Sets the handler that was responsible for generating the response.
`$handler` array Required The matched handler. 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/)
```
public function set_matched_handler( $handler ) {
$this->matched_handler = $handler;
}
```
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Response::is_error(): bool WP\_REST\_Response::is\_error(): bool
=====================================
Checks if the response is an error, i.e. >= 400 response code.
bool Whether the response is an error.
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/)
```
public function is_error() {
return $this->get_status() >= 400;
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Response::as\_error()](as_error) wp-includes/rest-api/class-wp-rest-response.php | Retrieves a [WP\_Error](../wp_error) object from the response. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_REST_Response::add_link( string $rel, string $href, array $attributes = array() ) WP\_REST\_Response::add\_link( string $rel, string $href, array $attributes = array() )
=======================================================================================
Adds a link to the response.
`$rel` string Required Link relation. Either an IANA registered type, or an absolute URL. `$href` string Required Target URI for the link. `$attributes` array Optional Link parameters to send along with the URL. Default: `array()`
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/)
```
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,
);
}
```
| Used By | Description |
| --- | --- |
| [WP\_REST\_Response::add\_links()](add_links) wp-includes/rest-api/class-wp-rest-response.php | Adds multiple links to the response. |
| Version | Description |
| --- | --- |
| [4.4.0](https://developer.wordpress.org/reference/since/4.4.0/) | Introduced. |
wordpress WP_Customize_Header_Image_Control::prepare_control() WP\_Customize\_Header\_Image\_Control::prepare\_control()
=========================================================
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/)
```
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();
}
```
| Uses | Description |
| --- | --- |
| [Custom\_Image\_Header::get\_default\_header\_images()](../custom_image_header/get_default_header_images) wp-admin/includes/class-custom-image-header.php | Gets the details of default header images if defined. |
| [Custom\_Image\_Header::get\_uploaded\_header\_images()](../custom_image_header/get_uploaded_header_images) wp-admin/includes/class-custom-image-header.php | Gets the previously uploaded header images. |
| [Custom\_Image\_Header::process\_default\_headers()](../custom_image_header/process_default_headers) wp-admin/includes/class-custom-image-header.php | Process the default headers |
| [add\_action()](../../functions/add_action) wp-includes/plugin.php | Adds a callback function to an action hook. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Header\_Image\_Control::enqueue()](enqueue) wp-includes/customize/class-wp-customize-header-image-control.php | |
wordpress WP_Customize_Header_Image_Control::__construct( WP_Customize_Manager $manager ) WP\_Customize\_Header\_Image\_Control::\_\_construct( WP\_Customize\_Manager $manager )
=======================================================================================
Constructor.
`$manager` [WP\_Customize\_Manager](../wp_customize_manager) Required Customizer bootstrap instance. 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/)
```
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',
)
);
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Manager::register\_controls()](../wp_customize_manager/register_controls) wp-includes/class-wp-customize-manager.php | Registers some default controls. |
| Version | Description |
| --- | --- |
| [3.4.0](https://developer.wordpress.org/reference/since/3.4.0/) | Introduced. |
wordpress WP_Customize_Header_Image_Control::print_header_image_template() WP\_Customize\_Header\_Image\_Control::print\_header\_image\_template()
=======================================================================
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/)
```
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
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
wordpress WP_Customize_Header_Image_Control::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/)
```
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 “Add new image” to upload an image file from your computer. Your theme works best with an image that matches the size of your video — you’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 “Add new image” to upload an image file from your computer. Your theme works best with an image with a header size of %s pixels — you’ll be able to crop your image once you upload it for a perfect fit.' ),
sprintf( '<strong>%s × %s</strong>', $width, $height )
);
} elseif ( $width ) {
printf(
/* translators: %s: Header width in pixels. */
__( 'Click “Add new image” to upload an image file from your computer. Your theme works best with an image with a header width of %s pixels — you’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 “Add new image” to upload an image file from your computer. Your theme works best with an image with a header height of %s pixels — you’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 |
| --- | --- |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [esc\_attr\_e()](../../functions/esc_attr_e) wp-includes/l10n.php | Displays translated text that has been escaped for safe use in an attribute. |
| [\_ex()](../../functions/_ex) wp-includes/l10n.php | Displays translated string with gettext context. |
| [WP\_Customize\_Header\_Image\_Control::get\_current\_image\_src()](get_current_image_src) wp-includes/customize/class-wp-customize-header-image-control.php | |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
| programming_docs |
wordpress WP_Customize_Header_Image_Control::get_current_image_src(): string|void WP\_Customize\_Header\_Image\_Control::get\_current\_image\_src(): string|void
==============================================================================
string|void
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/)
```
public function get_current_image_src() {
$src = $this->value();
if ( isset( $this->get_url ) ) {
$src = call_user_func( $this->get_url, $src );
return $src;
}
}
```
| Used By | Description |
| --- | --- |
| [WP\_Customize\_Header\_Image\_Control::enqueue()](enqueue) wp-includes/customize/class-wp-customize-header-image-control.php | |
| [WP\_Customize\_Header\_Image\_Control::render\_content()](render_content) wp-includes/customize/class-wp-customize-header-image-control.php | |
wordpress WP_Customize_Header_Image_Control::enqueue() WP\_Customize\_Header\_Image\_Control::enqueue()
================================================
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/)
```
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();
}
```
| Uses | Description |
| --- | --- |
| [get\_theme\_support()](../../functions/get_theme_support) wp-includes/theme.php | Gets the theme support arguments passed when registering that support. |
| [wp\_create\_nonce()](../../functions/wp_create_nonce) wp-includes/pluggable.php | Creates a cryptographic token tied to a specific action, user, user session, and window of time. |
| [wp\_enqueue\_script()](../../functions/wp_enqueue_script) wp-includes/functions.wp-scripts.php | Enqueue a script. |
| [wp\_localize\_script()](../../functions/wp_localize_script) wp-includes/functions.wp-scripts.php | Localize a script. |
| [wp\_enqueue\_media()](../../functions/wp_enqueue_media) wp-includes/media.php | Enqueues all scripts, styles, settings, and templates necessary to use all media JS APIs. |
| [WP\_Customize\_Header\_Image\_Control::prepare\_control()](prepare_control) wp-includes/customize/class-wp-customize-header-image-control.php | |
| [WP\_Customize\_Header\_Image\_Control::get\_current\_image\_src()](get_current_image_src) wp-includes/customize/class-wp-customize-header-image-control.php | |
| [absint()](../../functions/absint) wp-includes/functions.php | Converts a value to non-negative integer. |
wordpress WP_Application_Passwords_List_Table::single_row( array $item ) WP\_Application\_Passwords\_List\_Table::single\_row( array $item )
===================================================================
Generates content for a single row of the table.
`$item` array Required The current item. 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/)
```
public function single_row( $item ) {
echo '<tr data-uuid="' . esc_attr( $item['uuid'] ) . '">';
$this->single_row_columns( $item );
echo '</tr>';
}
```
| Uses | Description |
| --- | --- |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords_List_Table::prepare_items() WP\_Application\_Passwords\_List\_Table::prepare\_items()
=========================================================
Prepares the list of items for displaying.
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/)
```
public function prepare_items() {
global $user_id;
$this->items = array_reverse( WP_Application_Passwords::get_user_application_passwords( $user_id ) );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Application\_Passwords::get\_user\_application\_passwords()](../wp_application_passwords/get_user_application_passwords) wp-includes/class-wp-application-passwords.php | Gets a user’s application passwords. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords_List_Table::column_created( array $item ) WP\_Application\_Passwords\_List\_Table::column\_created( array $item )
=======================================================================
Handles the created column output.
`$item` array Required The current application password item. 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/)
```
public function column_created( $item ) {
if ( empty( $item['created'] ) ) {
echo '—';
} else {
echo date_i18n( __( 'F j, Y' ), $item['created'] );
}
}
```
| Uses | Description |
| --- | --- |
| [date\_i18n()](../../functions/date_i18n) wp-includes/functions.php | Retrieves the date in localized format, based on a sum of Unix timestamp and timezone offset in seconds. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords_List_Table::get_default_primary_column_name(): string WP\_Application\_Passwords\_List\_Table::get\_default\_primary\_column\_name(): string
======================================================================================
Gets the name of the default primary column.
string Name of the default primary column, in this case, `'name'`.
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/)
```
protected function get_default_primary_column_name() {
return 'name';
}
```
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords_List_Table::print_js_template_row() WP\_Application\_Passwords\_List\_Table::print\_js\_template\_row()
===================================================================
Prints the JavaScript template for the new row item.
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/)
```
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>';
}
```
[do\_action( "manage\_{$this->screen->id}\_custom\_column\_js\_template", string $column\_name )](../../hooks/manage_this-screen-id_custom_column_js_template)
Fires in the JavaScript row template for each custom column in the Application Passwords list table.
| Uses | Description |
| --- | --- |
| [esc\_html\_\_()](../../functions/esc_html__) wp-includes/l10n.php | Retrieves the translation of $text and escapes it for safe use in HTML output. |
| [wp\_strip\_all\_tags()](../../functions/wp_strip_all_tags) wp-includes/formatting.php | Properly strips all HTML tags including script and style |
| [wp\_json\_encode()](../../functions/wp_json_encode) wp-includes/functions.php | Encodes a variable into JSON, with some sanity checks. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords_List_Table::column_last_used( array $item ) WP\_Application\_Passwords\_List\_Table::column\_last\_used( array $item )
==========================================================================
Handles the last used column output.
`$item` array Required The current application password item. 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/)
```
public function column_last_used( $item ) {
if ( empty( $item['last_used'] ) ) {
echo '—';
} else {
echo date_i18n( __( 'F j, Y' ), $item['last_used'] );
}
}
```
| Uses | Description |
| --- | --- |
| [date\_i18n()](../../functions/date_i18n) wp-includes/functions.php | Retrieves the date in localized format, based on a sum of Unix timestamp and timezone offset in seconds. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords_List_Table::column_last_ip( array $item ) WP\_Application\_Passwords\_List\_Table::column\_last\_ip( array $item )
========================================================================
Handles the last ip column output.
`$item` array Required The current application password item. 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/)
```
public function column_last_ip( $item ) {
if ( empty( $item['last_ip'] ) ) {
echo '—';
} else {
echo $item['last_ip'];
}
}
```
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords_List_Table::display_tablenav( string $which ) WP\_Application\_Passwords\_List\_Table::display\_tablenav( string $which )
===========================================================================
Generates custom table navigation to prevent conflicting nonces.
`$which` string Required The location of the bulk actions: `'top'` or `'bottom'`. 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/)
```
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
}
```
| Uses | Description |
| --- | --- |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords_List_Table::get_columns(): array WP\_Application\_Passwords\_List\_Table::get\_columns(): array
==============================================================
Gets the list of columns.
array
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/)
```
public function get_columns() {
return array(
'name' => __( 'Name' ),
'created' => __( 'Created' ),
'last_used' => __( 'Last Used' ),
'last_ip' => __( 'Last IP' ),
'revoke' => __( 'Revoke' ),
);
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords_List_Table::column_revoke( array $item ) WP\_Application\_Passwords\_List\_Table::column\_revoke( array $item )
======================================================================
Handles the revoke column output.
`$item` array Required The current application password item. 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/)
```
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' )
);
}
```
| Uses | Description |
| --- | --- |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords_List_Table::column_name( array $item ) WP\_Application\_Passwords\_List\_Table::column\_name( array $item )
====================================================================
Handles the name column output.
`$item` array Required The current application password item. 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/)
```
public function column_name( $item ) {
echo esc_html( $item['name'] );
}
```
| Uses | Description |
| --- | --- |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Application_Passwords_List_Table::column_default( array $item, string $column_name ) WP\_Application\_Passwords\_List\_Table::column\_default( array $item, string $column\_name )
=============================================================================================
Generates content for a single row of the table
`$item` array Required The current item. `$column_name` string Required The current column name. 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/)
```
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 );
}
```
[do\_action( "manage\_{$this->screen->id}\_custom\_column", string $column\_name, array $item )](../../hooks/manage_this-screen-id_custom_column)
Fires for each custom column in the Application Passwords list table.
| Uses | Description |
| --- | --- |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| Version | Description |
| --- | --- |
| [5.6.0](https://developer.wordpress.org/reference/since/5.6.0/) | Introduced. |
wordpress WP_Widget_Archives::form( array $instance ) WP\_Widget\_Archives::form( array $instance )
=============================================
Outputs the settings form for the Archives widget.
`$instance` array Required Current settings. File: `wp-includes/widgets/class-wp-widget-archives.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-archives.php/)
```
public function form( $instance ) {
$instance = wp_parse_args(
(array) $instance,
array(
'title' => '',
'count' => 0,
'dropdown' => '',
)
);
?>
<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 class="checkbox" type="checkbox"<?php checked( $instance['dropdown'] ); ?> id="<?php echo $this->get_field_id( 'dropdown' ); ?>" name="<?php echo $this->get_field_name( 'dropdown' ); ?>" />
<label for="<?php echo $this->get_field_id( 'dropdown' ); ?>"><?php _e( 'Display as dropdown' ); ?></label>
<br />
<input class="checkbox" type="checkbox"<?php checked( $instance['count'] ); ?> id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo $this->get_field_name( 'count' ); ?>" />
<label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php _e( 'Show post counts' ); ?></label>
</p>
<?php
}
```
| Uses | Description |
| --- | --- |
| [checked()](../../functions/checked) wp-includes/general-template.php | Outputs the HTML checked attribute. |
| [\_e()](../../functions/_e) wp-includes/l10n.php | Displays translated text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
| programming_docs |
wordpress WP_Widget_Archives::update( array $new_instance, array $old_instance ): array WP\_Widget\_Archives::update( array $new\_instance, array $old\_instance ): array
=================================================================================
Handles updating settings for the current Archives widget instance.
`$new_instance` array Required New settings for this instance as input by the user via [WP\_Widget\_Archives::form()](form). `$old_instance` array Required Old settings for this instance. array Updated settings to save.
File: `wp-includes/widgets/class-wp-widget-archives.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-archives.php/)
```
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$new_instance = wp_parse_args(
(array) $new_instance,
array(
'title' => '',
'count' => 0,
'dropdown' => '',
)
);
$instance['title'] = sanitize_text_field( $new_instance['title'] );
$instance['count'] = $new_instance['count'] ? 1 : 0;
$instance['dropdown'] = $new_instance['dropdown'] ? 1 : 0;
return $instance;
}
```
| Uses | Description |
| --- | --- |
| [sanitize\_text\_field()](../../functions/sanitize_text_field) wp-includes/formatting.php | Sanitizes a string from user input or from the database. |
| [wp\_parse\_args()](../../functions/wp_parse_args) wp-includes/functions.php | Merges user defined arguments into defaults array. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Archives::__construct() WP\_Widget\_Archives::\_\_construct()
=====================================
Sets up a new Archives widget instance.
File: `wp-includes/widgets/class-wp-widget-archives.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-archives.php/)
```
public function __construct() {
$widget_ops = array(
'classname' => 'widget_archive',
'description' => __( 'A monthly archive of your site’s Posts.' ),
'customize_selective_refresh' => true,
'show_instance_in_rest' => true,
);
parent::__construct( 'archives', __( 'Archives' ), $widget_ops );
}
```
| Uses | Description |
| --- | --- |
| [WP\_Widget::\_\_construct()](../wp_widget/__construct) wp-includes/class-wp-widget.php | PHP5 constructor. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress WP_Widget_Archives::widget( array $args, array $instance ) WP\_Widget\_Archives::widget( array $args, array $instance )
============================================================
Outputs the content for the current Archives widget instance.
`$args` array Required Display arguments including `'before_title'`, `'after_title'`, `'before_widget'`, and `'after_widget'`. `$instance` array Required Settings for the current Archives widget instance. File: `wp-includes/widgets/class-wp-widget-archives.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/widgets/class-wp-widget-archives.php/)
```
public function widget( $args, $instance ) {
$default_title = __( 'Archives' );
$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';
$dropdown = ! empty( $instance['dropdown'] ) ? '1' : '0';
echo $args['before_widget'];
if ( $title ) {
echo $args['before_title'] . $title . $args['after_title'];
}
if ( $dropdown ) {
$dropdown_id = "{$this->id_base}-dropdown-{$this->number}";
?>
<label class="screen-reader-text" for="<?php echo esc_attr( $dropdown_id ); ?>"><?php echo $title; ?></label>
<select id="<?php echo esc_attr( $dropdown_id ); ?>" name="archive-dropdown">
<?php
/**
* Filters the arguments for the Archives widget drop-down.
*
* @since 2.8.0
* @since 4.9.0 Added the `$instance` parameter.
*
* @see wp_get_archives()
*
* @param array $args An array of Archives widget drop-down arguments.
* @param array $instance Settings for the current Archives widget instance.
*/
$dropdown_args = apply_filters(
'widget_archives_dropdown_args',
array(
'type' => 'monthly',
'format' => 'option',
'show_post_count' => $count,
),
$instance
);
switch ( $dropdown_args['type'] ) {
case 'yearly':
$label = __( 'Select Year' );
break;
case 'monthly':
$label = __( 'Select Month' );
break;
case 'daily':
$label = __( 'Select Day' );
break;
case 'weekly':
$label = __( 'Select Week' );
break;
default:
$label = __( 'Select Post' );
break;
}
$type_attr = current_theme_supports( 'html5', 'script' ) ? '' : ' type="text/javascript"';
?>
<option value=""><?php echo esc_html( $label ); ?></option>
<?php wp_get_archives( $dropdown_args ); ?>
</select>
<script<?php echo $type_attr; ?>>
/* <![CDATA[ */
(function() {
var dropdown = document.getElementById( "<?php echo esc_js( $dropdown_id ); ?>" );
function onSelectChange() {
if ( dropdown.options[ dropdown.selectedIndex ].value !== '' ) {
document.location.href = this.options[ this.selectedIndex ].value;
}
}
dropdown.onchange = onSelectChange;
})();
/* ]]> */
</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
wp_get_archives(
/**
* Filters the arguments for the Archives widget.
*
* @since 2.8.0
* @since 4.9.0 Added the `$instance` parameter.
*
* @see wp_get_archives()
*
* @param array $args An array of Archives option arguments.
* @param array $instance Array of settings for the current widget.
*/
apply_filters(
'widget_archives_args',
array(
'type' => 'monthly',
'show_post_count' => $count,
),
$instance
)
);
?>
</ul>
<?php
if ( 'html5' === $format ) {
echo '</nav>';
}
}
echo $args['after_widget'];
}
```
[apply\_filters( 'navigation\_widgets\_format', string $format )](../../hooks/navigation_widgets_format)
Filters the HTML format of widgets with navigation links.
[apply\_filters( 'widget\_archives\_args', array $args, array $instance )](../../hooks/widget_archives_args)
Filters the arguments for the Archives widget.
[apply\_filters( 'widget\_archives\_dropdown\_args', array $args, array $instance )](../../hooks/widget_archives_dropdown_args)
Filters the arguments for the Archives widget drop-down.
[apply\_filters( 'widget\_title', string $title, array $instance, mixed $id\_base )](../../hooks/widget_title)
Filters the widget title.
| Uses | Description |
| --- | --- |
| [esc\_js()](../../functions/esc_js) wp-includes/formatting.php | Escapes single quotes, `"`, , `&`, and fixes line endings. |
| [wp\_get\_archives()](../../functions/wp_get_archives) wp-includes/general-template.php | Displays archive links based on type and format. |
| [current\_theme\_supports()](../../functions/current_theme_supports) wp-includes/theme.php | Checks a theme’s support for a given feature. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [esc\_attr()](../../functions/esc_attr) wp-includes/formatting.php | Escaping for HTML attributes. |
| [esc\_html()](../../functions/esc_html) wp-includes/formatting.php | Escaping for HTML blocks. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Version | Description |
| --- | --- |
| [2.8.0](https://developer.wordpress.org/reference/since/2.8.0/) | Introduced. |
wordpress MagpieRSS::map_attrs( $k, $v ) MagpieRSS::map\_attrs( $k, $v )
===============================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function map_attrs($k, $v) {
return "$k=\"$v\"";
}
```
wordpress MagpieRSS::is_rss() MagpieRSS::is\_rss()
====================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function is_rss () {
if ( $this->feed_type == RSS ) {
return $this->feed_version;
}
else {
return false;
}
}
```
| Used By | Description |
| --- | --- |
| [MagpieRSS::normalize()](normalize) wp-includes/rss.php | |
wordpress MagpieRSS::is_atom() MagpieRSS::is\_atom()
=====================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function is_atom() {
if ( $this->feed_type == ATOM ) {
return $this->feed_version;
}
else {
return false;
}
}
```
| Used By | Description |
| --- | --- |
| [MagpieRSS::normalize()](normalize) wp-includes/rss.php | |
wordpress MagpieRSS::append( $el, $text ) MagpieRSS::append( $el, $text )
===============================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
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 );
}
}
}
```
| Uses | Description |
| --- | --- |
| [MagpieRSS::concat()](concat) wp-includes/rss.php | |
| Used By | Description |
| --- | --- |
| [MagpieRSS::feed\_start\_element()](feed_start_element) wp-includes/rss.php | |
| [MagpieRSS::feed\_cdata()](feed_cdata) wp-includes/rss.php | |
wordpress MagpieRSS::feed_end_element( $p, $el ) MagpieRSS::feed\_end\_element( $p, $el )
========================================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [MagpieRSS::append\_content()](append_content) wp-includes/rss.php | |
wordpress MagpieRSS::feed_start_element( $p, $element, $attrs ) MagpieRSS::feed\_start\_element( $p, $element, $attrs )
=======================================================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
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);
}
}
```
| Uses | Description |
| --- | --- |
| [MagpieRSS::append\_content()](append_content) wp-includes/rss.php | |
| [MagpieRSS::append()](append) wp-includes/rss.php | |
wordpress MagpieRSS::feed_cdata( $p, $text ) MagpieRSS::feed\_cdata( $p, $text )
===================================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
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);
}
}
```
| Uses | Description |
| --- | --- |
| [MagpieRSS::append\_content()](append_content) wp-includes/rss.php | |
| [MagpieRSS::append()](append) wp-includes/rss.php | |
wordpress MagpieRSS::MagpieRSS( $source ) MagpieRSS::MagpieRSS( $source )
===============================
PHP4 constructor.
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
public function MagpieRSS( $source ) {
self::__construct( $source );
}
```
| Uses | Description |
| --- | --- |
| [MagpieRSS::\_\_construct()](__construct) wp-includes/rss.php | PHP5 constructor. |
wordpress MagpieRSS::__construct( $source ) MagpieRSS::\_\_construct( $source )
===================================
PHP5 constructor.
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
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();
}
```
| Uses | Description |
| --- | --- |
| [MagpieRSS::error()](error) wp-includes/rss.php | |
| [MagpieRSS::normalize()](normalize) wp-includes/rss.php | |
| Used By | Description |
| --- | --- |
| [\_response\_to\_rss()](../../functions/_response_to_rss) wp-includes/rss.php | Retrieve |
| [MagpieRSS::MagpieRSS()](magpierss) wp-includes/rss.php | PHP4 constructor. |
wordpress MagpieRSS::append_content( $text ) MagpieRSS::append\_content( $text )
===================================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
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 );
}
}
```
| Uses | Description |
| --- | --- |
| [MagpieRSS::concat()](concat) wp-includes/rss.php | |
| Used By | Description |
| --- | --- |
| [MagpieRSS::feed\_end\_element()](feed_end_element) wp-includes/rss.php | |
| [MagpieRSS::feed\_start\_element()](feed_start_element) wp-includes/rss.php | |
| [MagpieRSS::feed\_cdata()](feed_cdata) wp-includes/rss.php | |
wordpress MagpieRSS::normalize() MagpieRSS::normalize()
======================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
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;
}
}
}
```
| Uses | Description |
| --- | --- |
| [MagpieRSS::is\_atom()](is_atom) wp-includes/rss.php | |
| [MagpieRSS::is\_rss()](is_rss) wp-includes/rss.php | |
| Used By | Description |
| --- | --- |
| [MagpieRSS::\_\_construct()](__construct) wp-includes/rss.php | PHP5 constructor. |
| programming_docs |
wordpress MagpieRSS::concat( $str1, $str2 = "" ) MagpieRSS::concat( $str1, $str2 = "" )
======================================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function concat (&$str1, $str2="") {
if (!isset($str1) ) {
$str1="";
}
$str1 .= $str2;
}
```
| Used By | Description |
| --- | --- |
| [MagpieRSS::append\_content()](append_content) wp-includes/rss.php | |
| [MagpieRSS::append()](append) wp-includes/rss.php | |
wordpress MagpieRSS::error( $errormsg, $lvl = E_USER_WARNING ) MagpieRSS::error( $errormsg, $lvl = E\_USER\_WARNING )
======================================================
File: `wp-includes/rss.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rss.php/)
```
function error( $errormsg, $lvl = E_USER_WARNING ) {
if ( MAGPIE_DEBUG ) {
trigger_error( $errormsg, $lvl);
} else {
error_log( $errormsg, 0);
}
}
```
| Used By | Description |
| --- | --- |
| [MagpieRSS::\_\_construct()](__construct) wp-includes/rss.php | PHP5 constructor. |
wordpress WP_REST_Posts_Controller::get_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Posts\_Controller::get\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
==================================================================================================
Retrieves a single post.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::get\_post()](get_post) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Gets the post, if the ID is valid. |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post output for response. |
| [is\_post\_type\_viewable()](../../functions/is_post_type_viewable) wp-includes/post.php | Determines whether a post type is considered “viewable”. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [get\_permalink()](../../functions/get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::can_access_password_content( WP_Post $post, WP_REST_Request $request ): bool WP\_REST\_Posts\_Controller::can\_access\_password\_content( WP\_Post $post, WP\_REST\_Request $request ): bool
===============================================================================================================
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.
`$post` [WP\_Post](../wp_post) Required Post to check against. `$request` [WP\_REST\_Request](../wp_rest_request) Required Request data to check. bool True if the user can access password-protected content, otherwise false.
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/)
```
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'] );
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post output for response. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::check_update_permission( WP_Post $post ): bool WP\_REST\_Posts\_Controller::check\_update\_permission( WP\_Post $post ): bool
==============================================================================
Checks if a post can be edited.
`$post` [WP\_Post](../wp_post) Required Post object. bool Whether the post can be edited.
File: `wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::check\_is\_post\_type\_allowed()](check_is_post_type_allowed) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given post type can be viewed or managed. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::update\_item\_permissions\_check()](update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to update a post. |
| [WP\_REST\_Posts\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to read a post. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::prepare_item_for_response( WP_Post $item, WP_REST_Request $request ): WP_REST_Response WP\_REST\_Posts\_Controller::prepare\_item\_for\_response( WP\_Post $item, WP\_REST\_Request $request ): WP\_REST\_Response
===========================================================================================================================
Prepares a single post output for response.
`$item` [WP\_Post](../wp_post) Required Post object. `$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. [WP\_REST\_Response](../wp_rest_response) Response object.
File: `wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php/)
```
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 );
}
```
[apply\_filters( 'get\_the\_excerpt', string $post\_excerpt, WP\_Post $post )](../../hooks/get_the_excerpt)
Filters the retrieved post excerpt.
[apply\_filters( 'get\_the\_guid', string $post\_guid, int $post\_id )](../../hooks/get_the_guid)
Filters the Global Unique Identifier (guid) of the post.
[apply\_filters( "rest\_prepare\_{$this->post\_type}", WP\_REST\_Response $response, WP\_Post $post, WP\_REST\_Request $request )](../../hooks/rest_prepare_this-post_type)
Filters the post data for a REST API response.
[apply\_filters( 'the\_content', string $content )](../../hooks/the_content)
Filters the post content.
[apply\_filters( 'the\_excerpt', string $post\_excerpt )](../../hooks/the_excerpt)
Filters the displayed post excerpt.
| Uses | Description |
| --- | --- |
| [rest\_is\_field\_included()](../../functions/rest_is_field_included) wp-includes/rest-api.php | Given an array of fields to include in a response, some of which may be `nested.fields`, determine whether the provided field should be included in the response body. |
| [wp\_list\_filter()](../../functions/wp_list_filter) wp-includes/functions.php | Filters a list of objects, based on a set of key => value arguments. |
| [is\_sticky()](../../functions/is_sticky) wp-includes/post.php | Determines whether a post is sticky. |
| [get\_the\_title()](../../functions/get_the_title) wp-includes/post-template.php | Retrieves the post title. |
| [post\_password\_required()](../../functions/post_password_required) wp-includes/post-template.php | Determines whether the post requires password and whether a correct password has been provided. |
| [get\_page\_template\_slug()](../../functions/get_page_template_slug) wp-includes/post-template.php | Gets the specific template filename for a given post. |
| [get\_post\_thumbnail\_id()](../../functions/get_post_thumbnail_id) wp-includes/post-thumbnail-template.php | Retrieves the post thumbnail ID. |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| [get\_object\_taxonomies()](../../functions/get_object_taxonomies) wp-includes/taxonomy.php | Returns the names or objects of the taxonomies which are registered for the requested object or object type, such as a post object or post type name. |
| [block\_version()](../../functions/block_version) wp-includes/blocks.php | Returns the current version of the block format that the content string is using. |
| [wp\_list\_pluck()](../../functions/wp_list_pluck) wp-includes/functions.php | Plucks a certain field out of each object or array in an array. |
| [setup\_postdata()](../../functions/setup_postdata) wp-includes/query.php | Set up global post data. |
| [get\_gmt\_from\_date()](../../functions/get_gmt_from_date) wp-includes/formatting.php | Given a date in the timezone of the site, returns that date in UTC. |
| [get\_the\_terms()](../../functions/get_the_terms) wp-includes/category-template.php | Retrieves the terms of the taxonomy that are attached to the post. |
| [get\_sample\_permalink()](../../functions/get_sample_permalink) wp-admin/includes/post.php | Returns a sample permalink based on the post name. |
| [is\_post\_type\_viewable()](../../functions/is_post_type_viewable) wp-includes/post.php | Determines whether a post type is considered “viewable”. |
| [WP\_REST\_Posts\_Controller::can\_access\_password\_content()](can_access_password_content) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if the user can access password-protected content. |
| [WP\_REST\_Posts\_Controller::prepare\_date\_response()](prepare_date_response) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks the post\_date\_gmt or modified\_gmt and prepare any post or modified date for single post output. |
| [WP\_REST\_Posts\_Controller::prepare\_links()](prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares links for the request. |
| [WP\_REST\_Posts\_Controller::get\_available\_actions()](get_available_actions) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Gets the link relations available for the post and current user. |
| [get\_post\_format()](../../functions/get_post_format) wp-includes/post-formats.php | Retrieve the format slug for a post |
| [get\_permalink()](../../functions/get_permalink) wp-includes/link-template.php | Retrieves the full permalink for the current post or post ID. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::prepare\_item\_for\_response()](../wp_rest_attachments_controller/prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Prepares a single attachment output for response. |
| [WP\_REST\_Posts\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Creates a single post. |
| [WP\_REST\_Posts\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Updates a single post. |
| [WP\_REST\_Posts\_Controller::delete\_item()](delete_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Deletes a single post. |
| [WP\_REST\_Posts\_Controller::get\_item()](get_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves a single post. |
| [WP\_REST\_Posts\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves a collection of posts. |
| Version | Description |
| --- | --- |
| [5.9.0](https://developer.wordpress.org/reference/since/5.9.0/) | Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Posts_Controller::prepare_links( WP_Post $post ): array WP\_REST\_Posts\_Controller::prepare\_links( WP\_Post $post ): array
====================================================================
Prepares links for the request.
`$post` [WP\_Post](../wp_post) Required Post object. array Links for the given 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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [wp\_get\_latest\_revision\_id\_and\_total\_count()](../../functions/wp_get_latest_revision_id_and_total_count) wp-includes/revision.php | Returns the latest revision ID and count of revisions for a post. |
| [rest\_get\_route\_for\_post\_type\_items()](../../functions/rest_get_route_for_post_type_items) wp-includes/rest-api.php | Gets the REST API route for a post type. |
| [rest\_get\_route\_for\_taxonomy\_items()](../../functions/rest_get_route_for_taxonomy_items) wp-includes/rest-api.php | Gets the REST API route for a taxonomy. |
| [rest\_get\_route\_for\_post()](../../functions/rest_get_route_for_post) wp-includes/rest-api.php | Gets the REST API route for a post. |
| [get\_object\_taxonomies()](../../functions/get_object_taxonomies) wp-includes/taxonomy.php | Returns the names or objects of the taxonomies which are registered for the requested object or object type, such as a post object or post type name. |
| [get\_post\_thumbnail\_id()](../../functions/get_post_thumbnail_id) wp-includes/post-thumbnail-template.php | Retrieves the post thumbnail ID. |
| [post\_type\_supports()](../../functions/post_type_supports) wp-includes/post.php | Checks a post type’s support for a given feature. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menu\_Items\_Controller::prepare\_links()](../wp_rest_menu_items_controller/prepare_links) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Prepares links for the request. |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post output for response. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::get_items( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Posts\_Controller::get\_items( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
===================================================================================================
Retrieves a collection of posts.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php/)
```
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;
}
```
[apply\_filters( "rest\_{$this->post\_type}\_query", array $args, WP\_REST\_Request $request )](../../hooks/rest_this-post_type_query)
Filters [WP\_Query](../wp_query) arguments when querying posts via the REST API.
| Uses | Description |
| --- | --- |
| [update\_post\_parent\_caches()](../../functions/update_post_parent_caches) wp-includes/post.php | Updates parent post caches for a list of post objects. |
| [remove\_filter()](../../functions/remove_filter) wp-includes/plugin.php | Removes a callback function from a filter hook. |
| [rest\_get\_route\_for\_post\_type\_items()](../../functions/rest_get_route_for_post_type_items) wp-includes/rest-api.php | Gets the REST API route for a post type. |
| [WP\_REST\_Posts\_Controller::prepare\_tax\_query()](prepare_tax_query) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares the ‘tax\_query’ for a collection of posts. |
| [WP\_REST\_Posts\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves the query params for the posts collection. |
| [WP\_REST\_Posts\_Controller::check\_read\_permission()](check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be read. |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post output for response. |
| [WP\_REST\_Posts\_Controller::prepare\_items\_query()](prepare_items_query) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Determines the allowed query\_vars for a get\_items() response and prepares them for [WP\_Query](../wp_query). |
| [post\_type\_supports()](../../functions/post_type_supports) wp-includes/post.php | Checks a post type’s support for a given feature. |
| [update\_post\_thumbnail\_cache()](../../functions/update_post_thumbnail_cache) wp-includes/post-thumbnail-template.php | Updates cache for thumbnails in the current loop. |
| [update\_post\_author\_caches()](../../functions/update_post_author_caches) wp-includes/post.php | Updates post author user caches for a list of post objects. |
| [urlencode\_deep()](../../functions/urlencode_deep) wp-includes/formatting.php | Navigates through an array, object, or scalar, and encodes the values to be used in a URL. |
| [WP\_Query::\_\_construct()](../wp_query/__construct) wp-includes/class-wp-query.php | Constructor. |
| [get\_option()](../../functions/get_option) wp-includes/option.php | Retrieves an option value based on an option name. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [add\_query\_arg()](../../functions/add_query_arg) wp-includes/functions.php | Retrieves a modified URL query string. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::check_assign_terms_permission( WP_REST_Request $request ): bool WP\_REST\_Posts\_Controller::check\_assign\_terms\_permission( WP\_REST\_Request $request ): bool
=================================================================================================
Checks whether current user can assign all terms sent with the current request.
`$request` [WP\_REST\_Request](../wp_rest_request) Required The request object with post and terms data. bool Whether the current user can assign the provided terms.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [get\_object\_taxonomies()](../../functions/get_object_taxonomies) wp-includes/taxonomy.php | Returns the names or objects of the taxonomies which are registered for the requested object or object type, such as a post object or post type name. |
| [wp\_list\_filter()](../../functions/wp_list_filter) wp-includes/functions.php | Filters a list of objects, based on a set of key => value arguments. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [get\_term()](../../functions/get_term) wp-includes/taxonomy.php | Gets all term data from database by term ID. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::update\_item\_permissions\_check()](update_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to update a post. |
| [WP\_REST\_Posts\_Controller::create\_item\_permissions\_check()](create_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to create a post. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Posts_Controller::prepare_taxonomy_limit_schema( array $query_params ): array WP\_REST\_Posts\_Controller::prepare\_taxonomy\_limit\_schema( array $query\_params ): array
============================================================================================
This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.
Prepares the collection schema for including and excluding items by terms.
`$query_params` array Required Collection schema. array Updated schema.
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/)
```
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 |
| --- | --- |
| [get\_object\_taxonomies()](../../functions/get_object_taxonomies) wp-includes/taxonomy.php | Returns the names or objects of the taxonomies which are registered for the requested object or object type, such as a post object or post type name. |
| [wp\_list\_filter()](../../functions/wp_list_filter) wp-includes/functions.php | Filters a list of objects, based on a set of key => value arguments. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves the query params for the posts collection. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::protected_title_format(): string WP\_REST\_Posts\_Controller::protected\_title\_format(): string
===============================================================
Overwrites the default protected title format.
By default, WordPress will show password protected posts with a title of "Protected: %s", as the REST API communicates the protected status of a post in a machine readable format, we remove the "Protected: " prefix.
string Protected title format.
File: `wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php/)
```
public function protected_title_format() {
return '%s';
}
```
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::create_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Posts\_Controller::create\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=====================================================================================================
Creates a single post.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php/)
```
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;
}
```
[do\_action( "rest\_after\_insert\_{$this->post\_type}", WP\_Post $post, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_after_insert_this-post_type)
Fires after a single post is completely created or updated via the REST API.
[do\_action( "rest\_insert\_{$this->post\_type}", WP\_Post $post, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_insert_this-post_type)
Fires after a single post is created or updated via the REST API.
| Uses | Description |
| --- | --- |
| [wp\_after\_insert\_post()](../../functions/wp_after_insert_post) wp-includes/post.php | Fires actions after a post, its terms and meta data has been saved. |
| [stick\_post()](../../functions/stick_post) wp-includes/post.php | Makes a post sticky. |
| [WP\_REST\_Posts\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves the post’s schema, conforming to JSON Schema. |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post output for response. |
| [WP\_REST\_Posts\_Controller::handle\_featured\_media()](handle_featured_media) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Determines the featured media based on a request param. |
| [WP\_REST\_Posts\_Controller::handle\_template()](handle_template) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Sets the template for a post. |
| [WP\_REST\_Posts\_Controller::handle\_terms()](handle_terms) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Updates the post’s terms from a REST request. |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_database()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post for create or update. |
| [set\_post\_format()](../../functions/set_post_format) wp-includes/post-formats.php | Assign a format to a post |
| [rest\_get\_route\_for\_post()](../../functions/rest_get_route_for_post) wp-includes/rest-api.php | Gets the REST API route for a post. |
| [unstick\_post()](../../functions/unstick_post) wp-includes/post.php | Un-sticks a post. |
| [wp\_unique\_post\_slug()](../../functions/wp_unique_post_slug) wp-includes/post.php | Computes a unique slug for the post, when given the desired slug and some post details. |
| [wp\_insert\_post()](../../functions/wp_insert_post) wp-includes/post.php | Inserts or update a post. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [rest\_url()](../../functions/rest_url) wp-includes/rest-api.php | Retrieves the URL to a REST endpoint. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::prepare_date_response( string $date_gmt, string|null $date = null ): string|null WP\_REST\_Posts\_Controller::prepare\_date\_response( string $date\_gmt, string|null $date = null ): string|null
================================================================================================================
Checks the post\_date\_gmt or modified\_gmt and prepare any post or modified date for single post output.
`$date_gmt` string Required GMT publication time. `$date` string|null Optional Local publication time. Default: `null`
string|null ISO8601/RFC3339 formatted datetime.
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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [mysql\_to\_rfc3339()](../../functions/mysql_to_rfc3339) wp-includes/functions.php | Parses and formats a MySQL datetime (Y-m-d H:i:s) for ISO8601 (Y-m-d\TH:i:s). |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post output for response. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::prepare_items_query( array $prepared_args = array(), WP_REST_Request $request = null ): array WP\_REST\_Posts\_Controller::prepare\_items\_query( array $prepared\_args = array(), WP\_REST\_Request $request = null ): array
===============================================================================================================================
Determines the allowed query\_vars for a get\_items() response and prepares them for [WP\_Query](../wp_query).
`$prepared_args` array Optional Prepared [WP\_Query](../wp_query) arguments. Default: `array()`
`$request` [WP\_REST\_Request](../wp_rest_request) Optional Full details about the request. Default: `null`
array Items query arguments.
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/)
```
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;
}
```
[apply\_filters( "rest\_query\_var-{$key}", string $value )](../../hooks/rest_query_var-key)
Filters the query\_vars used in get\_items() for the constructed query.
| Uses | Description |
| --- | --- |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menu\_Items\_Controller::prepare\_items\_query()](../wp_rest_menu_items_controller/prepare_items_query) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Determines the allowed query\_vars for a get\_items() response and prepares them for [WP\_Query](../wp_query). |
| [WP\_REST\_Attachments\_Controller::prepare\_items\_query()](../wp_rest_attachments_controller/prepare_items_query) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Determines the allowed query\_vars for a get\_items() response and prepares for [WP\_Query](../wp_query). |
| [WP\_REST\_Posts\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves a collection of posts. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::update_item( WP_REST_Request $request ): WP_REST_Response|WP_Error WP\_REST\_Posts\_Controller::update\_item( WP\_REST\_Request $request ): WP\_REST\_Response|WP\_Error
=====================================================================================================
Updates a single post.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. [WP\_REST\_Response](../wp_rest_response)|[WP\_Error](../wp_error) Response object on success, or [WP\_Error](../wp_error) object on failure.
File: `wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php/)
```
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 );
}
```
[do\_action( "rest\_after\_insert\_{$this->post\_type}", WP\_Post $post, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_after_insert_this-post_type)
Fires after a single post is completely created or updated via the REST API.
[do\_action( "rest\_insert\_{$this->post\_type}", WP\_Post $post, WP\_REST\_Request $request, bool $creating )](../../hooks/rest_insert_this-post_type)
Fires after a single post is created or updated via the REST API.
| Uses | Description |
| --- | --- |
| [wp\_after\_insert\_post()](../../functions/wp_after_insert_post) wp-includes/post.php | Fires actions after a post, its terms and meta data has been saved. |
| [unstick\_post()](../../functions/unstick_post) wp-includes/post.php | Un-sticks a post. |
| [WP\_REST\_Posts\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves the post’s schema, conforming to JSON Schema. |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_response()](prepare_item_for_response) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post output for response. |
| [WP\_REST\_Posts\_Controller::handle\_featured\_media()](handle_featured_media) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Determines the featured media based on a request param. |
| [WP\_REST\_Posts\_Controller::handle\_template()](handle_template) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Sets the template for a post. |
| [WP\_REST\_Posts\_Controller::handle\_terms()](handle_terms) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Updates the post’s terms from a REST request. |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_database()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post for create or update. |
| [set\_post\_format()](../../functions/set_post_format) wp-includes/post-formats.php | Assign a format to a post |
| [WP\_REST\_Posts\_Controller::get\_post()](get_post) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Gets the post, if the ID is valid. |
| [wp\_unique\_post\_slug()](../../functions/wp_unique_post_slug) wp-includes/post.php | Computes a unique slug for the post, when given the desired slug and some post details. |
| [wp\_update\_post()](../../functions/wp_update_post) wp-includes/post.php | Updates a post with new post data. |
| [stick\_post()](../../functions/stick_post) wp-includes/post.php | Makes a post sticky. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [wp\_slash()](../../functions/wp_slash) wp-includes/formatting.php | Adds slashes to a string or recursively adds slashes to strings within an array. |
| [do\_action()](../../functions/do_action) wp-includes/plugin.php | Calls the callback functions that have been added to an action hook. |
| [rest\_ensure\_response()](../../functions/rest_ensure_response) wp-includes/rest-api.php | Ensures a REST response is a response object (for consistency). |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::update\_item()](../wp_rest_attachments_controller/update_item) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Updates a single attachment. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Posts_Controller::delete_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Posts\_Controller::delete\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
===========================================================================================================
Checks if a given request has access to delete a post.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has access to delete the item, [WP\_Error](../wp_error) object otherwise.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::get\_post()](get_post) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Gets the post, if the ID is valid. |
| [WP\_REST\_Posts\_Controller::check\_delete\_permission()](check_delete_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be deleted. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::handle_featured_media( int $featured_media, int $post_id ): bool|WP_Error WP\_REST\_Posts\_Controller::handle\_featured\_media( int $featured\_media, int $post\_id ): bool|WP\_Error
===========================================================================================================
Determines the featured media based on a request param.
`$featured_media` int Required Featured Media ID. `$post_id` int Required Post ID. bool|[WP\_Error](../wp_error) Whether the post thumbnail was successfully deleted, otherwise [WP\_Error](../wp_error).
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/)
```
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 );
}
}
```
| Uses | Description |
| --- | --- |
| [delete\_post\_thumbnail()](../../functions/delete_post_thumbnail) wp-includes/post.php | Removes the thumbnail (featured image) from the given post. |
| [set\_post\_thumbnail()](../../functions/set_post_thumbnail) wp-includes/post.php | Sets the post thumbnail (featured image) for the given post. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Creates a single post. |
| [WP\_REST\_Posts\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Updates a single post. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::check_create_permission( WP_Post $post ): bool WP\_REST\_Posts\_Controller::check\_create\_permission( WP\_Post $post ): bool
==============================================================================
Checks if a post can be created.
`$post` [WP\_Post](../wp_post) Required Post object. bool Whether the post can be created.
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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::check\_is\_post\_type\_allowed()](check_is_post_type_allowed) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given post type can be viewed or managed. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::check_delete_permission( WP_Post $post ): bool WP\_REST\_Posts\_Controller::check\_delete\_permission( WP\_Post $post ): bool
==============================================================================
Checks if a post can be deleted.
`$post` [WP\_Post](../wp_post) Required Post object. bool Whether the post can be deleted.
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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::check\_is\_post\_type\_allowed()](check_is_post_type_allowed) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given post type can be viewed or managed. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::delete\_item\_permissions\_check()](delete_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to delete a post. |
| [WP\_REST\_Posts\_Controller::delete\_item()](delete_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Deletes a single post. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::prepare_item_for_database( WP_REST_Request $request ): stdClass|WP_Error WP\_REST\_Posts\_Controller::prepare\_item\_for\_database( WP\_REST\_Request $request ): stdClass|WP\_Error
===========================================================================================================
Prepares a single post for create or update.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Request object. stdClass|[WP\_Error](../wp_error) Post object or [WP\_Error](../wp_error).
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/)
```
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 );
}
```
[apply\_filters( "rest\_pre\_insert\_{$this->post\_type}", stdClass $prepared\_post, WP\_REST\_Request $request )](../../hooks/rest_pre_insert_this-post_type)
Filters a post before it is inserted via the REST API.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::get\_post()](get_post) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Gets the post, if the ID is valid. |
| [WP\_REST\_Posts\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves the post’s schema, conforming to JSON Schema. |
| [WP\_REST\_Posts\_Controller::handle\_status\_param()](handle_status_param) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Determines validity and normalizes the given status parameter. |
| [rest\_get\_date\_with\_gmt()](../../functions/rest_get_date_with_gmt) wp-includes/rest-api.php | Parses a date into both its local and UTC equivalent, in MySQL datetime format. |
| [post\_password\_required()](../../functions/post_password_required) wp-includes/post-template.php | Determines whether the post requires password and whether a correct password has been provided. |
| [is\_sticky()](../../functions/is_sticky) wp-includes/post.php | Determines whether a post is sticky. |
| [get\_post\_type()](../../functions/get_post_type) wp-includes/post.php | Retrieves the post type of the current post or of a given post. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_userdata()](../../functions/get_userdata) wp-includes/pluggable.php | Retrieves user info by user ID. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::prepare\_item\_for\_database()](../wp_rest_attachments_controller/prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Prepares a single attachment for create or update. |
| [WP\_REST\_Posts\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Creates a single post. |
| [WP\_REST\_Posts\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Updates a single post. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::get_items_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Posts\_Controller::get\_items\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
=========================================================================================================
Checks if a given request has access to read posts.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menu\_Items\_Controller::get\_items\_permissions\_check()](../wp_rest_menu_items_controller/get_items_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Checks if a given request has access to read menu items. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Posts_Controller::update_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Posts\_Controller::update\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
===========================================================================================================
Checks if a given request has access to update a post.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has access to update the item, [WP\_Error](../wp_error) object otherwise.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::get\_post()](get_post) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Gets the post, if the ID is valid. |
| [WP\_REST\_Posts\_Controller::check\_update\_permission()](check_update_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be edited. |
| [WP\_REST\_Posts\_Controller::check\_assign\_terms\_permission()](check_assign_terms_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks whether current user can assign all terms sent with the current request. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_current\_user\_id()](../../functions/get_current_user_id) wp-includes/user.php | Gets the current user’s ID. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::check_is_post_type_allowed( WP_Post_Type|string $post_type ): bool WP\_REST\_Posts\_Controller::check\_is\_post\_type\_allowed( WP\_Post\_Type|string $post\_type ): bool
======================================================================================================
Checks if a given post type can be viewed or managed.
`$post_type` [WP\_Post\_Type](../wp_post_type)|string Required Post type name or object. bool Whether the post type is allowed in REST.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::check\_read\_permission()](check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be read. |
| [WP\_REST\_Posts\_Controller::check\_update\_permission()](check_update_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be edited. |
| [WP\_REST\_Posts\_Controller::check\_create\_permission()](check_create_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be created. |
| [WP\_REST\_Posts\_Controller::check\_delete\_permission()](check_delete_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be deleted. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::check_password_required( bool $required, WP_Post $post ): bool WP\_REST\_Posts\_Controller::check\_password\_required( bool $required, WP\_Post $post ): bool
==============================================================================================
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.
`$required` bool Required Whether the post requires a password check. `$post` [WP\_Post](../wp_post) Required The post been password checked. bool Result of password check taking in to account REST API considerations.
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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Version | Description |
| --- | --- |
| [5.7.1](https://developer.wordpress.org/reference/since/5.7.1/) | Introduced. |
wordpress WP_REST_Posts_Controller::handle_template( string $template, int $post_id, bool $validate = false ) WP\_REST\_Posts\_Controller::handle\_template( string $template, int $post\_id, bool $validate = false )
========================================================================================================
Sets the template for a post.
`$template` string Required Page template filename. `$post_id` int Required Post ID. `$validate` bool Optional Whether to validate that the template selected is valid. Default: `false`
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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [update\_post\_meta()](../../functions/update_post_meta) wp-includes/post.php | Updates a post meta field based on the given post ID. |
| [WP\_Theme::get\_page\_templates()](../wp_theme/get_page_templates) wp-includes/class-wp-theme.php | Returns the theme’s post templates for a given post type. |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Creates a single post. |
| [WP\_REST\_Posts\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Updates a single post. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Added the `$validate` parameter. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::sanitize_post_statuses( string|array $statuses, WP_REST_Request $request, string $parameter ): array|WP_Error WP\_REST\_Posts\_Controller::sanitize\_post\_statuses( string|array $statuses, WP\_REST\_Request $request, string $parameter ): array|WP\_Error
===============================================================================================================================================
Sanitizes and validates the list of post statuses, including whether the user can query private statuses.
`$statuses` string|array Required One or more post statuses. `$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. `$parameter` string Required Additional parameter to pass to validation. array|[WP\_Error](../wp_error) A list of valid statuses, otherwise [WP\_Error](../wp_error) object.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [rest\_validate\_request\_arg()](../../functions/rest_validate_request_arg) wp-includes/rest-api.php | Validate a request argument based on details registered to the route. |
| [wp\_parse\_slug\_list()](../../functions/wp_parse_slug_list) wp-includes/functions.php | Cleans up an array, comma- or space-separated list of slugs. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::handle_status_param( string $post_status, WP_Post_Type $post_type ): string|WP_Error WP\_REST\_Posts\_Controller::handle\_status\_param( string $post\_status, WP\_Post\_Type $post\_type ): string|WP\_Error
========================================================================================================================
Determines validity and normalizes the given status parameter.
`$post_status` string Required Post status. `$post_type` [WP\_Post\_Type](../wp_post_type) Required Post type. string|[WP\_Error](../wp_error) Post status or [WP\_Error](../wp_error) if lacking the proper permission.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [get\_post\_status\_object()](../../functions/get_post_status_object) wp-includes/post.php | Retrieves a post status object by name. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::prepare\_item\_for\_database()](prepare_item_for_database) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares a single post for create or update. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::register_routes() WP\_REST\_Posts\_Controller::register\_routes()
===============================================
Registers the routes for posts.
* [register\_rest\_route()](../../functions/register_rest_route)
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/)
```
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' ),
)
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::get\_collection\_params()](get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves the query params for the posts collection. |
| [WP\_REST\_Posts\_Controller::get\_item\_schema()](get_item_schema) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves the post’s schema, conforming to JSON Schema. |
| [register\_rest\_route()](../../functions/register_rest_route) wp-includes/rest-api.php | Registers a REST API route. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Attachments\_Controller::register\_routes()](../wp_rest_attachments_controller/register_routes) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Registers the routes for attachments. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
wordpress WP_REST_Posts_Controller::handle_terms( int $post_id, WP_REST_Request $request ): null|WP_Error WP\_REST\_Posts\_Controller::handle\_terms( int $post\_id, WP\_REST\_Request $request ): null|WP\_Error
=======================================================================================================
Updates the post’s terms from a REST request.
`$post_id` int Required The post ID to update the terms form. `$request` [WP\_REST\_Request](../wp_rest_request) Required The request object with post and terms data. null|[WP\_Error](../wp_error) [WP\_Error](../wp_error) on an error assigning any of the terms, otherwise null.
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/)
```
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;
}
}
}
```
| Uses | Description |
| --- | --- |
| [wp\_list\_filter()](../../functions/wp_list_filter) wp-includes/functions.php | Filters a list of objects, based on a set of key => value arguments. |
| [wp\_set\_object\_terms()](../../functions/wp_set_object_terms) wp-includes/taxonomy.php | Creates term and taxonomy relationships. |
| [get\_object\_taxonomies()](../../functions/get_object_taxonomies) wp-includes/taxonomy.php | Returns the names or objects of the taxonomies which are registered for the requested object or object type, such as a post object or post type name. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::create\_item()](create_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Creates a single post. |
| [WP\_REST\_Posts\_Controller::update\_item()](update_item) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Updates a single post. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::get_collection_params(): array WP\_REST\_Posts\_Controller::get\_collection\_params(): array
=============================================================
Retrieves the query params for the posts collection.
array Collection parameters.
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/)
```
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 );
}
```
[apply\_filters( "rest\_{$this->post\_type}\_collection\_params", array $query\_params, WP\_Post\_Type $post\_type )](../../hooks/rest_this-post_type_collection_params)
Filters collection parameters for the posts controller.
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::prepare\_taxonomy\_limit\_schema()](prepare_taxonomy_limit_schema) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Prepares the collection schema for including and excluding items by terms. |
| [WP\_REST\_Controller::get\_collection\_params()](../wp_rest_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-controller.php | Retrieves the query params for the collections. |
| [post\_type\_supports()](../../functions/post_type_supports) wp-includes/post.php | Checks a post type’s support for a given feature. |
| [get\_post\_stati()](../../functions/get_post_stati) wp-includes/post.php | Gets a list of post statuses. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [apply\_filters()](../../functions/apply_filters) wp-includes/plugin.php | Calls the callback functions that have been added to a filter hook. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menu\_Items\_Controller::get\_collection\_params()](../wp_rest_menu_items_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Retrieves the query params for the posts collection. |
| [WP\_REST\_Attachments\_Controller::get\_collection\_params()](../wp_rest_attachments_controller/get_collection_params) wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php | Retrieves the query params for collections of attachments. |
| [WP\_REST\_Posts\_Controller::register\_routes()](register_routes) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Registers the routes for posts. |
| [WP\_REST\_Posts\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves a collection of posts. |
| Version | Description |
| --- | --- |
| [5.7.0](https://developer.wordpress.org/reference/since/5.7.0/) | The `modified_after` and `modified_before` query parameters were added. |
| [5.4.0](https://developer.wordpress.org/reference/since/5.4.0/) | The `tax_relation` query parameter was added. |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::check_read_permission( WP_Post $post ): bool WP\_REST\_Posts\_Controller::check\_read\_permission( WP\_Post $post ): bool
============================================================================
Checks if a post can be read.
Correctly handles posts with the inherit status.
`$post` [WP\_Post](../wp_post) Required Post object. bool Whether the post can be read.
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/)
```
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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::check\_is\_post\_type\_allowed()](check_is_post_type_allowed) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given post type can be viewed or managed. |
| [WP\_REST\_Posts\_Controller::check\_read\_permission()](check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be read. |
| [get\_post\_status\_object()](../../functions/get_post_status_object) wp-includes/post.php | Retrieves a post status object by name. |
| [current\_user\_can()](../../functions/current_user_can) wp-includes/capabilities.php | Returns whether the current user has the specified capability. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Blocks\_Controller::check\_read\_permission()](../wp_rest_blocks_controller/check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-blocks-controller.php | Checks if a block can be read. |
| [WP\_REST\_Posts\_Controller::check\_read\_permission()](check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be read. |
| [WP\_REST\_Posts\_Controller::get\_item\_permissions\_check()](get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a given request has access to read a post. |
| [WP\_REST\_Posts\_Controller::get\_items()](get_items) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Retrieves a collection of posts. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::check_template( string $template, WP_REST_Request $request ): bool|WP_Error WP\_REST\_Posts\_Controller::check\_template( string $template, WP\_REST\_Request $request ): bool|WP\_Error
============================================================================================================
Checks whether the template is valid for the given post.
`$template` string Required Page template filename. `$request` [WP\_REST\_Request](../wp_rest_request) Required Request. bool|[WP\_Error](../wp_error) True if template is still valid or if the same as existing value, or false if template not supported.
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/)
```
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 ) ) )
);
}
```
| Uses | Description |
| --- | --- |
| [WP\_Theme::get\_page\_templates()](../wp_theme/get_page_templates) wp-includes/class-wp-theme.php | Returns the theme’s post templates for a given post type. |
| [get\_page\_template\_slug()](../../functions/get_page_template_slug) wp-includes/post-template.php | Gets the specific template filename for a given post. |
| [wp\_get\_theme()](../../functions/wp_get_theme) wp-includes/theme.php | Gets a [WP\_Theme](../wp_theme) object for a theme. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [get\_post()](../../functions/get_post) wp-includes/post.php | Retrieves post data given a post ID or post object. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Version | Description |
| --- | --- |
| [4.9.0](https://developer.wordpress.org/reference/since/4.9.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::__construct( string $post_type ) WP\_REST\_Posts\_Controller::\_\_construct( string $post\_type )
================================================================
Constructor.
`$post_type` string Required Post type. 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/)
```
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 );
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Post\_Meta\_Fields::\_\_construct()](../wp_rest_post_meta_fields/__construct) wp-includes/rest-api/fields/class-wp-rest-post-meta-fields.php | Constructor. |
| [get\_post\_type\_object()](../../functions/get_post_type_object) wp-includes/post.php | Retrieves a post type object by name. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Autosaves\_Controller::\_\_construct()](../wp_rest_autosaves_controller/__construct) wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php | Constructor. |
| [WP\_REST\_Revisions\_Controller::\_\_construct()](../wp_rest_revisions_controller/__construct) wp-includes/rest-api/endpoints/class-wp-rest-revisions-controller.php | Constructor. |
| [WP\_REST\_Comments\_Controller::check\_read\_post\_permission()](../wp_rest_comments_controller/check_read_post_permission) wp-includes/rest-api/endpoints/class-wp-rest-comments-controller.php | Checks if the post can be read. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
wordpress WP_REST_Posts_Controller::get_item_permissions_check( WP_REST_Request $request ): true|WP_Error WP\_REST\_Posts\_Controller::get\_item\_permissions\_check( WP\_REST\_Request $request ): true|WP\_Error
========================================================================================================
Checks if a given request has access to read a post.
`$request` [WP\_REST\_Request](../wp_rest_request) Required Full details about the request. true|[WP\_Error](../wp_error) True if the request has read access for the item, [WP\_Error](../wp_error) object otherwise.
File: `wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php`. [View all references](https://developer.wordpress.org/reference/files/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php/)
```
public function get_item_permissions_check( $request ) {
$post = $this->get_post( $request['id'] );
if ( is_wp_error( $post ) ) {
return $post;
}
if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) {
return new WP_Error(
'rest_forbidden_context',
__( 'Sorry, you are not allowed to edit this 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;
}
```
| Uses | Description |
| --- | --- |
| [WP\_REST\_Posts\_Controller::get\_post()](get_post) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Gets the post, if the ID is valid. |
| [WP\_REST\_Posts\_Controller::check\_update\_permission()](check_update_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be edited. |
| [WP\_REST\_Posts\_Controller::check\_read\_permission()](check_read_permission) wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | Checks if a post can be read. |
| [rest\_authorization\_required\_code()](../../functions/rest_authorization_required_code) wp-includes/rest-api.php | Returns a contextual HTTP error code for authorization failure. |
| [\_\_()](../../functions/__) wp-includes/l10n.php | Retrieves the translation of $text. |
| [add\_filter()](../../functions/add_filter) wp-includes/plugin.php | Adds a callback function to a filter hook. |
| [is\_wp\_error()](../../functions/is_wp_error) wp-includes/load.php | Checks whether the given variable is a WordPress Error. |
| [WP\_Error::\_\_construct()](../wp_error/__construct) wp-includes/class-wp-error.php | Initializes the error. |
| Used By | Description |
| --- | --- |
| [WP\_REST\_Menu\_Items\_Controller::get\_item\_permissions\_check()](../wp_rest_menu_items_controller/get_item_permissions_check) wp-includes/rest-api/endpoints/class-wp-rest-menu-items-controller.php | Checks if a given request has access to read a menu item if they have access to edit them. |
| Version | Description |
| --- | --- |
| [4.7.0](https://developer.wordpress.org/reference/since/4.7.0/) | Introduced. |
| programming_docs |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.