pt data. Default true.
* @return string|false Script data on success, false otherwise.
*/
public function print_inline_script( $handle, $position = 'after', $display = true ) {
_deprecated_function( __METHOD__, '6.3.0', 'WP_Scripts::get_inline_script_data() or WP_Scripts::get_inline_script_tag()' );
$output = $this->get_inline_script_data( $handle, $position );
if ( empty( $output ) ) {
return false;
}
if ( $display ) {
echo $this->get_inline_script_tag( $handle, $position );
}
return $output;
}
/**
* Gets data for inline scripts registered for a specific handle.
*
* @since 6.3.0
*
* @param string $handle Name of the script to get data for.
* Must be lowercase.
* @param string $position Optional. Whether to add the inline script
* before the handle or after. Default 'after'.
* @return string Inline script, which may be empty string.
*/
public function get_inline_script_data( $handle, $position = 'after' ) {
$data = $this->get_data( $handle, $position );
if ( empty( $data ) || ! is_array( $data ) ) {
return '';
}
return trim( implode( "\n", $data ), "\n" );
}
/**
* Gets unaliased dependencies.
*
* An alias is a dependency whose src is false. It is used as a way to bundle multiple dependencies in a single
* handle. This in effect flattens an alias dependency tree.
*
* @since 6.3.0
*
* @param string[] $deps Dependency handles.
* @return string[] Unaliased handles.
*/
private function get_unaliased_deps( array $deps ) {
$flattened = array();
foreach ( $deps as $dep ) {
if ( ! isset( $this->registered[ $dep ] ) ) {
continue;
}
if ( $this->registered[ $dep ]->src ) {
$flattened[] = $dep;
} elseif ( $this->registered[ $dep ]->deps ) {
array_push( $flattened, ...$this->get_unaliased_deps( $this->registered[ $dep ]->deps ) );
}
}
return $flattened;
}
/**
* Gets tags for inline scripts registered for a specific handle.
*
* @since 6.3.0
*
* @param string $handle Name of the script to get associated inline script tag for.
* Must be lowercase.
* @param string $position Optional. Whether to get tag for inline
* scripts in the before or after position. Default 'after'.
* @return string Inline script, which may be empty string.
*/
public function get_inline_script_tag( $handle, $position = 'after' ) {
$js = $this->get_inline_script_data( $handle, $position );
if ( empty( $js ) ) {
return '';
}
$id = "{$handle}-js-{$position}";
return wp_get_inline_script_tag( $js, compact( 'id' ) );
}
/**
* Localizes a script, only if the script has already been added.
*
* @since 2.1.0
*
* @param string $handle Name of the script to attach data to.
* @param string $object_name Name of the variable that will contain the data.
* @param array $l10n Array of data to localize.
* @return bool True on success, false on failure.
*/
public function localize( $handle, $object_name, $l10n ) {
if ( 'jquery' === $handle ) {
$handle = 'jquery-core';
}
if ( is_array( $l10n ) && isset( $l10n['l10n_print_after'] ) ) { // back compat, preserve the code in 'l10n_print_after' if present.
$after = $l10n['l10n_print_after'];
unset( $l10n['l10n_print_after'] );
}
if ( ! is_array( $l10n ) ) {
_doing_it_wrong(
__METHOD__,
sprintf(
/* translators: 1: $l10n, 2: wp_add_inline_script() */
__( 'The %1$s parameter must be an array. To pass arbitrary data to scripts, use the %2$s function instead.' ),
'$l10n
',
'wp_add_inline_script()
'
),
'5.7.0'
);
if ( false === $l10n ) {
// This should really not be needed, but is necessary for backward compatibility.
$l10n = array( $l10n );
}
}
if ( is_string( $l10n ) ) {
$l10n = html_entity_decode( $l10n, ENT_QUOTES, 'UTF-8' );
} elseif ( is_array( $l10n ) ) {
foreach ( $l10n as $key => $value ) {
if ( ! is_scalar( $value ) ) {
continue;
}
$l10n[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
}
}
$script = "var $object_name = " . wp_json_encode( $l10n ) . ';';
if ( ! empty( $after ) ) {
$script .= "\n$after;";
}
$data = $this->get_data( $handle, 'data' );
if ( ! empty( $data ) ) {
$script = "$data\n$script";
}
return $this->add_data( $handle, 'data', $script );
}
/**
* Sets handle group.
*
* @since 2.8.0
*
* @see WP_Dependencies::set_group()
*
* @param string $handle Name of the item. Should be unique.
* @param bool $recursion Internal flag that calling function was called recursively.
* @param int|false $group Optional. Group level: level (int), no groups (false).
* Default false.
* @return bool Not already in the group or a lower group.
*/
public function set_group( $handle, $recursion, $group = false ) {
if ( isset( $this->registered[ $handle ]->args ) && 1 === $this->registered[ $handle ]->args ) {
$grp = 1;
} else {
$grp = (int) $this->get_data( $handle, 'group' );
}
if ( false !== $group && $grp > $group ) {
$grp = $group;
}
return parent::set_group( $handle, $recursion, $grp );
}
/**
* Sets a translation textdomain.
*
* @since 5.0.0
* @since 5.1.0 The `$domain` parameter was made optional.
*
* @param string $handle Name of the script to register a translation domain to.
* @param string $domain Optional. Text domain. Default 'default'.
* @param string $path Optional. The full file path to the directory containing translation files.
* @return bool True if the text domain was registered, false if not.
*/
public function set_translations( $handle, $domain = 'default', $path = '' ) {
if ( ! isset( $this->registered[ $handle ] ) ) {
return false;
}
/** @var \_WP_Dependency $obj */
$obj = $this->registered[ $handle ];
if ( ! in_array( 'wp-i18n', $obj->deps, true ) ) {
$obj->deps[] = 'wp-i18n';
}
return $obj->set_translations( $domain, $path );
}
/**
* Prints translations set for a specific handle.
*
* @since 5.0.0
*
* @param string $handle Name of the script to add the inline script to.
* Must be lowercase.
* @param bool $display Optional. Whether to print the script
* instead of just returning it. Default true.
* @return string|false Script on success, false otherwise.
*/
public function print_translations( $handle, $display = true ) {
if ( ! isset( $this->registered[ $handle ] ) || empty( $this->registered[ $handle ]->textdomain ) ) {
return false;
}
$domain = $this->registered[ $handle ]->textdomain;
$path = '';
if ( isset( $this->registered[ $handle ]->translations_path ) ) {
$path = $this->registered[ $handle ]->translations_path;
}
$json_translations = load_script_textdomain( $handle, $domain, $path );
if ( ! $json_translations ) {
return false;
}
$output = <<\n%s\n\n", $this->type_attr, esc_attr( $handle ), $output );
}
return $output;
}
/**
* Determines script dependencies.
*
* @since 2.1.0
*
* @see WP_Dependencies::all_deps()
*
* @param string|string[] $handles Item handle (string) or item handles (array of strings).
* @param bool $recursion Optional. Internal flag that function is calling itself.
* Default false.
* @param int|false $group Optional. Group level: level (int), no groups (false).
* Default false.
* @return bool True on success, false on failure.
*/
public function all_deps( $handles, $recursion = false, $group = false ) {
$r = parent::all_deps( $handles, $recursion, $group );
if ( ! $recursion ) {
/**
* Filters the list of script dependencies left to print.
*
* @since 2.3.0
*
* @param string[] $to_do An array of script dependency handles.
*/
$this->to_do = apply_filters( 'print_scripts_array', $this->to_do );
}
return $r;
}
/**
* Processes items and dependencies for the head group.
*
* @since 2.8.0
*
* @see WP_Dependencies::do_items()
*
* @return string[] Handles of items that have been processed.
*/
public function do_head_items() {
$this->do_items( false, 0 );
return $this->done;
}
/**
* Processes items and dependencies for the footer group.
*
* @since 2.8.0
*
* @see WP_Dependencies::do_items()
*
* @return string[] Handles of items that have been processed.
*/
public function do_footer_items() {
$this->do_items( false, 1 );
return $this->done;
}
/**
* Whether a handle's source is in a default directory.
*
* @since 2.8.0
*
* @param string $src The source of the enqueued script.
* @return bool True if found, false if not.
*/
public function in_default_dir( $src ) {
if ( ! $this->default_dirs ) {
return true;
}
if ( str_starts_with( $src, '/' . WPINC . '/js/l10n' ) ) {
return false;
}
foreach ( (array) $this->default_dirs as $test ) {
if ( str_starts_with( $src, $test ) ) {
return true;
}
}
return false;
}
/**
* This overrides the add_data method from WP_Dependencies, to support normalizing of $args.
*
* @since 6.3.0
*
* @param string $handle Name of the item. Should be unique.
* @param string $key The data key.
* @param mixed $value The data value.
* @return bool True on success, false on failure.
*/
public function add_data( $handle, $key, $value ) {
if ( ! isset( $this->registered[ $handle ] ) ) {
return false;
}
if ( 'strategy' === $key ) {
if ( ! empty( $value ) && ! $this->is_delayed_strategy( $value ) ) {
_doing_it_wrong(
__METHOD__,
sprintf(
/* translators: 1: $strategy, 2: $handle */
__( 'Invalid strategy `%1$s` defined for `%2$s` during script registration.' ),
$value,
$handle
),
'6.3.0'
);
return false;
} elseif ( ! $this->registered[ $handle ]->src && $this->is_delayed_strategy( $value ) ) {
_doing_it_wrong(
__METHOD__,
sprintf(
/* translators: 1: $strategy, 2: $handle */
__( 'Cannot supply a strategy `%1$s` for script `%2$s` because it is an alias (it lacks a `src` value).' ),
$value,
$handle
),
'6.3.0'
);
return false;
}
}
return parent::add_data( $handle, $key, $value );
}
/**
* Gets all dependents of a script.
*
* @since 6.3.0
*
* @param string $handle The script handle.
* @return string[] Script handles.
*/
private function get_dependents( $handle ) {
// Check if dependents map for the handle in question is present. If so, use it.
if ( isset( $this->dependents_map[ $handle ] ) ) {
return $this->dependents_map[ $handle ];
}
$dependents = array();
// Iterate over all registered scripts, finding dependents of the script passed to this method.
foreach ( $this->registered as $registered_handle => $args ) {
if ( in_array( $handle, $args->deps, true ) ) {
$dependents[] = $registered_handle;
}
}
// Add the handles dependents to the map to ease future lookups.
$this->dependents_map[ $handle ] = $dependents;
return $dependents;
}
/**
* Checks if the strategy passed is a valid delayed (non-blocking) strategy.
*
* @since 6.3.0
*
* @param string $strategy The strategy to check.
* @return bool True if $strategy is one of the delayed strategies, otherwise false.
*/
private function is_delayed_strategy( $strategy ) {
return in_array(
$strategy,
$this->delayed_strategies,
true
);
}
/**
* Gets the best eligible loading strategy for a script.
*
* @since 6.3.0
*
* @param string $handle The script handle.
* @return string The best eligible loading strategy.
*/
private function get_eligible_loading_strategy( $handle ) {
$intended = (string) $this->get_data( $handle, 'strategy' );
// Bail early if there is no intended strategy.
if ( ! $intended ) {
return '';
}
/*
* If the intended strategy is 'defer', limit the initial list of eligible
* strategies, since 'async' can fallback to 'defer', but not vice-versa.
*/
$initial = ( 'defer' === $intended ) ? array( 'defer' ) : null;
$eligible = $this->filter_eligible_strategies( $handle, $initial );
// Return early once we know the eligible strategy is blocking.
if ( empty( $eligible ) ) {
return '';
}
return in_array( 'async', $eligible, true ) ? 'async' : 'defer';
}
/**
* Filter the list of eligible loading strategies for a script.
*
* @since 6.3.0
*
* @param string $handle The script handle.
* @param string[]|null $eligible Optional. The list of strategies to filter. Default null.
* @param array $checked Optional. An array of already checked script handles, used to avoid recursive loops.
* @return string[] A list of eligible loading strategies that could be used.
*/
private function filter_eligible_strategies( $handle, $eligible = null, $checked = array() ) {
// If no strategies are being passed, all strategies are eligible.
if ( null === $eligible ) {
$eligible = $this->delayed_strategies;
}
// If this handle was already checked, return early.
if ( isset( $checked[ $handle ] ) ) {
return $eligible;
}
// Mark this handle as checked.
$checked[ $handle ] = true;
// If this handle isn't registered, don't filter anything and return.
if ( ! isset( $this->registered[ $handle ] ) ) {
return $eligible;
}
// If the handle is not enqueued, don't filter anything and return.
if ( ! $this->query( $handle, 'enqueued' ) ) {
return $eligible;
}
$is_alias = (bool) ! $this->registered[ $handle ]->src;
$intended_strategy = $this->get_data( $handle, 'strategy' );
// For non-alias handles, an empty intended strategy filters all strategies.
if ( ! $is_alias && empty( $intended_strategy ) ) {
return array();
}
// Handles with inline scripts attached in the 'after' position cannot be delayed.
if ( $this->has_inline_script( $handle, 'after' ) ) {
return array();
}
// If the intended strategy is 'defer', filter out 'async'.
if ( 'defer' === $intended_strategy ) {
$eligible = array( 'defer' );
}
$dependents = $this->get_dependents( $handle );
// Recursively filter eligible strategies for dependents.
foreach ( $dependents as $dependent ) {
// Bail early once we know the eligible strategy is blocking.
if ( empty( $eligible ) ) {
return array();
}
$eligible = $this->filter_eligible_strategies( $dependent, $eligible, $checked );
}
return $eligible;
}
/**
* Gets data for inline scripts registered for a specific handle.
*
* @since 6.3.0
*
* @param string $handle Name of the script to get data for. Must be lowercase.
* @param string $position The position of the inline script.
* @return bool Whether the handle has an inline script (either before or after).
*/
private function has_inline_script( $handle, $position = null ) {
if ( $position && in_array( $position, array( 'before', 'after' ), true ) ) {
return (bool) $this->get_data( $handle, $position );
}
return (bool) ( $this->get_data( $handle, 'before' ) || $this->get_data( $handle, 'after' ) );
}
/**
* Resets class properties.
*
* @since 2.8.0
*/
public function reset() {
$this->do_concat = false;
$this->print_code = '';
$this->concat = '';
$this->concat_version = '';
$this->print_html = '';
$this->ext_version = '';
$this->ext_handles = '';
}
}
'post' === $this->post_type ) {
$schema['properties']['sticky'] = array(
'description' => __( 'Whether or not the post should be treated as sticky.' ),
'type' => 'boolean',
'context' => array( 'view', 'edit' ),
);
}
$schema['properties']['template'] = array(
'description' => __( 'The theme file to use to display the post.' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'arg_options' => array(
'validate_callback' => array( $this, 'check_template' ),
),
);
$taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
foreach ( $taxonomies as $taxonomy ) {
$base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
if ( array_key_exists( $base, $schema['properties'] ) ) {
$taxonomy_field_name_with_conflict = ! empty( $taxonomy->rest_base ) ? 'rest_base' : 'name';
_doing_it_wrong(
'register_taxonomy',
sprintf(
/* translators: 1: The taxonomy name, 2: The property name, either 'rest_base' or 'name', 3: The conflicting value. */
__( 'The "%1$s" taxonomy "%2$s" property (%3$s) conflicts with an existing property on the REST API Posts Controller. Specify a custom "rest_base" when registering the taxonomy to avoid this error.' ),
$taxonomy->name,
$taxonomy_field_name_with_conflict,
$base
),
'5.4.0'
);
}
$schema['properties'][ $base ] = array(
/* translators: %s: Taxonomy name. */
'description' => sprintf( __( 'The terms assigned to the post in the %s taxonomy.' ), $taxonomy->name ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'context' => array( 'view', 'edit' ),
);
}
$schema_links = $this->get_schema_links();
if ( $schema_links ) {
$schema['links'] = $schema_links;
}
// Take a snapshot of which fields are in the schema pre-filtering.
$schema_fields = array_keys( $schema['properties'] );
/**
* Filters the post's schema.
*
* The dynamic portion of the filter, `$this->post_type`, refers to the
* post type slug for the controller.
*
* Possible hook names include:
*
* - `rest_post_item_schema`
* - `rest_page_item_schema`
* - `rest_attachment_item_schema`
*
* @since 5.4.0
*
* @param array $schema Item schema data.
*/
$schema = apply_filters( "rest_{$this->post_type}_item_schema", $schema );
// Emit a _doing_it_wrong warning if user tries to add new properties using this filter.
$new_fields = array_diff( array_keys( $schema['properties'] ), $schema_fields );
if ( count( $new_fields ) > 0 ) {
_doing_it_wrong(
__METHOD__,
sprintf(
/* translators: %s: register_rest_field */
__( 'Please use %s to add new schema properties.' ),
'register_rest_field'
),
'5.4.0'
);
}
$this->schema = $schema;
return $this->add_additional_fields_schema( $this->schema );
}
/**
* Retrieves Link Description Objects that should be added to the Schema for the posts collection.
*
* @since 4.9.8
*
* @return array
*/
protected function get_schema_links() {
$href = rest_url( "{$this->namespace}/{$this->rest_base}/{id}" );
$links = array();
if ( 'attachment' !== $this->post_type ) {
$links[] = array(
'rel' => 'https://api.w.org/action-publish',
'title' => __( 'The current user can publish this post.' ),
'href' => $href,
'targetSchema' => array(
'type' => 'object',
'properties' => array(
'status' => array(
'type' => 'string',
'enum' => array( 'publish', 'future' ),
),
),
),
);
}
$links[] = array(
'rel' => 'https://api.w.org/action-unfiltered-html',
'title' => __( 'The current user can post unfiltered HTML markup and JavaScript.' ),
'href' => $href,
'targetSchema' => array(
'type' => 'object',
'properties' => array(
'content' => array(
'raw' => array(
'type' => 'string',
),
),
),
),
);
if ( 'post' === $this->post_type ) {
$links[] = array(
'rel' => 'https://api.w.org/action-sticky',
'title' => __( 'The current user can sticky this post.' ),
'href' => $href,
'targetSchema' => array(
'type' => 'object',
'properties' => array(
'sticky' => array(
'type' => 'boolean',
),
),
),
);
}
if ( post_type_supports( $this->post_type, 'author' ) ) {
$links[] = array(
'rel' => 'https://api.w.org/action-assign-author',
'title' => __( 'The current user can change the author on this post.' ),
'href' => $href,
'targetSchema' => array(
'type' => 'object',
'properties' => array(
'author' => array(
'type' => 'integer',
),
),
),
);
}
$taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
foreach ( $taxonomies as $tax ) {
$tax_base = ! empty( $tax->rest_base ) ? $tax->rest_base : $tax->name;
/* translators: %s: Taxonomy name. */
$assign_title = sprintf( __( 'The current user can assign terms in the %s taxonomy.' ), $tax->name );
/* translators: %s: Taxonomy name. */
$create_title = sprintf( __( 'The current user can create terms in the %s taxonomy.' ), $tax->name );
$links[] = array(
'rel' => 'https://api.w.org/action-assign-' . $tax_base,
'title' => $assign_title,
'href' => $href,
'targetSchema' => array(
'type' => 'object',
'properties' => array(
$tax_base => array(
'type' => 'array',
'items' => array(
'type' => 'integer',
),
),
),
),
);
$links[] = array(
'rel' => 'https://api.w.org/action-create-' . $tax_base,
'title' => $create_title,
'href' => $href,
'targetSchema' => array(
'type' => 'object',
'properties' => array(
$tax_base => array(
'type' => 'array',
'items' => array(
'type' => 'integer',
),
),
),
),
);
}
return $links;
}
/**
* Retrieves the query params for the posts collection.
*
* @since 4.7.0
* @since 5.4.0 The `tax_relation` query parameter was added.
* @since 5.7.0 The `modified_after` and `modified_before` query parameters were added.
*
* @return array Collection parameters.
*/
public function get_collection_params() {
$query_params = parent::get_collection_params();
$query_params['context']['default'] = 'view';
$query_params['after'] = array(
'description' => __( 'Limit response to posts published after a given ISO8601 compliant date.' ),
'type' => 'string',
'format' => 'date-time',
);
$query_params['modified_after'] = array(
'description' => __( 'Limit response to posts modified after a given ISO8601 compliant date.' ),
'type' => 'string',
'format' => 'date-time',
);
if ( post_type_supports( $this->post_type, 'author' ) ) {
$query_params['author'] = array(
'description' => __( 'Limit result set to posts assigned to specific authors.' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'default' => array(),
);
$query_params['author_exclude'] = array(
'description' => __( 'Ensure result set excludes posts assigned to specific authors.' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'default' => array(),
);
}
$query_params['before'] = array(
'description' => __( 'Limit response to posts published before a given ISO8601 compliant date.' ),
'type' => 'string',
'format' => 'date-time',
);
$query_params['modified_before'] = array(
'description' => __( 'Limit response to posts modified before a given ISO8601 compliant date.' ),
'type' => 'string',
'format' => 'date-time',
);
$query_params['exclude'] = array(
'description' => __( 'Ensure result set excludes specific IDs.' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'default' => array(),
);
$query_params['include'] = array(
'description' => __( 'Limit result set to specific IDs.' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'default' => array(),
);
if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
$query_params['menu_order'] = array(
'description' => __( 'Limit result set to posts with a specific menu_order value.' ),
'type' => 'integer',
);
}
$query_params['offset'] = array(
'description' => __( 'Offset the result set by a specific number of items.' ),
'type' => 'integer',
);
$query_params['order'] = array(
'description' => __( 'Order sort attribute ascending or descending.' ),
'type' => 'string',
'default' => 'desc',
'enum' => array( 'asc', 'desc' ),
);
$query_params['orderby'] = array(
'description' => __( 'Sort collection by post attribute.' ),
'type' => 'string',
'default' => 'date',
'enum' => array(
'author',
'date',
'id',
'include',
'modified',
'parent',
'relevance',
'slug',
'include_slugs',
'title',
),
);
if ( 'page' === $this->post_type || post_type_supports( $this->post_type, 'page-attributes' ) ) {
$query_params['orderby']['enum'][] = 'menu_order';
}
$post_type = get_post_type_object( $this->post_type );
if ( $post_type->hierarchical || 'attachment' === $this->post_type ) {
$query_params['parent'] = array(
'description' => __( 'Limit result set to items with particular parent IDs.' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'default' => array(),
);
$query_params['parent_exclude'] = array(
'description' => __( 'Limit result set to all items except those of a particular parent ID.' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'default' => array(),
);
}
$query_params['search_columns'] = array(
'default' => array(),
'description' => __( 'Array of column names to be searched.' ),
'type' => 'array',
'items' => array(
'enum' => array( 'post_title', 'post_content', 'post_excerpt' ),
'type' => 'string',
),
);
$query_params['slug'] = array(
'description' => __( 'Limit result set to posts with one or more specific slugs.' ),
'type' => 'array',
'items' => array(
'type' => 'string',
),
);
$query_params['status'] = array(
'default' => 'publish',
'description' => __( 'Limit result set to posts assigned one or more statuses.' ),
'type' => 'array',
'items' => array(
'enum' => array_merge( array_keys( get_post_stati() ), array( 'any' ) ),
'type' => 'string',
),
'sanitize_callback' => array( $this, 'sanitize_post_statuses' ),
);
$query_params = $this->prepare_taxonomy_limit_schema( $query_params );
if ( 'post' === $this->post_type ) {
$query_params['sticky'] = array(
'description' => __( 'Limit result set to items that are sticky.' ),
'type' => 'boolean',
);
}
/**
* Filters collection parameters for the posts controller.
*
* The dynamic part of the filter `$this->post_type` refers to the post
* type slug for the controller.
*
* This filter registers the collection parameter, but does not map the
* collection parameter to an internal WP_Query parameter. Use the
* `rest_{$this->post_type}_query` filter to set WP_Query parameters.
*
* @since 4.7.0
*
* @param array $query_params JSON Schema-formatted collection parameters.
* @param WP_Post_Type $post_type Post type object.
*/
return apply_filters( "rest_{$this->post_type}_collection_params", $query_params, $post_type );
}
/**
* Sanitizes and validates the list of post statuses, including whether the
* user can query private statuses.
*
* @since 4.7.0
*
* @param string|array $statuses One or more post statuses.
* @param WP_REST_Request $request Full details about the request.
* @param string $parameter Additional parameter to pass to validation.
* @return array|WP_Error A list of valid statuses, otherwise WP_Error object.
*/
public function sanitize_post_statuses( $statuses, $request, $parameter ) {
$statuses = wp_parse_slug_list( $statuses );
// The default status is different in WP_REST_Attachments_Controller.
$attributes = $request->get_attributes();
$default_status = $attributes['args']['status']['default'];
foreach ( $statuses as $status ) {
if ( $status === $default_status ) {
continue;
}
$post_type_obj = get_post_type_object( $this->post_type );
if ( current_user_can( $post_type_obj->cap->edit_posts ) || 'private' === $status && current_user_can( $post_type_obj->cap->read_private_posts ) ) {
$result = rest_validate_request_arg( $status, $request, $parameter );
if ( is_wp_error( $result ) ) {
return $result;
}
} else {
return new WP_Error(
'rest_forbidden_status',
__( 'Status is forbidden.' ),
array( 'status' => rest_authorization_required_code() )
);
}
}
return $statuses;
}
/**
* Prepares the 'tax_query' for a collection of posts.
*
* @since 5.7.0
*
* @param array $args WP_Query arguments.
* @param WP_REST_Request $request Full details about the request.
* @return array Updated query arguments.
*/
private function prepare_tax_query( array $args, WP_REST_Request $request ) {
$relation = $request['tax_relation'];
if ( $relation ) {
$args['tax_query'] = array( 'relation' => $relation );
}
$taxonomies = wp_list_filter(
get_object_taxonomies( $this->post_type, 'objects' ),
array( 'show_in_rest' => true )
);
foreach ( $taxonomies as $taxonomy ) {
$base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
$tax_include = $request[ $base ];
$tax_exclude = $request[ $base . '_exclude' ];
if ( $tax_include ) {
$terms = array();
$include_children = false;
$operator = 'IN';
if ( rest_is_array( $tax_include ) ) {
$terms = $tax_include;
} elseif ( rest_is_object( $tax_include ) ) {
$terms = empty( $tax_include['terms'] ) ? array() : $tax_include['terms'];
$include_children = ! empty( $tax_include['include_children'] );
if ( isset( $tax_include['operator'] ) && 'AND' === $tax_include['operator'] ) {
$operator = 'AND';
}
}
if ( $terms ) {
$args['tax_query'][] = array(
'taxonomy' => $taxonomy->name,
'field' => 'term_id',
'terms' => $terms,
'include_children' => $include_children,
'operator' => $operator,
);
}
}
if ( $tax_exclude ) {
$terms = array();
$include_children = false;
if ( rest_is_array( $tax_exclude ) ) {
$terms = $tax_exclude;
} elseif ( rest_is_object( $tax_exclude ) ) {
$terms = empty( $tax_exclude['terms'] ) ? array() : $tax_exclude['terms'];
$include_children = ! empty( $tax_exclude['include_children'] );
}
if ( $terms ) {
$args['tax_query'][] = array(
'taxonomy' => $taxonomy->name,
'field' => 'term_id',
'terms' => $terms,
'include_children' => $include_children,
'operator' => 'NOT IN',
);
}
}
}
return $args;
}
/**
* Prepares the collection schema for including and excluding items by terms.
*
* @since 5.7.0
*
* @param array $query_params Collection schema.
* @return array Updated schema.
*/
private function prepare_taxonomy_limit_schema( array $query_params ) {
$taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) );
if ( ! $taxonomies ) {
return $query_params;
}
$query_params['tax_relation'] = array(
'description' => __( 'Limit result set based on relationship between multiple taxonomies.' ),
'type' => 'string',
'enum' => array( 'AND', 'OR' ),
);
$limit_schema = array(
'type' => array( 'object', 'array' ),
'oneOf' => array(
array(
'title' => __( 'Term ID List' ),
'description' => __( 'Match terms with the listed IDs.' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
),
array(
'title' => __( 'Term ID Taxonomy Query' ),
'description' => __( 'Perform an advanced term query.' ),
'type' => 'object',
'properties' => array(
'terms' => array(
'description' => __( 'Term IDs.' ),
'type' => 'array',
'items' => array(
'type' => 'integer',
),
'default' => array(),
),
'include_children' => array(
'description' => __( 'Whether to include child terms in the terms limiting the result set.' ),
'type' => 'boolean',
'default' => false,
),
),
'additionalProperties' => false,
),
),
);
$include_schema = array_merge(
array(
/* translators: %s: Taxonomy name. */
'description' => __( 'Limit result set to items with specific terms assigned in the %s taxonomy.' ),
),
$limit_schema
);
// 'operator' is supported only for 'include' queries.
$include_schema['oneOf'][1]['properties']['operator'] = array(
'description' => __( 'Whether items must be assigned all or any of the specified terms.' ),
'type' => 'string',
'enum' => array( 'AND', 'OR' ),
'default' => 'OR',
);
$exclude_schema = array_merge(
array(
/* translators: %s: Taxonomy name. */
'description' => __( 'Limit result set to items except those with specific terms assigned in the %s taxonomy.' ),
),
$limit_schema
);
foreach ( $taxonomies as $taxonomy ) {
$base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name;
$base_exclude = $base . '_exclude';
$query_params[ $base ] = $include_schema;
$query_params[ $base ]['description'] = sprintf( $query_params[ $base ]['description'], $base );
$query_params[ $base_exclude ] = $exclude_schema;
$query_params[ $base_exclude ]['description'] = sprintf( $query_params[ $base_exclude ]['description'], $base );
if ( ! $taxonomy->hierarchical ) {
unset( $query_params[ $base ]['oneOf'][1]['properties']['include_children'] );
unset( $query_params[ $base_exclude ]['oneOf'][1]['properties']['include_children'] );
}
}
return $query_params;
}
}