/**
* Post API: Walker_Page class
*
* @package WordPress
* @subpackage Template
* @since 4.4.0
*/
/**
* Core walker class used to create an HTML list of pages.
*
* @since 2.1.0
*
* @see Walker
*/
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}
{$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}
{$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 === (int) $current_page_id ) {
$css_class[] = 'current_page_item';
} elseif ( $_current_page && $page->ID === $_current_page->post_parent ) {
$css_class[] = 'current_page_parent';
}
} elseif ( (int) 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 === (int) $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 `` 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(
'
%s%s%s',
$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 .= "
{$n}";
}
}
/**
* Post revision functions.
*
* @package WordPress
* @subpackage Post_Revisions
*/
/**
* Determines which fields of posts are to be saved in revisions.
*
* @since 2.6.0
* @since 4.5.0 A `WP_Post` object can now be passed to the `$post` parameter.
* @since 4.5.0 The optional `$autosave` parameter was deprecated and renamed to `$deprecated`.
* @access private
*
* @param array|WP_Post $post Optional. A post array or a WP_Post object being processed
* for insertion as a post revision. Default empty array.
* @param bool $deprecated Not used.
* @return string[] Array of fields that can be versioned.
*/
function _wp_post_revision_fields( $post = array(), $deprecated = false ) {
static $fields = null;
if ( ! is_array( $post ) ) {
$post = get_post( $post, ARRAY_A );
}
if ( is_null( $fields ) ) {
// Allow these to be versioned.
$fields = array(
'post_title' => __( 'Title' ),
'post_content' => __( 'Content' ),
'post_excerpt' => __( 'Excerpt' ),
);
}
/**
* Filters the list of fields saved in post revisions.
*
* Included by default: 'post_title', 'post_content' and 'post_excerpt'.
*
* Disallowed fields: 'ID', 'post_name', 'post_parent', 'post_date',
* 'post_date_gmt', 'post_status', 'post_type', 'comment_count',
* and 'post_author'.
*
* @since 2.6.0
* @since 4.5.0 The `$post` parameter was added.
*
* @param string[] $fields List of fields to revision. Contains 'post_title',
* 'post_content', and 'post_excerpt' by default.
* @param array $post A post array being processed for insertion as a post revision.
*/
$fields = apply_filters( '_wp_post_revision_fields', $fields, $post );
// WP uses these internally either in versioning or elsewhere - they cannot be versioned.
foreach ( array( 'ID', 'post_name', 'post_parent', 'post_date', 'post_date_gmt', 'post_status', 'post_type', 'comment_count', 'post_author' ) as $protect ) {
unset( $fields[ $protect ] );
}
return $fields;
}
/**
* Returns a post array ready to be inserted into the posts table as a post revision.
*
* @since 4.5.0
* @access private
*
* @param array|WP_Post $post Optional. A post array or a WP_Post object to be processed
* for insertion as a post revision. Default empty array.
* @param bool $autosave Optional. Is the revision an autosave? Default false.
* @return array Post array ready to be inserted as a post revision.
*/
function _wp_post_revision_data( $post = array(), $autosave = false ) {
if ( ! is_array( $post ) ) {
$post = get_post( $post, ARRAY_A );
}
$fields = _wp_post_revision_fields( $post );
$revision_data = array();
foreach ( array_intersect( array_keys( $post ), array_keys( $fields ) ) as $field ) {
$revision_data[ $field ] = $post[ $field ];
}
$revision_data['post_parent'] = $post['ID'];
$revision_data['post_status'] = 'inherit';
$revision_data['post_type'] = 'revision';
$revision_data['post_name'] = $autosave ? "$post[ID]-autosave-v1" : "$post[ID]-revision-v1"; // "1" is the revisioning system version.
$revision_data['post_date'] = isset( $post['post_modified'] ) ? $post['post_modified'] : '';
$revision_data['post_date_gmt'] = isset( $post['post_modified_gmt'] ) ? $post['post_modified_gmt'] : '';
return $revision_data;
}
/**
* Saves revisions for a post after all changes have been made.
*
* @since 6.4.0
*
* @param int $post_id The post id that was inserted.
* @param WP_Post $post The post object that was inserted.
* @param bool $update Whether this insert is updating an existing post.
*/
function wp_save_post_revision_on_insert( $post_id, $post, $update ) {
if ( ! $update ) {
return;
}
if ( ! has_action( 'post_updated', 'wp_save_post_revision' ) ) {
return;
}
wp_save_post_revision( $post_id );
}
/**
* Creates a revision for the current version of a post.
*
* Typically used immediately after a post update, as every update is a revision,
* and the most recent revision always matches the current post.
*
* @since 2.6.0
*
* @param int $post_id The ID of the post to save as a revision.
* @return int|WP_Error|void Void or 0 if error, new revision ID, if success.
*/
function wp_save_post_revision( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Prevent saving post revisions if revisions should be saved on wp_after_insert_post.
if ( doing_action( 'post_updated' ) && has_action( 'wp_after_insert_post', 'wp_save_post_revision_on_insert' ) ) {
return;
}
$post = get_post( $post_id );
if ( ! $post ) {
return;
}
if ( ! post_type_supports( $post->post_type, 'revisions' ) ) {
return;
}
if ( 'auto-draft' === $post->post_status ) {
return;
}
if ( ! wp_revisions_enabled( $post ) ) {
return;
}
/*
* Compare the proposed update with the last stored revision verifying that
* they are different, unless a plugin tells us to always save regardless.
* If no previous revisions, save one.
*/
$revisions = wp_get_post_revisions( $post_id );
if ( $revisions ) {
// Grab the latest revision, but not an autosave.
foreach ( $revisions as $revision ) {
if ( str_contains( $revision->post_name, "{$revision->post_parent}-revision" ) ) {
$latest_revision = $revision;
break;
}
}
/**
* Filters whether the post has changed since the latest revision.
*
* By default a revision is saved only if one of the revisioned fields has changed.
* This filter can override that so a revision is saved even if nothing has changed.
*
* @since 3.6.0
*
* @param bool $check_for_changes Whether to check for changes before saving a new revision.
* Default true.
* @param WP_Post $latest_revision The latest revision post object.
* @param WP_Post $post The post object.
*/
if ( isset( $latest_revision ) && apply_filters( 'wp_save_post_revision_check_for_changes', true, $latest_revision, $post ) ) {
$post_has_changed = false;
foreach ( array_keys( _wp_post_revision_fields( $post ) ) as $field ) {
if ( normalize_whitespace( $post->$field ) !== normalize_whitespace( $latest_revision->$field ) ) {
$post_has_changed = true;
break;
}
}
/**
* Filters whether a post has changed.
*
* By default a revision is saved only if one of the revisioned fields has changed.
* This filter allows for additional checks to determine if there were changes.
*
* @since 4.1.0
*
* @param bool $post_has_changed Whether the post has changed.
* @param WP_Post $latest_revision The latest revision post object.
* @param WP_Post $post The post object.
*/
$post_has_changed = (bool) apply_filters( 'wp_save_post_revision_post_has_changed', $post_has_changed, $latest_revision, $post );
// Don't save revision if post unchanged.
if ( ! $post_has_changed ) {
return;
}
}
}
$return = _wp_put_post_revision( $post );
/*
* If a limit for the number of revisions to keep has been set,
* delete the oldest ones.
*/
$revisions_to_keep = wp_revisions_to_keep( $post );
if ( $revisions_to_keep < 0 ) {
return $return;
}
$revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );
/**
* Filters the revisions to be considered for deletion.
*
* @since 6.2.0
*
* @param WP_Post[] $revisions Array of revisions, or an empty array if none.
* @param int $post_id The ID of the post to save as a revision.
*/
$revisions = apply_filters(
'wp_save_post_revision_revisions_before_deletion',
$revisions,
$post_id
);
$delete = count( $revisions ) - $revisions_to_keep;
if ( $delete < 1 ) {
return $return;
}
$revisions = array_slice( $revisions, 0, $delete );
for ( $i = 0; isset( $revisions[ $i ] ); $i++ ) {
if ( str_contains( $revisions[ $i ]->post_name, 'autosave' ) ) {
continue;
}
wp_delete_post_revision( $revisions[ $i ]->ID );
}
return $return;
}
/**
* Retrieves the autosaved data of the specified post.
*
* Returns a post object with the information that was autosaved for the specified post.
* If the optional $user_id is passed, returns the autosave for that user, otherwise
* returns the latest autosave.
*
* @since 2.6.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int $post_id The post ID.
* @param int $user_id Optional. The post author ID. Default 0.
* @return WP_Post|false The autosaved data or false on failure or when no autosave exists.
*/
function wp_get_post_autosave( $post_id, $user_id = 0 ) {
global $wpdb;
$autosave_name = $post_id . '-autosave-v1';
$user_id_query = ( 0 !== $user_id ) ? "AND post_author = $user_id" : null;
// Construct the autosave query.
$autosave_query = "
SELECT *
FROM $wpdb->posts
WHERE post_parent = %d
AND post_type = 'revision'
AND post_status = 'inherit'
AND post_name = %s " . $user_id_query . '
ORDER BY post_date DESC
LIMIT 1';
$autosave = $wpdb->get_results(
$wpdb->prepare(
$autosave_query,
$post_id,
$autosave_name
)
);
if ( ! $autosave ) {
return false;
}
return get_post( $autosave[0] );
}
/**
* Determines if the specified post is a revision.
*
* @since 2.6.0
*
* @param int|WP_Post $post Post ID or post object.
* @return int|false ID of revision's parent on success, false if not a revision.
*/
function wp_is_post_revision( $post ) {
$post = wp_get_post_revision( $post );
if ( ! $post ) {
return false;
}
return (int) $post->post_parent;
}
/**
* Determines if the specified post is an autosave.
*
* @since 2.6.0
*
* @param int|WP_Post $post Post ID or post object.
* @return int|false ID of autosave's parent on success, false if not a revision.
*/
function wp_is_post_autosave( $post ) {
$post = wp_get_post_revision( $post );
if ( ! $post ) {
return false;
}
if ( str_contains( $post->post_name, "{$post->post_parent}-autosave" ) ) {
return (int) $post->post_parent;
}
return false;
}
/**
* Inserts post data into the posts table as a post revision.
*
* @since 2.6.0
* @access private
*
* @param int|WP_Post|array|null $post Post ID, post object OR post array.
* @param bool $autosave Optional. Whether the revision is an autosave or not.
* Default false.
* @return int|WP_Error WP_Error or 0 if error, new revision ID if success.
*/
function _wp_put_post_revision( $post = null, $autosave = false ) {
if ( is_object( $post ) ) {
$post = get_object_vars( $post );
} elseif ( ! is_array( $post ) ) {
$post = get_post( $post, ARRAY_A );
}
if ( ! $post || empty( $post['ID'] ) ) {
return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
}
if ( isset( $post['post_type'] ) && 'revision' === $post['post_type'] ) {
return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
}
$post = _wp_post_revision_data( $post, $autosave );
$post = wp_slash( $post ); // Since data is from DB.
$revision_id = wp_insert_post( $post, true );
if ( is_wp_error( $revision_id ) ) {
return $revision_id;
}
if ( $revision_id ) {
/**
* Fires once a revision has been saved.
*
* @since 2.6.0
* @since 6.4.0 The post_id parameter was added.
*
* @param int $revision_id Post revision ID.
* @param int $post_id Post ID.
*/
do_action( '_wp_put_post_revision', $revision_id, $post['post_parent'] );
}
return $revision_id;
}
/**
* Save the revisioned meta fields.
*
* @since 6.4.0
*
* @param int $revision_id The ID of the revision to save the meta to.
* @param int $post_id The ID of the post the revision is associated with.
*/
function wp_save_revisioned_meta_fields( $revision_id, $post_id ) {
$post_type = get_post_type( $post_id );
if ( ! $post_type ) {
return;
}
foreach ( wp_post_revision_meta_keys( $post_type ) as $meta_key ) {
if ( metadata_exists( 'post', $post_id, $meta_key ) ) {
_wp_copy_post_meta( $post_id, $revision_id, $meta_key );
}
}
}
/**
* Gets a post revision.
*
* @since 2.6.0
*
* @param int|WP_Post $post Post ID or post object.
* @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
* correspond to a WP_Post object, an associative array, or a numeric array,
* respectively. Default OBJECT.
* @param string $filter Optional sanitization filter. See sanitize_post(). Default 'raw'.
* @return WP_Post|array|null WP_Post (or array) on success, or null on failure.
*/
function wp_get_post_revision( &$post, $output = OBJECT, $filter = 'raw' ) {
$revision = get_post( $post, OBJECT, $filter );
if ( ! $revision ) {
return $revision;
}
if ( 'revision' !== $revision->post_type ) {
return null;
}
if ( OBJECT === $output ) {
return $revision;
} elseif ( ARRAY_A === $output ) {
$_revision = get_object_vars( $revision );
return $_revision;
} elseif ( ARRAY_N === $output ) {
$_revision = array_values( get_object_vars( $revision ) );
return $_revision;
}
return $revision;
}
/**
* Restores a post to the specified revision.
*
* Can restore a past revision using all fields of the post revision, or only selected fields.
*
* @since 2.6.0
*
* @param int|WP_Post $revision Revision ID or revision object.
* @param array $fields Optional. What fields to restore from. Defaults to all.
* @return int|false|null Null if error, false if no fields to restore, (int) post ID if success.
*/
function wp_restore_post_revision( $revision, $fields = null ) {
$revision = wp_get_post_revision( $revision, ARRAY_A );
if ( ! $revision ) {
return $revision;
}
if ( ! is_array( $fields ) ) {
$fields = array_keys( _wp_post_revision_fields( $revision ) );
}
$update = array();
foreach ( array_intersect( array_keys( $revision ), $fields ) as $field ) {
$update[ $field ] = $revision[ $field ];
}
if ( ! $update ) {
return false;
}
$update['ID'] = $revision['post_parent'];
$update = wp_slash( $update ); // Since data is from DB.
$post_id = wp_update_post( $update );
if ( ! $post_id || is_wp_error( $post_id ) ) {
return $post_id;
}
// Update last edit user.
update_post_meta( $post_id, '_edit_last', get_current_user_id() );
/**
* Fires after a post revision has been restored.
*
* @since 2.6.0
*
* @param int $post_id Post ID.
* @param int $revision_id Post revision ID.
*/
do_action( 'wp_restore_post_revision', $post_id, $revision['ID'] );
return $post_id;
}
/**
* Restore the revisioned meta values for a post.
*
* @since 6.4.0
*
* @param int $post_id The ID of the post to restore the meta to.
* @param int $revision_id The ID of the revision to restore the meta from.
*/
function wp_restore_post_revision_meta( $post_id, $revision_id ) {
$post_type = get_post_type( $post_id );
if ( ! $post_type ) {
return;
}
// Restore revisioned meta fields.
foreach ( wp_post_revision_meta_keys( $post_type ) as $meta_key ) {
// Clear any existing meta.
delete_post_meta( $post_id, $meta_key );
_wp_copy_post_meta( $revision_id, $post_id, $meta_key );
}
}
/**
* Copy post meta for the given key from one post to another.
*
* @since 6.4.0
*
* @param int $source_post_id Post ID to copy meta value(s) from.
* @param int $target_post_id Post ID to copy meta value(s) to.
* @param string $meta_key Meta key to copy.
*/
function _wp_copy_post_meta( $source_post_id, $target_post_id, $meta_key ) {
foreach ( get_post_meta( $source_post_id, $meta_key ) as $meta_value ) {
/**
* We use add_metadata() function vs add_post_meta() here
* to allow for a revision post target OR regular post.
*/
add_metadata( 'post', $target_post_id, $meta_key, wp_slash( $meta_value ) );
}
}
/**
* Determine which post meta fields should be revisioned.
*
* @since 6.4.0
*
* @param string $post_type The post type being revisioned.
* @return array An array of meta keys to be revisioned.
*/
function wp_post_revision_meta_keys( $post_type ) {
$registered_meta = array_merge(
get_registered_meta_keys( 'post' ),
get_registered_meta_keys( 'post', $post_type )
);
$wp_revisioned_meta_keys = array();
foreach ( $registered_meta as $name => $args ) {
if ( $args['revisions_enabled'] ) {
$wp_revisioned_meta_keys[ $name ] = true;
}
}
$wp_revisioned_meta_keys = array_keys( $wp_revisioned_meta_keys );
/**
* Filter the list of post meta keys to be revisioned.
*
* @since 6.4.0
*
* @param array $keys An array of meta fields to be revisioned.
* @param string $post_type The post type being revisioned.
*/
return apply_filters( 'wp_post_revision_meta_keys', $wp_revisioned_meta_keys, $post_type );
}
/**
* Check whether revisioned post meta fields have changed.
*
* @since 6.4.0
*
* @param bool $post_has_changed Whether the post has changed.
* @param WP_Post $last_revision The last revision post object.
* @param WP_Post $post The post object.
* @return bool Whether the post has changed.
*/
function wp_check_revisioned_meta_fields_have_changed( $post_has_changed, WP_Post $last_revision, WP_Post $post ) {
foreach ( wp_post_revision_meta_keys( $post->post_type ) as $meta_key ) {
if ( get_post_meta( $post->ID, $meta_key ) !== get_post_meta( $last_revision->ID, $meta_key ) ) {
$post_has_changed = true;
break;
}
}
return $post_has_changed;
}
/**
* Deletes a revision.
*
* Deletes the row from the posts table corresponding to the specified revision.
*
* @since 2.6.0
*
* @param int|WP_Post $revision Revision ID or revision object.
* @return WP_Post|false|null Null or false if error, deleted post object if success.
*/
function wp_delete_post_revision( $revision ) {
$revision = wp_get_post_revision( $revision );
if ( ! $revision ) {
return $revision;
}
$delete = wp_delete_post( $revision->ID );
if ( $delete ) {
/**
* Fires once a post revision has been deleted.
*
* @since 2.6.0
*
* @param int $revision_id Post revision ID.
* @param WP_Post $revision Post revision object.
*/
do_action( 'wp_delete_post_revision', $revision->ID, $revision );
}
return $delete;
}
/**
* Returns all revisions of specified post.
*
* @since 2.6.0
*
* @see get_children()
*
* @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
* @param array|null $args Optional. Arguments for retrieving post revisions. Default null.
* @return WP_Post[]|int[] Array of revision objects or IDs, or an empty array if none.
*/
function wp_get_post_revisions( $post = 0, $args = null ) {
$post = get_post( $post );
if ( ! $post || empty( $post->ID ) ) {
return array();
}
$defaults = array(
'order' => 'DESC',
'orderby' => 'date ID',
'check_enabled' => true,
);
$args = wp_parse_args( $args, $defaults );
if ( $args['check_enabled'] && ! wp_revisions_enabled( $post ) ) {
return array();
}
$args = array_merge(
$args,
array(
'post_parent' => $post->ID,
'post_type' => 'revision',
'post_status' => 'inherit',
)
);
$revisions = get_children( $args );
if ( ! $revisions ) {
return array();
}
return $revisions;
}
/**
* Returns the latest revision ID and count of revisions for a post.
*
* @since 6.1.0
*
* @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
* @return array|WP_Error {
* Returns associative array with latest revision ID and total count,
* or a WP_Error if the post does not exist or revisions are not enabled.
*
* @type int $latest_id The latest revision post ID or 0 if no revisions exist.
* @type int $count The total count of revisions for the given post.
* }
*/
function wp_get_latest_revision_id_and_total_count( $post = 0 ) {
$post = get_post( $post );
if ( ! $post ) {
return new WP_Error( 'invalid_post', __( 'Invalid post.' ) );
}
if ( ! wp_revisions_enabled( $post ) ) {
return new WP_Error( 'revisions_not_enabled', __( 'Revisions not enabled.' ) );
}
$args = array(
'post_parent' => $post->ID,
'fields' => 'ids',
'post_type' => 'revision',
'post_status' => 'inherit',
'order' => 'DESC',
'orderby' => 'date ID',
'posts_per_page' => 1,
'ignore_sticky_posts' => true,
);
$revision_query = new WP_Query();
$revisions = $revision_query->query( $args );
if ( ! $revisions ) {
return array(
'latest_id' => 0,
'count' => 0,
);
}
return array(
'latest_id' => $revisions[0],
'count' => $revision_query->found_posts,
);
}
/**
* Returns the url for viewing and potentially restoring revisions of a given post.
*
* @since 5.9.0
*
* @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
* @return string|null The URL for editing revisions on the given post, otherwise null.
*/
function wp_get_post_revisions_url( $post = 0 ) {
$post = get_post( $post );
if ( ! $post instanceof WP_Post ) {
return null;
}
// If the post is a revision, return early.
if ( 'revision' === $post->post_type ) {
return get_edit_post_link( $post );
}
if ( ! wp_revisions_enabled( $post ) ) {
return null;
}
$revisions = wp_get_latest_revision_id_and_total_count( $post->ID );
if ( is_wp_error( $revisions ) || 0 === $revisions['count'] ) {
return null;
}
return get_edit_post_link( $revisions['latest_id'] );
}
/**
* Determines whether revisions are enabled for a given post.
*
* @since 3.6.0
*
* @param WP_Post $post The post object.
* @return bool True if number of revisions to keep isn't zero, false otherwise.
*/
function wp_revisions_enabled( $post ) {
return wp_revisions_to_keep( $post ) !== 0;
}
/**
* Determines how many revisions to retain for a given post.
*
* By default, an infinite number of revisions are kept.
*
* The constant WP_POST_REVISIONS can be set in wp-config to specify the limit
* of revisions to keep.
*
* @since 3.6.0
*
* @param WP_Post $post The post object.
* @return int The number of revisions to keep.
*/
function wp_revisions_to_keep( $post ) {
$num = WP_POST_REVISIONS;
if ( true === $num ) {
$num = -1;
} else {
$num = (int) $num;
}
if ( ! post_type_supports( $post->post_type, 'revisions' ) ) {
$num = 0;
}
/**
* Filters the number of revisions to save for the given post.
*
* Overrides the value of WP_POST_REVISIONS.
*
* @since 3.6.0
*
* @param int $num Number of revisions to store.
* @param WP_Post $post Post object.
*/
$num = apply_filters( 'wp_revisions_to_keep', $num, $post );
/**
* Filters the number of revisions to save for the given post by its post type.
*
* Overrides both the value of WP_POST_REVISIONS and the {@see 'wp_revisions_to_keep'} filter.
*
* The dynamic portion of the hook name, `$post->post_type`, refers to
* the post type slug.
*
* Possible hook names include:
*
* - `wp_post_revisions_to_keep`
* - `wp_page_revisions_to_keep`
*
* @since 5.8.0
*
* @param int $num Number of revisions to store.
* @param WP_Post $post Post object.
*/
$num = apply_filters( "wp_{$post->post_type}_revisions_to_keep", $num, $post );
return (int) $num;
}
/**
* Sets up the post object for preview based on the post autosave.
*
* @since 2.7.0
* @access private
*
* @param WP_Post $post
* @return WP_Post|false
*/
function _set_preview( $post ) {
if ( ! is_object( $post ) ) {
return $post;
}
$preview = wp_get_post_autosave( $post->ID );
if ( is_object( $preview ) ) {
$preview = sanitize_post( $preview );
$post->post_content = $preview->post_content;
$post->post_title = $preview->post_title;
$post->post_excerpt = $preview->post_excerpt;
}
add_filter( 'get_the_terms', '_wp_preview_terms_filter', 10, 3 );
add_filter( 'get_post_metadata', '_wp_preview_post_thumbnail_filter', 10, 3 );
add_filter( 'get_post_metadata', '_wp_preview_meta_filter', 10, 4 );
return $post;
}
/**
* Filters the latest content for preview from the post autosave.
*
* @since 2.7.0
* @access private
*/
function _show_post_preview() {
if ( isset( $_GET['preview_id'] ) && isset( $_GET['preview_nonce'] ) ) {
$id = (int) $_GET['preview_id'];
if ( false === wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . $id ) ) {
wp_die( __( 'Sorry, you are not allowed to preview drafts.' ), 403 );
}
add_filter( 'the_preview', '_set_preview' );
}
}
/**
* Filters terms lookup to set the post format.
*
* @since 3.6.0
* @access private
*
* @param array $terms
* @param int $post_id
* @param string $taxonomy
* @return array
*/
function _wp_preview_terms_filter( $terms, $post_id, $taxonomy ) {
$post = get_post();
if ( ! $post ) {
return $terms;
}
if ( empty( $_REQUEST['post_format'] ) || $post->ID !== $post_id
|| 'post_format' !== $taxonomy || 'revision' === $post->post_type
) {
return $terms;
}
if ( 'standard' === $_REQUEST['post_format'] ) {
$terms = array();
} else {
$term = get_term_by( 'slug', 'post-format-' . sanitize_key( $_REQUEST['post_format'] ), 'post_format' );
if ( $term ) {
$terms = array( $term ); // Can only have one post format.
}
}
return $terms;
}
/**
* Filters post thumbnail lookup to set the post thumbnail.
*
* @since 4.6.0
* @access private
*
* @param null|array|string $value The value to return - a single metadata value, or an array of values.
* @param int $post_id Post ID.
* @param string $meta_key Meta key.
* @return null|array The default return value or the post thumbnail meta array.
*/
function _wp_preview_post_thumbnail_filter( $value, $post_id, $meta_key ) {
$post = get_post();
if ( ! $post ) {
return $value;
}
if ( empty( $_REQUEST['_thumbnail_id'] ) || empty( $_REQUEST['preview_id'] )
|| $post->ID !== $post_id || $post_id !== (int) $_REQUEST['preview_id']
|| '_thumbnail_id' !== $meta_key || 'revision' === $post->post_type
) {
return $value;
}
$thumbnail_id = (int) $_REQUEST['_thumbnail_id'];
if ( $thumbnail_id <= 0 ) {
return '';
}
return (string) $thumbnail_id;
}
/**
* Gets the post revision version.
*
* @since 3.6.0
* @access private
*
* @param WP_Post $revision
* @return int|false
*/
function _wp_get_post_revision_version( $revision ) {
if ( is_object( $revision ) ) {
$revision = get_object_vars( $revision );
} elseif ( ! is_array( $revision ) ) {
return false;
}
if ( preg_match( '/^\d+-(?:autosave|revision)-v(\d+)$/', $revision['post_name'], $matches ) ) {
return (int) $matches[1];
}
return 0;
}
/**
* Upgrades the revisions author, adds the current post as a revision and sets the revisions version to 1.
*
* @since 3.6.0
* @access private
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param WP_Post $post Post object.
* @param array $revisions Current revisions of the post.
* @return bool true if the revisions were upgraded, false if problems.
*/
function _wp_upgrade_revisions_of_post( $post, $revisions ) {
global $wpdb;
// Add post option exclusively.
$lock = "revision-upgrade-{$post->ID}";
$now = time();
$result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, 'no') /* LOCK */", $lock, $now ) );
if ( ! $result ) {
// If we couldn't get a lock, see how old the previous lock is.
$locked = get_option( $lock );
if ( ! $locked ) {
/*
* Can't write to the lock, and can't read the lock.
* Something broken has happened.
*/
return false;
}
if ( $locked > $now - HOUR_IN_SECONDS ) {
// Lock is not too old: some other process may be upgrading this post. Bail.
return false;
}
// Lock is too old - update it (below) and continue.
}
// If we could get a lock, re-"add" the option to fire all the correct filters.
update_option( $lock, $now );
reset( $revisions );
$add_last = true;
do {
$this_revision = current( $revisions );
$prev_revision = next( $revisions );
$this_revision_version = _wp_get_post_revision_version( $this_revision );
// Something terrible happened.
if ( false === $this_revision_version ) {
continue;
}
/*
* 1 is the latest revision version, so we're already up to date.
* No need to add a copy of the post as latest revision.
*/
if ( 0 < $this_revision_version ) {
$add_last = false;
continue;
}
// Always update the revision version.
$update = array(
'post_name' => preg_replace( '/^(\d+-(?:autosave|revision))[\d-]*$/', '$1-v1', $this_revision->post_name ),
);
/*
* If this revision is the oldest revision of the post, i.e. no $prev_revision,
* the correct post_author is probably $post->post_author, but that's only a good guess.
* Update the revision version only and Leave the author as-is.
*/
if ( $prev_revision ) {
$prev_revision_version = _wp_get_post_revision_version( $prev_revision );
// If the previous revision is already up to date, it no longer has the information we need :(
if ( $prev_revision_version < 1 ) {
$update['post_author'] = $prev_revision->post_author;
}
}
// Upgrade this revision.
$result = $wpdb->update( $wpdb->posts, $update, array( 'ID' => $this_revision->ID ) );
if ( $result ) {
wp_cache_delete( $this_revision->ID, 'posts' );
}
} while ( $prev_revision );
delete_option( $lock );
// Add a copy of the post as latest revision.
if ( $add_last ) {
wp_save_post_revision( $post->ID );
}
return true;
}
/**
* Filters preview post meta retrieval to get values from the autosave.
*
* Filters revisioned meta keys only.
*
* @since 6.4.0
*
* @param mixed $value Meta value to filter.
* @param int $object_id Object ID.
* @param string $meta_key Meta key to filter a value for.
* @param bool $single Whether to return a single value. Default false.
* @return mixed Original meta value if the meta key isn't revisioned, the object doesn't exist,
* the post type is a revision or the post ID doesn't match the object ID.
* Otherwise, the revisioned meta value is returned for the preview.
*/
function _wp_preview_meta_filter( $value, $object_id, $meta_key, $single ) {
$post = get_post();
if (
empty( $post ) ||
$post->ID !== $object_id ||
! in_array( $meta_key, wp_post_revision_meta_keys( $post->post_type ), true ) ||
'revision' === $post->post_type
) {
return $value;
}
$preview = wp_get_post_autosave( $post->ID );
if ( false === $preview ) {
return $value;
}
return get_post_meta( $preview->ID, $meta_key, $single );
}
/**
* WordPress scripts and styles default loader.
*
* Several constants are used to manage the loading, concatenating and compression of scripts and CSS:
* define('SCRIPT_DEBUG', true); loads the development (non-minified) versions of all scripts and CSS, and disables compression and concatenation,
* define('CONCATENATE_SCRIPTS', false); disables compression and concatenation of scripts and CSS,
* define('COMPRESS_SCRIPTS', false); disables compression of scripts,
* define('COMPRESS_CSS', false); disables compression of CSS,
* define('ENFORCE_GZIP', true); forces gzip for compression (default is deflate).
*
* The globals $concatenate_scripts, $compress_scripts and $compress_css can be set by plugins
* to temporarily override the above settings. Also a compression test is run once and the result is saved
* as option 'can_compress_scripts' (0/1). The test will run again if that option is deleted.
*
* @package WordPress
*/
/** WordPress Dependency Class */
require ABSPATH . WPINC . '/class-wp-dependency.php';
/** WordPress Dependencies Class */
require ABSPATH . WPINC . '/class-wp-dependencies.php';
/** WordPress Scripts Class */
require ABSPATH . WPINC . '/class-wp-scripts.php';
/** WordPress Scripts Functions */
require ABSPATH . WPINC . '/functions.wp-scripts.php';
/** WordPress Styles Class */
require ABSPATH . WPINC . '/class-wp-styles.php';
/** WordPress Styles Functions */
require ABSPATH . WPINC . '/functions.wp-styles.php';
/**
* Registers TinyMCE scripts.
*
* @since 5.0.0
*
* @global string $tinymce_version
* @global bool $concatenate_scripts
* @global bool $compress_scripts
*
* @param WP_Scripts $scripts WP_Scripts object.
* @param bool $force_uncompressed Whether to forcibly prevent gzip compression. Default false.
*/
function wp_register_tinymce_scripts( $scripts, $force_uncompressed = false ) {
global $tinymce_version, $concatenate_scripts, $compress_scripts;
$suffix = wp_scripts_get_suffix();
$dev_suffix = wp_scripts_get_suffix( 'dev' );
script_concat_settings();
$compressed = $compress_scripts && $concatenate_scripts && isset( $_SERVER['HTTP_ACCEPT_ENCODING'] )
&& false !== stripos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip' ) && ! $force_uncompressed;
/*
* Load tinymce.js when running from /src, otherwise load wp-tinymce.js.gz (in production)
* or tinymce.min.js (when SCRIPT_DEBUG is true).
*/
if ( $compressed ) {
$scripts->add( 'wp-tinymce', includes_url( 'js/tinymce/' ) . 'wp-tinymce.js', array(), $tinymce_version );
} else {
$scripts->add( 'wp-tinymce-root', includes_url( 'js/tinymce/' ) . "tinymce$dev_suffix.js", array(), $tinymce_version );
$scripts->add( 'wp-tinymce', includes_url( 'js/tinymce/' ) . "plugins/compat3x/plugin$dev_suffix.js", array( 'wp-tinymce-root' ), $tinymce_version );
}
$scripts->add( 'wp-tinymce-lists', includes_url( "js/tinymce/plugins/lists/plugin$suffix.js" ), array( 'wp-tinymce' ), $tinymce_version );
}
/**
* Registers all the WordPress vendor scripts that are in the standardized
* `js/dist/vendor/` location.
*
* For the order of `$scripts->add` see `wp_default_scripts`.
*
* @since 5.0.0
*
* @global WP_Locale $wp_locale WordPress date and time locale object.
*
* @param WP_Scripts $scripts WP_Scripts object.
*/
function wp_default_packages_vendor( $scripts ) {
global $wp_locale;
$suffix = wp_scripts_get_suffix();
$vendor_scripts = array(
'react' => array( 'wp-polyfill' ),
'react-dom' => array( 'react' ),
'regenerator-runtime',
'moment',
'lodash',
'wp-polyfill-fetch',
'wp-polyfill-formdata',
'wp-polyfill-node-contains',
'wp-polyfill-url',
'wp-polyfill-dom-rect',
'wp-polyfill-element-closest',
'wp-polyfill-object-fit',
'wp-polyfill-inert',
'wp-polyfill' => array( 'wp-polyfill-inert', 'regenerator-runtime' ),
);
$vendor_scripts_versions = array(
'react' => '18.2.0',
'react-dom' => '18.2.0',
'regenerator-runtime' => '0.14.0',
'moment' => '2.29.4',
'lodash' => '4.17.19',
'wp-polyfill-fetch' => '3.6.17',
'wp-polyfill-formdata' => '4.0.10',
'wp-polyfill-node-contains' => '4.8.0',
'wp-polyfill-url' => '3.6.4',
'wp-polyfill-dom-rect' => '4.8.0',
'wp-polyfill-element-closest' => '3.0.2',
'wp-polyfill-object-fit' => '2.3.5',
'wp-polyfill-inert' => '3.1.2',
'wp-polyfill' => '3.15.0',
);
foreach ( $vendor_scripts as $handle => $dependencies ) {
if ( is_string( $dependencies ) ) {
$handle = $dependencies;
$dependencies = array();
}
$path = "/wp-includes/js/dist/vendor/$handle$suffix.js";
$version = $vendor_scripts_versions[ $handle ];
$scripts->add( $handle, $path, $dependencies, $version, 1 );
}
did_action( 'init' ) && $scripts->add_inline_script( 'lodash', 'window.lodash = _.noConflict();' );
did_action( 'init' ) && $scripts->add_inline_script(
'moment',
sprintf(
"moment.updateLocale( '%s', %s );",
get_user_locale(),
wp_json_encode(
array(
'months' => array_values( $wp_locale->month ),
'monthsShort' => array_values( $wp_locale->month_abbrev ),
'weekdays' => array_values( $wp_locale->weekday ),
'weekdaysShort' => array_values( $wp_locale->weekday_abbrev ),
'week' => array(
'dow' => (int) get_option( 'start_of_week', 0 ),
),
'longDateFormat' => array(
'LT' => get_option( 'time_format', __( 'g:i a' ) ),
'LTS' => null,
'L' => null,
'LL' => get_option( 'date_format', __( 'F j, Y' ) ),
'LLL' => __( 'F j, Y g:i a' ),
'LLLL' => null,
),
)
)
),
'after'
);
}
/**
* Returns contents of an inline script used in appending polyfill scripts for
* browsers which fail the provided tests. The provided array is a mapping from
* a condition to verify feature support to its polyfill script handle.
*
* @since 5.0.0
*
* @param WP_Scripts $scripts WP_Scripts object.
* @param string[] $tests Features to detect.
* @return string Conditional polyfill inline script.
*/
function wp_get_script_polyfill( $scripts, $tests ) {
$polyfill = '';
foreach ( $tests as $test => $handle ) {
if ( ! array_key_exists( $handle, $scripts->registered ) ) {
continue;
}
$src = $scripts->registered[ $handle ]->src;
$ver = $scripts->registered[ $handle ]->ver;
if ( ! preg_match( '|^(https?:)?//|', $src ) && ! ( $scripts->content_url && str_starts_with( $src, $scripts->content_url ) ) ) {
$src = $scripts->base_url . $src;
}
if ( ! empty( $ver ) ) {
$src = add_query_arg( 'ver', $ver, $src );
}
/** This filter is documented in wp-includes/class-wp-scripts.php */
$src = esc_url( apply_filters( 'script_loader_src', $src, $handle ) );
if ( ! $src ) {
continue;
}
$polyfill .= (
// Test presence of feature...
'( ' . $test . ' ) || ' .
/*
* ...appending polyfill on any failures. Cautious viewers may balk
* at the `document.write`. Its caveat of synchronous mid-stream
* blocking write is exactly the behavior we need though.
*/
'document.write( \'\n";
}
$concat = str_split( $concat, 128 );
$concatenated = '';
foreach ( $concat as $key => $chunk ) {
$concatenated .= "&load%5Bchunk_{$key}%5D={$chunk}";
}
$src = $wp_scripts->base_url . "/wp-admin/load-scripts.php?c={$zip}" . $concatenated . '&ver=' . $wp_scripts->default_version;
echo "\n";
}
if ( ! empty( $wp_scripts->print_html ) ) {
echo $wp_scripts->print_html;
}
}
/**
* Prints the script queue in the HTML head on the front end.
*
* Postpones the scripts that were queued for the footer.
* wp_print_footer_scripts() is called in the footer to print these scripts.
*
* @since 2.8.0
*
* @global WP_Scripts $wp_scripts
*
* @return array
*/
function wp_print_head_scripts() {
global $wp_scripts;
if ( ! did_action( 'wp_print_scripts' ) ) {
/** This action is documented in wp-includes/functions.wp-scripts.php */
do_action( 'wp_print_scripts' );
}
if ( ! ( $wp_scripts instanceof WP_Scripts ) ) {
return array(); // No need to run if nothing is queued.
}
return print_head_scripts();
}
/**
* Private, for use in *_footer_scripts hooks
*
* @since 3.3.0
*/
function _wp_footer_scripts() {
print_late_styles();
print_footer_scripts();
}
/**
* Hooks to print the scripts and styles in the footer.
*
* @since 2.8.0
*/
function wp_print_footer_scripts() {
/**
* Fires when footer scripts are printed.
*
* @since 2.8.0
*/
do_action( 'wp_print_footer_scripts' );
}
/**
* Wrapper for do_action( 'wp_enqueue_scripts' ).
*
* Allows plugins to queue scripts for the front end using wp_enqueue_script().
* Runs first in wp_head() where all is_home(), is_page(), etc. functions are available.
*
* @since 2.8.0
*/
function wp_enqueue_scripts() {
/**
* Fires when scripts and styles are enqueued.
*
* @since 2.8.0
*/
do_action( 'wp_enqueue_scripts' );
}
/**
* Prints the styles queue in the HTML head on admin pages.
*
* @since 2.8.0
*
* @global bool $concatenate_scripts
*
* @return array
*/
function print_admin_styles() {
global $concatenate_scripts;
$wp_styles = wp_styles();
script_concat_settings();
$wp_styles->do_concat = $concatenate_scripts;
$wp_styles->do_items( false );
/**
* Filters whether to print the admin styles.
*
* @since 2.8.0
*
* @param bool $print Whether to print the admin styles. Default true.
*/
if ( apply_filters( 'print_admin_styles', true ) ) {
_print_styles();
}
$wp_styles->reset();
return $wp_styles->done;
}
/**
* Prints the styles that were queued too late for the HTML head.
*
* @since 3.3.0
*
* @global WP_Styles $wp_styles
* @global bool $concatenate_scripts
*
* @return array|void
*/
function print_late_styles() {
global $wp_styles, $concatenate_scripts;
if ( ! ( $wp_styles instanceof WP_Styles ) ) {
return;
}
script_concat_settings();
$wp_styles->do_concat = $concatenate_scripts;
$wp_styles->do_footer_items();
/**
* Filters whether to print the styles queued too late for the HTML head.
*
* @since 3.3.0
*
* @param bool $print Whether to print the 'late' styles. Default true.
*/
if ( apply_filters( 'print_late_styles', true ) ) {
_print_styles();
}
$wp_styles->reset();
return $wp_styles->done;
}
/**
* Prints styles (internal use only).
*
* @ignore
* @since 3.3.0
*
* @global bool $compress_css
*/
function _print_styles() {
global $compress_css;
$wp_styles = wp_styles();
$zip = $compress_css ? 1 : 0;
if ( $zip && defined( 'ENFORCE_GZIP' ) && ENFORCE_GZIP ) {
$zip = 'gzip';
}
$concat = trim( $wp_styles->concat, ', ' );
$type_attr = current_theme_supports( 'html5', 'style' ) ? '' : ' type="text/css"';
if ( $concat ) {
$dir = $wp_styles->text_direction;
$ver = $wp_styles->default_version;
$concat = str_split( $concat, 128 );
$concatenated = '';
foreach ( $concat as $key => $chunk ) {
$concatenated .= "&load%5Bchunk_{$key}%5D={$chunk}";
}
$href = $wp_styles->base_url . "/wp-admin/load-styles.php?c={$zip}&dir={$dir}" . $concatenated . '&ver=' . $ver;
echo "\n";
if ( ! empty( $wp_styles->print_code ) ) {
echo "\n";
}
}
if ( ! empty( $wp_styles->print_html ) ) {
echo $wp_styles->print_html;
}
}
/**
* Determines the concatenation and compression settings for scripts and styles.
*
* @since 2.8.0
*
* @global bool $concatenate_scripts
* @global bool $compress_scripts
* @global bool $compress_css
*/
function script_concat_settings() {
global $concatenate_scripts, $compress_scripts, $compress_css;
$compressed_output = ( ini_get( 'zlib.output_compression' ) || 'ob_gzhandler' === ini_get( 'output_handler' ) );
$can_compress_scripts = ! wp_installing() && get_site_option( 'can_compress_scripts' );
if ( ! isset( $concatenate_scripts ) ) {
$concatenate_scripts = defined( 'CONCATENATE_SCRIPTS' ) ? CONCATENATE_SCRIPTS : true;
if ( ( ! is_admin() && ! did_action( 'login_init' ) ) || ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ) {
$concatenate_scripts = false;
}
}
if ( ! isset( $compress_scripts ) ) {
$compress_scripts = defined( 'COMPRESS_SCRIPTS' ) ? COMPRESS_SCRIPTS : true;
if ( $compress_scripts && ( ! $can_compress_scripts || $compressed_output ) ) {
$compress_scripts = false;
}
}
if ( ! isset( $compress_css ) ) {
$compress_css = defined( 'COMPRESS_CSS' ) ? COMPRESS_CSS : true;
if ( $compress_css && ( ! $can_compress_scripts || $compressed_output ) ) {
$compress_css = false;
}
}
}
/**
* Handles the enqueueing of block scripts and styles that are common to both
* the editor and the front-end.
*
* @since 5.0.0
*/
function wp_common_block_scripts_and_styles() {
if ( is_admin() && ! wp_should_load_block_editor_scripts_and_styles() ) {
return;
}
wp_enqueue_style( 'wp-block-library' );
if ( current_theme_supports( 'wp-block-styles' ) && ! wp_should_load_separate_core_block_assets() ) {
wp_enqueue_style( 'wp-block-library-theme' );
}
/**
* Fires after enqueuing block assets for both editor and front-end.
*
* Call `add_action` on any hook before 'wp_enqueue_scripts'.
*
* In the function call you supply, simply use `wp_enqueue_script` and
* `wp_enqueue_style` to add your functionality to the Gutenberg editor.
*
* @since 5.0.0
*/
do_action( 'enqueue_block_assets' );
}
/**
* Applies a filter to the list of style nodes that comes from WP_Theme_JSON::get_style_nodes().
*
* This particular filter removes all of the blocks from the array.
*
* We want WP_Theme_JSON to be ignorant of the implementation details of how the CSS is being used.
* This filter allows us to modify the output of WP_Theme_JSON depending on whether or not we are
* loading separate assets, without making the class aware of that detail.
*
* @since 6.1.0
*
* @param array $nodes The nodes to filter.
* @return array A filtered array of style nodes.
*/
function wp_filter_out_block_nodes( $nodes ) {
return array_filter(
$nodes,
static function ( $node ) {
return ! in_array( 'blocks', $node['path'], true );
},
ARRAY_FILTER_USE_BOTH
);
}
/**
* Enqueues the global styles defined via theme.json.
*
* @since 5.8.0
*/
function wp_enqueue_global_styles() {
$separate_assets = wp_should_load_separate_core_block_assets();
$is_block_theme = wp_is_block_theme();
$is_classic_theme = ! $is_block_theme;
/*
* Global styles should be printed in the head when loading all styles combined.
* The footer should only be used to print global styles for classic themes with separate core assets enabled.
*
* See https://core.trac.wordpress.org/ticket/53494.
*/
if (
( $is_block_theme && doing_action( 'wp_footer' ) ) ||
( $is_classic_theme && doing_action( 'wp_footer' ) && ! $separate_assets ) ||
( $is_classic_theme && doing_action( 'wp_enqueue_scripts' ) && $separate_assets )
) {
return;
}
/*
* If loading the CSS for each block separately, then load the theme.json CSS conditionally.
* This removes the CSS from the global-styles stylesheet and adds it to the inline CSS for each block.
* This filter must be registered before calling wp_get_global_stylesheet();
*/
add_filter( 'wp_theme_json_get_style_nodes', 'wp_filter_out_block_nodes' );
$stylesheet = wp_get_global_stylesheet();
if ( empty( $stylesheet ) ) {
return;
}
wp_register_style( 'global-styles', false );
wp_add_inline_style( 'global-styles', $stylesheet );
wp_enqueue_style( 'global-styles' );
// Add each block as an inline css.
wp_add_global_styles_for_blocks();
}
/**
* Enqueues the global styles custom css defined via theme.json.
*
* @since 6.2.0
*/
function wp_enqueue_global_styles_custom_css() {
if ( ! wp_is_block_theme() ) {
return;
}
// Don't enqueue Customizer's custom CSS separately.
remove_action( 'wp_head', 'wp_custom_css_cb', 101 );
$custom_css = wp_get_custom_css();
$custom_css .= wp_get_global_styles_custom_css();
if ( ! empty( $custom_css ) ) {
wp_add_inline_style( 'global-styles', $custom_css );
}
}
/**
* Checks if the editor scripts and styles for all registered block types
* should be enqueued on the current screen.
*
* @since 5.6.0
*
* @global WP_Screen $current_screen WordPress current screen object.
*
* @return bool Whether scripts and styles should be enqueued.
*/
function wp_should_load_block_editor_scripts_and_styles() {
global $current_screen;
$is_block_editor_screen = ( $current_screen instanceof WP_Screen ) && $current_screen->is_block_editor();
/**
* Filters the flag that decides whether or not block editor scripts and styles
* are going to be enqueued on the current screen.
*
* @since 5.6.0
*
* @param bool $is_block_editor_screen Current value of the flag.
*/
return apply_filters( 'should_load_block_editor_scripts_and_styles', $is_block_editor_screen );
}
/**
* Checks whether separate styles should be loaded for core blocks on-render.
*
* When this function returns true, other functions ensure that core blocks
* only load their assets on-render, and each block loads its own, individual
* assets. Third-party blocks only load their assets when rendered.
*
* When this function returns false, all core block assets are loaded regardless
* of whether they are rendered in a page or not, because they are all part of
* the `block-library/style.css` file. Assets for third-party blocks are always
* enqueued regardless of whether they are rendered or not.
*
* This only affects front end and not the block editor screens.
*
* @see wp_enqueue_registered_block_scripts_and_styles()
* @see register_block_style_handle()
*
* @since 5.8.0
*
* @return bool Whether separate assets will be loaded.
*/
function wp_should_load_separate_core_block_assets() {
if ( is_admin() || is_feed() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
return false;
}
/**
* Filters whether block styles should be loaded separately.
*
* Returning false loads all core block assets, regardless of whether they are rendered
* in a page or not. Returning true loads core block assets only when they are rendered.
*
* @since 5.8.0
*
* @param bool $load_separate_assets Whether separate assets will be loaded.
* Default false (all block assets are loaded, even when not used).
*/
return apply_filters( 'should_load_separate_core_block_assets', false );
}
/**
* Enqueues registered block scripts and styles, depending on current rendered
* context (only enqueuing editor scripts while in context of the editor).
*
* @since 5.0.0
*
* @global WP_Screen $current_screen WordPress current screen object.
*/
function wp_enqueue_registered_block_scripts_and_styles() {
global $current_screen;
if ( wp_should_load_separate_core_block_assets() ) {
return;
}
$load_editor_scripts_and_styles = is_admin() && wp_should_load_block_editor_scripts_and_styles();
$block_registry = WP_Block_Type_Registry::get_instance();
foreach ( $block_registry->get_all_registered() as $block_name => $block_type ) {
// Front-end and editor styles.
foreach ( $block_type->style_handles as $style_handle ) {
wp_enqueue_style( $style_handle );
}
// Front-end and editor scripts.
foreach ( $block_type->script_handles as $script_handle ) {
wp_enqueue_script( $script_handle );
}
if ( $load_editor_scripts_and_styles ) {
// Editor styles.
foreach ( $block_type->editor_style_handles as $editor_style_handle ) {
wp_enqueue_style( $editor_style_handle );
}
// Editor scripts.
foreach ( $block_type->editor_script_handles as $editor_script_handle ) {
wp_enqueue_script( $editor_script_handle );
}
}
}
}
/**
* Function responsible for enqueuing the styles required for block styles functionality on the editor and on the frontend.
*
* @since 5.3.0
*
* @global WP_Styles $wp_styles
*/
function enqueue_block_styles_assets() {
global $wp_styles;
$block_styles = WP_Block_Styles_Registry::get_instance()->get_all_registered();
foreach ( $block_styles as $block_name => $styles ) {
foreach ( $styles as $style_properties ) {
if ( isset( $style_properties['style_handle'] ) ) {
// If the site loads separate styles per-block, enqueue the stylesheet on render.
if ( wp_should_load_separate_core_block_assets() ) {
add_filter(
'render_block',
static function ( $html, $block ) use ( $block_name, $style_properties ) {
if ( $block['blockName'] === $block_name ) {
wp_enqueue_style( $style_properties['style_handle'] );
}
return $html;
},
10,
2
);
} else {
wp_enqueue_style( $style_properties['style_handle'] );
}
}
if ( isset( $style_properties['inline_style'] ) ) {
// Default to "wp-block-library".
$handle = 'wp-block-library';
// If the site loads separate styles per-block, check if the block has a stylesheet registered.
if ( wp_should_load_separate_core_block_assets() ) {
$block_stylesheet_handle = generate_block_asset_handle( $block_name, 'style' );
if ( isset( $wp_styles->registered[ $block_stylesheet_handle ] ) ) {
$handle = $block_stylesheet_handle;
}
}
// Add inline styles to the calculated handle.
wp_add_inline_style( $handle, $style_properties['inline_style'] );
}
}
}
}
/**
* Function responsible for enqueuing the assets required for block styles functionality on the editor.
*
* @since 5.3.0
*/
function enqueue_editor_block_styles_assets() {
$block_styles = WP_Block_Styles_Registry::get_instance()->get_all_registered();
$register_script_lines = array( '( function() {' );
foreach ( $block_styles as $block_name => $styles ) {
foreach ( $styles as $style_properties ) {
$block_style = array(
'name' => $style_properties['name'],
'label' => $style_properties['label'],
);
if ( isset( $style_properties['is_default'] ) ) {
$block_style['isDefault'] = $style_properties['is_default'];
}
$register_script_lines[] = sprintf(
' wp.blocks.registerBlockStyle( \'%s\', %s );',
$block_name,
wp_json_encode( $block_style )
);
}
}
$register_script_lines[] = '} )();';
$inline_script = implode( "\n", $register_script_lines );
wp_register_script( 'wp-block-styles', false, array( 'wp-blocks' ), true, array( 'in_footer' => true ) );
wp_add_inline_script( 'wp-block-styles', $inline_script );
wp_enqueue_script( 'wp-block-styles' );
}
/**
* Enqueues the assets required for the block directory within the block editor.
*
* @since 5.5.0
*/
function wp_enqueue_editor_block_directory_assets() {
wp_enqueue_script( 'wp-block-directory' );
wp_enqueue_style( 'wp-block-directory' );
}
/**
* Enqueues the assets required for the format library within the block editor.
*
* @since 5.8.0
*/
function wp_enqueue_editor_format_library_assets() {
wp_enqueue_script( 'wp-format-library' );
wp_enqueue_style( 'wp-format-library' );
}
/**
* Sanitizes an attributes array into an attributes string to be placed inside a `\n", wp_sanitize_script_attributes( $attributes ) );
}
/**
* Prints formatted `
*
* In an HTML document this would print "…" to the console,
* but in an XHTML document it would print "…" to the console.
*
*
*
* In an HTML document this would print "An image is in HTML",
* but it's an invalid XHTML document because it interprets the ``
* as an empty tag missing its closing `/`.
*
* @see https://www.w3.org/TR/xhtml1/#h-4.8
*/
if ( ! $is_html5 ) {
/*
* If the string `]]>` exists within the JavaScript it would break
* out of any wrapping CDATA section added here, so to start, it's
* necessary to escape that sequence which requires splitting the
* content into two CDATA sections wherever it's found.
*
* Note: it's only necessary to escape the closing `]]>` because
* an additional `', ']]]]>', $javascript );
// Wrap the entire escaped script inside a CDATA section.
$javascript = sprintf( "/* */", $javascript );
}
$javascript = "\n" . trim( $javascript, "\n\r " ) . "\n";
/**
* Filters attributes to be added to a script tag.
*
* @since 5.7.0
*
* @param array $attributes Key-value pairs representing `\n", wp_sanitize_script_attributes( $attributes ), $javascript );
}
/**
* Prints inline JavaScript wrapped in `" from
* around an inline script after trimming whitespace. Typlically this
* is used in conjunction with output buffering, where `ob_get_clean()`
* is passed as the `$contents` argument.
*
* Example:
*
* // Strips exact literal empty SCRIPT tags.
* $js = ';
* 'sayHello();' === wp_remove_surrounding_empty_script_tags( $js );
*
* // Otherwise if anything is different it warns in the JS console.
* $js = '';
* 'console.error( ... )' === wp_remove_surrounding_empty_script_tags( $js );
*
* @private
* @since 6.4.0
*
* @see wp_print_inline_script_tag()
* @see wp_get_inline_script_tag()
*
* @param string $contents Script body with manually created SCRIPT tag literals.
* @return string Script body without surrounding script tag literals, or
* original contents if both exact literals aren't present.
*/
function wp_remove_surrounding_empty_script_tags( $contents ) {
$contents = trim( $contents );
$opener = '';
if (
strlen( $contents ) > strlen( $opener ) + strlen( $closer ) &&
strtoupper( substr( $contents, 0, strlen( $opener ) ) ) === $opener &&
strtoupper( substr( $contents, -strlen( $closer ) ) ) === $closer
) {
return substr( $contents, strlen( $opener ), -strlen( $closer ) );
} else {
$error_message = __( 'Expected string to start with script tag (without attributes) and end with script tag, with optional whitespace.' );
_doing_it_wrong( __FUNCTION__, $error_message, '6.4' );
return sprintf( 'console.error(%s)', wp_json_encode( __( 'Function wp_remove_surrounding_empty_script_tags() used incorrectly in PHP.' ) . ' ' . $error_message ) );
}
}