of a post type. The function will return a piece of SQL code
* that can be added to a WHERE clause; this SQL is constructed to allow all
* published posts, and all private posts to which the user has access.
*
* @since 2.2.0
* @since 4.3.0 Added the ability to pass an array to `$post_type`.
*
* @param string|array $post_type Single post type or an array of post types. Currently only supports 'post' or 'page'.
* @return string SQL code that can be added to a where clause.
*/
function get_private_posts_cap_sql( $post_type ) {
return get_posts_by_author_sql( $post_type, false );
}
/**
* Retrieves the post SQL based on capability, author, and type.
*
* @since 3.0.0
* @since 4.3.0 Introduced the ability to pass an array of post types to `$post_type`.
*
* @see get_private_posts_cap_sql()
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string|string[] $post_type Single post type or an array of post types.
* @param bool $full Optional. Returns a full WHERE statement instead of just
* an 'andalso' term. Default true.
* @param int $post_author Optional. Query posts having a single author ID. Default null.
* @param bool $public_only Optional. Only return public posts. Skips cap checks for
* $current_user. Default false.
* @return string SQL WHERE code that can be added to a query.
*/
function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
global $wpdb;
if ( is_array( $post_type ) ) {
$post_types = $post_type;
} else {
$post_types = array( $post_type );
}
$post_type_clauses = array();
foreach ( $post_types as $post_type ) {
$post_type_obj = get_post_type_object( $post_type );
if ( ! $post_type_obj ) {
continue;
}
/**
* Filters the capability to read private posts for a custom post type
* when generating SQL for getting posts by author.
*
* @since 2.2.0
* @deprecated 3.2.0 The hook transitioned from "somewhat useless" to "totally useless".
*
* @param string $cap Capability.
*/
$cap = apply_filters_deprecated( 'pub_priv_sql_capability', array( '' ), '3.2.0' );
if ( ! $cap ) {
$cap = current_user_can( $post_type_obj->cap->read_private_posts );
}
// Only need to check the cap if $public_only is false.
$post_status_sql = "post_status = 'publish'";
if ( false === $public_only ) {
if ( $cap ) {
// Does the user have the capability to view private posts? Guess so.
$post_status_sql .= " OR post_status = 'private'";
} elseif ( is_user_logged_in() ) {
// Users can view their own private posts.
$id = get_current_user_id();
if ( null === $post_author || ! $full ) {
$post_status_sql .= " OR post_status = 'private' AND post_author = $id";
} elseif ( $id == (int) $post_author ) {
$post_status_sql .= " OR post_status = 'private'";
} // Else none.
} // Else none.
}
$post_type_clauses[] = "( post_type = '" . $post_type . "' AND ( $post_status_sql ) )";
}
if ( empty( $post_type_clauses ) ) {
return $full ? 'WHERE 1 = 0' : '1 = 0';
}
$sql = '( ' . implode( ' OR ', $post_type_clauses ) . ' )';
if ( null !== $post_author ) {
$sql .= $wpdb->prepare( ' AND post_author = %d', $post_author );
}
if ( $full ) {
$sql = 'WHERE ' . $sql;
}
return $sql;
}
/**
* Retrieves the most recent time that a post on the site was published.
*
* The server timezone is the default and is the difference between GMT and
* server time. The 'blog' value is the date when the last post was posted.
* The 'gmt' is when the last post was posted in GMT formatted date.
*
* @since 0.71
* @since 4.4.0 The `$post_type` argument was added.
*
* @param string $timezone Optional. The timezone for the timestamp. Accepts 'server', 'blog', or 'gmt'.
* 'server' uses the server's internal timezone.
* 'blog' uses the `post_date` field, which proxies to the timezone set for the site.
* 'gmt' uses the `post_date_gmt` field.
* Default 'server'.
* @param string $post_type Optional. The post type to check. Default 'any'.
* @return string The date of the last post, or false on failure.
*/
function get_lastpostdate( $timezone = 'server', $post_type = 'any' ) {
$lastpostdate = _get_last_post_time( $timezone, 'date', $post_type );
/**
* Filters the most recent time that a post on the site was published.
*
* @since 2.3.0
* @since 5.5.0 Added the `$post_type` parameter.
*
* @param string|false $lastpostdate The most recent time that a post was published,
* in 'Y-m-d H:i:s' format. False on failure.
* @param string $timezone Location to use for getting the post published date.
* See get_lastpostdate() for accepted `$timezone` values.
* @param string $post_type The post type to check.
*/
return apply_filters( 'get_lastpostdate', $lastpostdate, $timezone, $post_type );
}
/**
* Gets the most recent time that a post on the site was modified.
*
* The server timezone is the default and is the difference between GMT and
* server time. The 'blog' value is just when the last post was modified.
* The 'gmt' is when the last post was modified in GMT time.
*
* @since 1.2.0
* @since 4.4.0 The `$post_type` argument was added.
*
* @param string $timezone Optional. The timezone for the timestamp. See get_lastpostdate()
* for information on accepted values.
* Default 'server'.
* @param string $post_type Optional. The post type to check. Default 'any'.
* @return string The timestamp in 'Y-m-d H:i:s' format, or false on failure.
*/
function get_lastpostmodified( $timezone = 'server', $post_type = 'any' ) {
/**
* Pre-filter the return value of get_lastpostmodified() before the query is run.
*
* @since 4.4.0
*
* @param string|false $lastpostmodified The most recent time that a post was modified,
* in 'Y-m-d H:i:s' format, or false. Returning anything
* other than false will short-circuit the function.
* @param string $timezone Location to use for getting the post modified date.
* See get_lastpostdate() for accepted `$timezone` values.
* @param string $post_type The post type to check.
*/
$lastpostmodified = apply_filters( 'pre_get_lastpostmodified', false, $timezone, $post_type );
if ( false !== $lastpostmodified ) {
return $lastpostmodified;
}
$lastpostmodified = _get_last_post_time( $timezone, 'modified', $post_type );
$lastpostdate = get_lastpostdate( $timezone, $post_type );
if ( $lastpostdate > $lastpostmodified ) {
$lastpostmodified = $lastpostdate;
}
/**
* Filters the most recent time that a post on the site was modified.
*
* @since 2.3.0
* @since 5.5.0 Added the `$post_type` parameter.
*
* @param string|false $lastpostmodified The most recent time that a post was modified,
* in 'Y-m-d H:i:s' format. False on failure.
* @param string $timezone Location to use for getting the post modified date.
* See get_lastpostdate() for accepted `$timezone` values.
* @param string $post_type The post type to check.
*/
return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone, $post_type );
}
/**
* Gets the timestamp of the last time any post was modified or published.
*
* @since 3.1.0
* @since 4.4.0 The `$post_type` argument was added.
* @access private
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $timezone The timezone for the timestamp. See get_lastpostdate().
* for information on accepted values.
* @param string $field Post field to check. Accepts 'date' or 'modified'.
* @param string $post_type Optional. The post type to check. Default 'any'.
* @return string|false The timestamp in 'Y-m-d H:i:s' format, or false on failure.
*/
function _get_last_post_time( $timezone, $field, $post_type = 'any' ) {
global $wpdb;
if ( ! in_array( $field, array( 'date', 'modified' ), true ) ) {
return false;
}
$timezone = strtolower( $timezone );
$key = "lastpost{$field}:$timezone";
if ( 'any' !== $post_type ) {
$key .= ':' . sanitize_key( $post_type );
}
$date = wp_cache_get( $key, 'timeinfo' );
if ( false !== $date ) {
return $date;
}
if ( 'any' === $post_type ) {
$post_types = get_post_types( array( 'public' => true ) );
array_walk( $post_types, array( $wpdb, 'escape_by_ref' ) );
$post_types = "'" . implode( "', '", $post_types ) . "'";
} else {
$post_types = "'" . sanitize_key( $post_type ) . "'";
}
switch ( $timezone ) {
case 'gmt':
$date = $wpdb->get_var( "SELECT post_{$field}_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1" );
break;
case 'blog':
$date = $wpdb->get_var( "SELECT post_{$field} FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1" );
break;
case 'server':
$add_seconds_server = gmdate( 'Z' );
$date = $wpdb->get_var( "SELECT DATE_ADD(post_{$field}_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1" );
break;
}
if ( $date ) {
wp_cache_set( $key, $date, 'timeinfo' );
return $date;
}
return false;
}
/**
* Updates posts in cache.
*
* @since 1.5.1
*
* @param WP_Post[] $posts Array of post objects (passed by reference).
*/
function update_post_cache( &$posts ) {
if ( ! $posts ) {
return;
}
$data = array();
foreach ( $posts as $post ) {
if ( empty( $post->filter ) || 'raw' !== $post->filter ) {
$post = sanitize_post( $post, 'raw' );
}
$data[ $post->ID ] = $post;
}
wp_cache_add_multiple( $data, 'posts' );
}
/**
* Will clean the post in the cache.
*
* Cleaning means delete from the cache of the post. Will call to clean the term
* object cache associated with the post ID.
*
* This function not run if $_wp_suspend_cache_invalidation is not empty. See
* wp_suspend_cache_invalidation().
*
* @since 2.0.0
*
* @global bool $_wp_suspend_cache_invalidation
*
* @param int|WP_Post $post Post ID or post object to remove from the cache.
*/
function clean_post_cache( $post ) {
global $_wp_suspend_cache_invalidation;
if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
return;
}
$post = get_post( $post );
if ( ! $post ) {
return;
}
wp_cache_delete( $post->ID, 'posts' );
wp_cache_delete( 'post_parent:' . (string) $post->ID, 'posts' );
wp_cache_delete( $post->ID, 'post_meta' );
clean_object_term_cache( $post->ID, $post->post_type );
wp_cache_delete( 'wp_get_archives', 'general' );
/**
* Fires immediately after the given post's cache is cleaned.
*
* @since 2.5.0
*
* @param int $post_id Post ID.
* @param WP_Post $post Post object.
*/
do_action( 'clean_post_cache', $post->ID, $post );
if ( 'page' === $post->post_type ) {
wp_cache_delete( 'all_page_ids', 'posts' );
/**
* Fires immediately after the given page's cache is cleaned.
*
* @since 2.5.0
*
* @param int $post_id Post ID.
*/
do_action( 'clean_page_cache', $post->ID );
}
wp_cache_set_posts_last_changed();
}
/**
* Updates post, term, and metadata caches for a list of post objects.
*
* @since 1.5.0
*
* @param WP_Post[] $posts Array of post objects (passed by reference).
* @param string $post_type Optional. Post type. Default 'post'.
* @param bool $update_term_cache Optional. Whether to update the term cache. Default true.
* @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
*/
function update_post_caches( &$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true ) {
// No point in doing all this work if we didn't match any posts.
if ( ! $posts ) {
return;
}
update_post_cache( $posts );
$post_ids = array();
foreach ( $posts as $post ) {
$post_ids[] = $post->ID;
}
if ( ! $post_type ) {
$post_type = 'any';
}
if ( $update_term_cache ) {
if ( is_array( $post_type ) ) {
$ptypes = $post_type;
} elseif ( 'any' === $post_type ) {
$ptypes = array();
// Just use the post_types in the supplied posts.
foreach ( $posts as $post ) {
$ptypes[] = $post->post_type;
}
$ptypes = array_unique( $ptypes );
} else {
$ptypes = array( $post_type );
}
if ( ! empty( $ptypes ) ) {
update_object_term_cache( $post_ids, $ptypes );
}
}
if ( $update_meta_cache ) {
update_postmeta_cache( $post_ids );
}
}
/**
* Updates post author user caches for a list of post objects.
*
* @since 6.1.0
*
* @param WP_Post[] $posts Array of post objects.
*/
function update_post_author_caches( $posts ) {
/*
* cache_users() is a pluggable function so is not available prior
* to the `plugins_loaded` hook firing. This is to ensure against
* fatal errors when the function is not available.
*/
if ( ! function_exists( 'cache_users' ) ) {
return;
}
$author_ids = wp_list_pluck( $posts, 'post_author' );
$author_ids = array_map( 'absint', $author_ids );
$author_ids = array_unique( array_filter( $author_ids ) );
cache_users( $author_ids );
}
/**
* Updates parent post caches for a list of post objects.
*
* @since 6.1.0
*
* @param WP_Post[] $posts Array of post objects.
*/
function update_post_parent_caches( $posts ) {
$parent_ids = wp_list_pluck( $posts, 'post_parent' );
$parent_ids = array_map( 'absint', $parent_ids );
$parent_ids = array_unique( array_filter( $parent_ids ) );
if ( ! empty( $parent_ids ) ) {
_prime_post_caches( $parent_ids, false );
}
}
/**
* Updates metadata cache for a list of post IDs.
*
* Performs SQL query to retrieve the metadata for the post IDs and updates the
* metadata cache for the posts. Therefore, the functions, which call this
* function, do not need to perform SQL queries on their own.
*
* @since 2.1.0
*
* @param int[] $post_ids Array of post IDs.
* @return array|false An array of metadata on success, false if there is nothing to update.
*/
function update_postmeta_cache( $post_ids ) {
return update_meta_cache( 'post', $post_ids );
}
/**
* Will clean the attachment in the cache.
*
* Cleaning means delete from the cache. Optionally will clean the term
* object cache associated with the attachment ID.
*
* This function will not run if $_wp_suspend_cache_invalidation is not empty.
*
* @since 3.0.0
*
* @global bool $_wp_suspend_cache_invalidation
*
* @param int $id The attachment ID in the cache to clean.
* @param bool $clean_terms Optional. Whether to clean terms cache. Default false.
*/
function clean_attachment_cache( $id, $clean_terms = false ) {
global $_wp_suspend_cache_invalidation;
if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
return;
}
$id = (int) $id;
wp_cache_delete( $id, 'posts' );
wp_cache_delete( $id, 'post_meta' );
if ( $clean_terms ) {
clean_object_term_cache( $id, 'attachment' );
}
/**
* Fires after the given attachment's cache is cleaned.
*
* @since 3.0.0
*
* @param int $id Attachment ID.
*/
do_action( 'clean_attachment_cache', $id );
}
//
// Hooks.
//
/**
* Hook for managing future post transitions to published.
*
* @since 2.3.0
* @access private
*
* @see wp_clear_scheduled_hook()
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $new_status New post status.
* @param string $old_status Previous post status.
* @param WP_Post $post Post object.
*/
function _transition_post_status( $new_status, $old_status, $post ) {
global $wpdb;
if ( 'publish' !== $old_status && 'publish' === $new_status ) {
// Reset GUID if transitioning to publish and it is empty.
if ( '' === get_the_guid( $post->ID ) ) {
$wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
}
/**
* Fires when a post's status is transitioned from private to published.
*
* @since 1.5.0
* @deprecated 2.3.0 Use {@see 'private_to_publish'} instead.
*
* @param int $post_id Post ID.
*/
do_action_deprecated( 'private_to_published', array( $post->ID ), '2.3.0', 'private_to_publish' );
}
// If published posts changed clear the lastpostmodified cache.
if ( 'publish' === $new_status || 'publish' === $old_status ) {
foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
wp_cache_delete( "lastpostdate:$timezone:{$post->post_type}", 'timeinfo' );
}
}
if ( $new_status !== $old_status ) {
wp_cache_delete( _count_posts_cache_key( $post->post_type ), 'counts' );
wp_cache_delete( _count_posts_cache_key( $post->post_type, 'readable' ), 'counts' );
}
// Always clears the hook in case the post status bounced from future to draft.
wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
}
/**
* Hook used to schedule publication for a post marked for the future.
*
* The $post properties used and must exist are 'ID' and 'post_date_gmt'.
*
* @since 2.3.0
* @access private
*
* @param int $deprecated Not used. Can be set to null. Never implemented. Not marked
* as deprecated with _deprecated_argument() as it conflicts with
* wp_transition_post_status() and the default filter for _future_post_hook().
* @param WP_Post $post Post object.
*/
function _future_post_hook( $deprecated, $post ) {
wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT' ), 'publish_future_post', array( $post->ID ) );
}
/**
* Hook to schedule pings and enclosures when a post is published.
*
* Uses XMLRPC_REQUEST and WP_IMPORTING constants.
*
* @since 2.3.0
* @access private
*
* @param int $post_id The ID of the post being published.
*/
function _publish_post_hook( $post_id ) {
if ( defined( 'XMLRPC_REQUEST' ) ) {
/**
* Fires when _publish_post_hook() is called during an XML-RPC request.
*
* @since 2.1.0
*
* @param int $post_id Post ID.
*/
do_action( 'xmlrpc_publish_post', $post_id );
}
if ( defined( 'WP_IMPORTING' ) ) {
return;
}
if ( get_option( 'default_pingback_flag' ) ) {
add_post_meta( $post_id, '_pingme', '1', true );
}
add_post_meta( $post_id, '_encloseme', '1', true );
$to_ping = get_to_ping( $post_id );
if ( ! empty( $to_ping ) ) {
add_post_meta( $post_id, '_trackbackme', '1' );
}
if ( ! wp_next_scheduled( 'do_pings' ) ) {
wp_schedule_single_event( time(), 'do_pings' );
}
}
/**
* Returns the ID of the post's parent.
*
* @since 3.1.0
* @since 5.9.0 The `$post` parameter was made optional.
*
* @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
* @return int|false Post parent ID (which can be 0 if there is no parent),
* or false if the post does not exist.
*/
function wp_get_post_parent_id( $post = null ) {
$post = get_post( $post );
if ( ! $post || is_wp_error( $post ) ) {
return false;
}
return (int) $post->post_parent;
}
/**
* Checks the given subset of the post hierarchy for hierarchy loops.
*
* Prevents loops from forming and breaks those that it finds. Attached
* to the {@see 'wp_insert_post_parent'} filter.
*
* @since 3.1.0
*
* @see wp_find_hierarchy_loop()
*
* @param int $post_parent ID of the parent for the post we're checking.
* @param int $post_id ID of the post we're checking.
* @return int The new post_parent for the post, 0 otherwise.
*/
function wp_check_post_hierarchy_for_loops( $post_parent, $post_id ) {
// Nothing fancy here - bail.
if ( ! $post_parent ) {
return 0;
}
// New post can't cause a loop.
if ( ! $post_id ) {
return $post_parent;
}
// Can't be its own parent.
if ( $post_parent == $post_id ) {
return 0;
}
// Now look for larger loops.
$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_id, $post_parent );
if ( ! $loop ) {
return $post_parent; // No loop.
}
// Setting $post_parent to the given value causes a loop.
if ( isset( $loop[ $post_id ] ) ) {
return 0;
}
// There's a loop, but it doesn't contain $post_id. Break the loop.
foreach ( array_keys( $loop ) as $loop_member ) {
wp_update_post(
array(
'ID' => $loop_member,
'post_parent' => 0,
)
);
}
return $post_parent;
}
/**
* Sets the post thumbnail (featured image) for the given post.
*
* @since 3.1.0
*
* @param int|WP_Post $post Post ID or post object where thumbnail should be attached.
* @param int $thumbnail_id Thumbnail to attach.
* @return int|bool True on success, false on failure.
*/
function set_post_thumbnail( $post, $thumbnail_id ) {
$post = get_post( $post );
$thumbnail_id = absint( $thumbnail_id );
if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
if ( wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) ) {
return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
} else {
return delete_post_meta( $post->ID, '_thumbnail_id' );
}
}
return false;
}
/**
* Removes the thumbnail (featured image) from the given post.
*
* @since 3.3.0
*
* @param int|WP_Post $post Post ID or post object from which the thumbnail should be removed.
* @return bool True on success, false on failure.
*/
function delete_post_thumbnail( $post ) {
$post = get_post( $post );
if ( $post ) {
return delete_post_meta( $post->ID, '_thumbnail_id' );
}
return false;
}
/**
* Deletes auto-drafts for new posts that are > 7 days old.
*
* @since 3.4.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*/
function wp_delete_auto_drafts() {
global $wpdb;
// Cleanup old auto-drafts more than 7 days old.
$old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
foreach ( (array) $old_posts as $delete ) {
// Force delete.
wp_delete_post( $delete, true );
}
}
/**
* Queues posts for lazy-loading of term meta.
*
* @since 4.5.0
*
* @param WP_Post[] $posts Array of WP_Post objects.
*/
function wp_queue_posts_for_term_meta_lazyload( $posts ) {
$post_type_taxonomies = array();
$prime_post_terms = array();
foreach ( $posts as $post ) {
if ( ! ( $post instanceof WP_Post ) ) {
continue;
}
if ( ! isset( $post_type_taxonomies[ $post->post_type ] ) ) {
$post_type_taxonomies[ $post->post_type ] = get_object_taxonomies( $post->post_type );
}
foreach ( $post_type_taxonomies[ $post->post_type ] as $taxonomy ) {
$prime_post_terms[ $taxonomy ][] = $post->ID;
}
}
$term_ids = array();
if ( $prime_post_terms ) {
foreach ( $prime_post_terms as $taxonomy => $post_ids ) {
$cached_term_ids = wp_cache_get_multiple( $post_ids, "{$taxonomy}_relationships" );
if ( is_array( $cached_term_ids ) ) {
$cached_term_ids = array_filter( $cached_term_ids );
foreach ( $cached_term_ids as $_term_ids ) {
// Backward compatibility for if a plugin is putting objects into the cache, rather than IDs.
foreach ( $_term_ids as $term_id ) {
if ( is_numeric( $term_id ) ) {
$term_ids[] = (int) $term_id;
} elseif ( isset( $term_id->term_id ) ) {
$term_ids[] = (int) $term_id->term_id;
}
}
}
}
}
$term_ids = array_unique( $term_ids );
}
wp_lazyload_term_meta( $term_ids );
}
/**
* Updates the custom taxonomies' term counts when a post's status is changed.
*
* For example, default posts term counts (for custom taxonomies) don't include
* private / draft posts.
*
* @since 3.3.0
* @access private
*
* @param string $new_status New post status.
* @param string $old_status Old post status.
* @param WP_Post $post Post object.
*/
function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
// Update counts for the post's terms.
foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
$tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
wp_update_term_count( $tt_ids, $taxonomy );
}
}
/**
* Adds any posts from the given IDs to the cache that do not already exist in cache.
*
* @since 3.4.0
* @since 6.1.0 This function is no longer marked as "private".
*
* @see update_post_cache()
* @see update_postmeta_cache()
* @see update_object_term_cache()
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int[] $ids ID list.
* @param bool $update_term_cache Optional. Whether to update the term cache. Default true.
* @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
*/
function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
global $wpdb;
$non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
if ( ! empty( $non_cached_ids ) ) {
$fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", implode( ',', $non_cached_ids ) ) );
if ( $fresh_posts ) {
// Despite the name, update_post_cache() expects an array rather than a single post.
update_post_cache( $fresh_posts );
}
}
if ( $update_meta_cache ) {
update_postmeta_cache( $ids );
}
if ( $update_term_cache ) {
$post_types = array_map( 'get_post_type', $ids );
$post_types = array_unique( $post_types );
update_object_term_cache( $ids, $post_types );
}
}
/**
* Prime the cache containing the parent ID of various post objects.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @since 6.4.0
*
* @param int[] $ids ID list.
*/
function _prime_post_parent_id_caches( array $ids ) {
global $wpdb;
$ids = array_filter( $ids, '_validate_cache_id' );
$ids = array_unique( array_map( 'intval', $ids ), SORT_NUMERIC );
if ( empty( $ids ) ) {
return;
}
$cache_keys = array();
foreach ( $ids as $id ) {
$cache_keys[ $id ] = 'post_parent:' . (string) $id;
}
$cached_data = wp_cache_get_multiple( array_values( $cache_keys ), 'posts' );
$non_cached_ids = array();
foreach ( $cache_keys as $id => $cache_key ) {
if ( false === $cached_data[ $cache_key ] ) {
$non_cached_ids[] = $id;
}
}
if ( ! empty( $non_cached_ids ) ) {
$fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.ID, $wpdb->posts.post_parent FROM $wpdb->posts WHERE ID IN (%s)", implode( ',', $non_cached_ids ) ) );
if ( $fresh_posts ) {
$post_parent_data = array();
foreach ( $fresh_posts as $fresh_post ) {
$post_parent_data[ 'post_parent:' . (string) $fresh_post->ID ] = (int) $fresh_post->post_parent;
}
wp_cache_add_multiple( $post_parent_data, 'posts' );
}
}
}
/**
* Adds a suffix if any trashed posts have a given slug.
*
* Store its desired (i.e. current) slug so it can try to reclaim it
* if the post is untrashed.
*
* For internal use.
*
* @since 4.5.0
* @access private
*
* @param string $post_name Post slug.
* @param int $post_id Optional. Post ID that should be ignored. Default 0.
*/
function wp_add_trashed_suffix_to_post_name_for_trashed_posts( $post_name, $post_id = 0 ) {
$trashed_posts_with_desired_slug = get_posts(
array(
'name' => $post_name,
'post_status' => 'trash',
'post_type' => 'any',
'nopaging' => true,
'post__not_in' => array( $post_id ),
)
);
if ( ! empty( $trashed_posts_with_desired_slug ) ) {
foreach ( $trashed_posts_with_desired_slug as $_post ) {
wp_add_trashed_suffix_to_post_name_for_post( $_post );
}
}
}
/**
* Adds a trashed suffix for a given post.
*
* Store its desired (i.e. current) slug so it can try to reclaim it
* if the post is untrashed.
*
* For internal use.
*
* @since 4.5.0
* @access private
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param WP_Post $post The post.
* @return string New slug for the post.
*/
function wp_add_trashed_suffix_to_post_name_for_post( $post ) {
global $wpdb;
$post = get_post( $post );
if ( str_ends_with( $post->post_name, '__trashed' ) ) {
return $post->post_name;
}
add_post_meta( $post->ID, '_wp_desired_post_slug', $post->post_name );
$post_name = _truncate_post_slug( $post->post_name, 191 ) . '__trashed';
$wpdb->update( $wpdb->posts, array( 'post_name' => $post_name ), array( 'ID' => $post->ID ) );
clean_post_cache( $post->ID );
return $post_name;
}
/**
* Sets the last changed time for the 'posts' cache group.
*
* @since 5.0.0
*/
function wp_cache_set_posts_last_changed() {
wp_cache_set_last_changed( 'posts' );
}
/**
* Gets all available post MIME types for a given post type.
*
* @since 2.5.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $type
* @return string[] An array of MIME types.
*/
function get_available_post_mime_types( $type = 'attachment' ) {
global $wpdb;
/**
* Filters the list of available post MIME types for the given post type.
*
* @since 6.4.0
*
* @param string[]|null $mime_types An array of MIME types. Default null.
* @param string $type The post type name. Usually 'attachment' but can be any post type.
*/
$mime_types = apply_filters( 'pre_get_available_post_mime_types', null, $type );
if ( ! is_array( $mime_types ) ) {
$mime_types = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s", $type ) );
}
return $mime_types;
}
/**
* Retrieves the path to an uploaded image file.
*
* Similar to `get_attached_file()` however some images may have been processed after uploading
* to make them suitable for web use. In this case the attached "full" size file is usually replaced
* with a scaled down version of the original image. This function always returns the path
* to the originally uploaded image file.
*
* @since 5.3.0
* @since 5.4.0 Added the `$unfiltered` parameter.
*
* @param int $attachment_id Attachment ID.
* @param bool $unfiltered Optional. Passed through to `get_attached_file()`. Default false.
* @return string|false Path to the original image file or false if the attachment is not an image.
*/
function wp_get_original_image_path( $attachment_id, $unfiltered = false ) {
if ( ! wp_attachment_is_image( $attachment_id ) ) {
return false;
}
$image_meta = wp_get_attachment_metadata( $attachment_id );
$image_file = get_attached_file( $attachment_id, $unfiltered );
if ( empty( $image_meta['original_image'] ) ) {
$original_image = $image_file;
} else {
$original_image = path_join( dirname( $image_file ), $image_meta['original_image'] );
}
/**
* Filters the path to the original image.
*
* @since 5.3.0
*
* @param string $original_image Path to original image file.
* @param int $attachment_id Attachment ID.
*/
return apply_filters( 'wp_get_original_image_path', $original_image, $attachment_id );
}
/**
* Retrieves the URL to an original attachment image.
*
* Similar to `wp_get_attachment_url()` however some images may have been
* processed after uploading. In this case this function returns the URL
* to the originally uploaded image file.
*
* @since 5.3.0
*
* @param int $attachment_id Attachment post ID.
* @return string|false Attachment image URL, false on error or if the attachment is not an image.
*/
function wp_get_original_image_url( $attachment_id ) {
if ( ! wp_attachment_is_image( $attachment_id ) ) {
return false;
}
$image_url = wp_get_attachment_url( $attachment_id );
if ( ! $image_url ) {
return false;
}
$image_meta = wp_get_attachment_metadata( $attachment_id );
if ( empty( $image_meta['original_image'] ) ) {
$original_image_url = $image_url;
} else {
$original_image_url = path_join( dirname( $image_url ), $image_meta['original_image'] );
}
/**
* Filters the URL to the original attachment image.
*
* @since 5.3.0
*
* @param string $original_image_url URL to original image.
* @param int $attachment_id Attachment ID.
*/
return apply_filters( 'wp_get_original_image_url', $original_image_url, $attachment_id );
}
/**
* Filters callback which sets the status of an untrashed post to its previous status.
*
* This can be used as a callback on the `wp_untrash_post_status` filter.
*
* @since 5.6.0
*
* @param string $new_status The new status of the post being restored.
* @param int $post_id The ID of the post being restored.
* @param string $previous_status The status of the post at the point where it was trashed.
* @return string The new status of the post.
*/
function wp_untrash_post_set_previous_status( $new_status, $post_id, $previous_status ) {
return $previous_status;
}
/**
* Returns whether the post can be edited in the block editor.
*
* @since 5.0.0
* @since 6.1.0 Moved to wp-includes from wp-admin.
*
* @param int|WP_Post $post Post ID or WP_Post object.
* @return bool Whether the post can be edited in the block editor.
*/
function use_block_editor_for_post( $post ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
// We're in the meta box loader, so don't use the block editor.
if ( is_admin() && isset( $_GET['meta-box-loader'] ) ) {
check_admin_referer( 'meta-box-loader', 'meta-box-loader-nonce' );
return false;
}
$use_block_editor = use_block_editor_for_post_type( $post->post_type );
/**
* Filters whether a post is able to be edited in the block editor.
*
* @since 5.0.0
*
* @param bool $use_block_editor Whether the post can be edited or not.
* @param WP_Post $post The post being checked.
*/
return apply_filters( 'use_block_editor_for_post', $use_block_editor, $post );
}
/**
* Returns whether a post type is compatible with the block editor.
*
* The block editor depends on the REST API, and if the post type is not shown in the
* REST API, then it won't work with the block editor.
*
* @since 5.0.0
* @since 6.1.0 Moved to wp-includes from wp-admin.
*
* @param string $post_type The post type.
* @return bool Whether the post type can be edited with the block editor.
*/
function use_block_editor_for_post_type( $post_type ) {
if ( ! post_type_exists( $post_type ) ) {
return false;
}
if ( ! post_type_supports( $post_type, 'editor' ) ) {
return false;
}
$post_type_object = get_post_type_object( $post_type );
if ( $post_type_object && ! $post_type_object->show_in_rest ) {
return false;
}
/**
* Filters whether a post is able to be edited in the block editor.
*
* @since 5.0.0
*
* @param bool $use_block_editor Whether the post type can be edited or not. Default true.
* @param string $post_type The post type being checked.
*/
return apply_filters( 'use_block_editor_for_post_type', true, $post_type );
}
/**
* Registers any additional post meta fields.
*
* @since 6.3.0 Adds `wp_pattern_sync_status` meta field to the wp_block post type so an unsynced option can be added.
*
* @link https://github.com/WordPress/gutenberg/pull/51144
*/
function wp_create_initial_post_meta() {
register_post_meta(
'wp_block',
'wp_pattern_sync_status',
array(
'sanitize_callback' => 'sanitize_text_field',
'single' => true,
'type' => 'string',
'show_in_rest' => array(
'schema' => array(
'type' => 'string',
'enum' => array( 'partial', 'unsynced' ),
),
),
)
);
}
onal data.
*
* @type array[] $data An array of personal data arrays.
* @type bool $done Whether the exporter is finished.
* }
*/
function wp_media_personal_data_exporter( $email_address, $page = 1 ) {
// Limit us to 50 attachments at a time to avoid timing out.
$number = 50;
$page = (int) $page;
$data_to_export = array();
$user = get_user_by( 'email', $email_address );
if ( false === $user ) {
return array(
'data' => $data_to_export,
'done' => true,
);
}
$post_query = new WP_Query(
array(
'author' => $user->ID,
'posts_per_page' => $number,
'paged' => $page,
'post_type' => 'attachment',
'post_status' => 'any',
'orderby' => 'ID',
'order' => 'ASC',
)
);
foreach ( (array) $post_query->posts as $post ) {
$attachment_url = wp_get_attachment_url( $post->ID );
if ( $attachment_url ) {
$post_data_to_export = array(
array(
'name' => __( 'URL' ),
'value' => $attachment_url,
),
);
$data_to_export[] = array(
'group_id' => 'media',
'group_label' => __( 'Media' ),
'group_description' => __( 'User’s media data.' ),
'item_id' => "post-{$post->ID}",
'data' => $post_data_to_export,
);
}
}
$done = $post_query->max_num_pages <= $page;
return array(
'data' => $data_to_export,
'done' => $done,
);
}
/**
* Adds additional default image sub-sizes.
*
* These sizes are meant to enhance the way WordPress displays images on the front-end on larger,
* high-density devices. They make it possible to generate more suitable `srcset` and `sizes` attributes
* when the users upload large images.
*
* The sizes can be changed or removed by themes and plugins but that is not recommended.
* The size "names" reflect the image dimensions, so changing the sizes would be quite misleading.
*
* @since 5.3.0
* @access private
*/
function _wp_add_additional_image_sizes() {
// 2x medium_large size.
add_image_size( '1536x1536', 1536, 1536 );
// 2x large size.
add_image_size( '2048x2048', 2048, 2048 );
}
/**
* Callback to enable showing of the user error when uploading .heic images.
*
* @since 5.5.0
*
* @param array[] $plupload_settings The settings for Plupload.js.
* @return array[] Modified settings for Plupload.js.
*/
function wp_show_heic_upload_error( $plupload_settings ) {
$plupload_settings['heic_upload_error'] = true;
return $plupload_settings;
}
/**
* Allows PHP's getimagesize() to be debuggable when necessary.
*
* @since 5.7.0
* @since 5.8.0 Added support for WebP images.
* @since 6.5.0 Added support for AVIF images.
*
* @param string $filename The file path.
* @param array $image_info Optional. Extended image information (passed by reference).
* @return array|false Array of image information or false on failure.
*/
function wp_getimagesize( $filename, array &$image_info = null ) {
// Don't silence errors when in debug mode, unless running unit tests.
if ( defined( 'WP_DEBUG' ) && WP_DEBUG
&& ! defined( 'WP_RUN_CORE_TESTS' )
) {
if ( 2 === func_num_args() ) {
$info = getimagesize( $filename, $image_info );
} else {
$info = getimagesize( $filename );
}
} else {
/*
* Silencing notice and warning is intentional.
*
* getimagesize() has a tendency to generate errors, such as
* "corrupt JPEG data: 7191 extraneous bytes before marker",
* even when it's able to provide image size information.
*
* See https://core.trac.wordpress.org/ticket/42480
*/
if ( 2 === func_num_args() ) {
$info = @getimagesize( $filename, $image_info );
} else {
$info = @getimagesize( $filename );
}
}
if (
! empty( $info ) &&
// Some PHP versions return 0x0 sizes from `getimagesize` for unrecognized image formats, including AVIFs.
! ( empty( $info[0] ) && empty( $info[1] ) )
) {
return $info;
}
/*
* For PHP versions that don't support WebP images,
* extract the image size info from the file headers.
*/
if ( 'image/webp' === wp_get_image_mime( $filename ) ) {
$webp_info = wp_get_webp_info( $filename );
$width = $webp_info['width'];
$height = $webp_info['height'];
// Mimic the native return format.
if ( $width && $height ) {
return array(
$width,
$height,
IMAGETYPE_WEBP,
sprintf(
'width="%d" height="%d"',
$width,
$height
),
'mime' => 'image/webp',
);
}
}
// For PHP versions that don't support AVIF images, extract the image size info from the file headers.
if ( 'image/avif' === wp_get_image_mime( $filename ) ) {
$avif_info = wp_get_avif_info( $filename );
$width = $avif_info['width'];
$height = $avif_info['height'];
// Mimic the native return format.
if ( $width && $height ) {
return array(
$width,
$height,
IMAGETYPE_AVIF,
sprintf(
'width="%d" height="%d"',
$width,
$height
),
'mime' => 'image/avif',
);
}
}
// The image could not be parsed.
return false;
}
/**
* Extracts meta information about an AVIF file: width, height, bit depth, and number of channels.
*
* @since 6.5.0
*
* @param string $filename Path to an AVIF file.
* @return array {
* An array of AVIF image information.
*
* @type int|false $width Image width on success, false on failure.
* @type int|false $height Image height on success, false on failure.
* @type int|false $bit_depth Image bit depth on success, false on failure.
* @type int|false $num_channels Image number of channels on success, false on failure.
* }
*/
function wp_get_avif_info( $filename ) {
$results = array(
'width' => false,
'height' => false,
'bit_depth' => false,
'num_channels' => false,
);
if ( 'image/avif' !== wp_get_image_mime( $filename ) ) {
return $results;
}
// Parse the file using libavifinfo's PHP implementation.
require_once ABSPATH . WPINC . '/class-avif-info.php';
$handle = fopen( $filename, 'rb' );
if ( $handle ) {
$parser = new Avifinfo\Parser( $handle );
$success = $parser->parse_ftyp() && $parser->parse_file();
fclose( $handle );
if ( $success ) {
$results = $parser->features->primary_item_features;
}
}
return $results;
}
/**
* Extracts meta information about a WebP file: width, height, and type.
*
* @since 5.8.0
*
* @param string $filename Path to a WebP file.
* @return array {
* An array of WebP image information.
*
* @type int|false $width Image width on success, false on failure.
* @type int|false $height Image height on success, false on failure.
* @type string|false $type The WebP type: one of 'lossy', 'lossless' or 'animated-alpha'.
* False on failure.
* }
*/
function wp_get_webp_info( $filename ) {
$width = false;
$height = false;
$type = false;
if ( 'image/webp' !== wp_get_image_mime( $filename ) ) {
return compact( 'width', 'height', 'type' );
}
$magic = file_get_contents( $filename, false, null, 0, 40 );
if ( false === $magic ) {
return compact( 'width', 'height', 'type' );
}
// Make sure we got enough bytes.
if ( strlen( $magic ) < 40 ) {
return compact( 'width', 'height', 'type' );
}
/*
* The headers are a little different for each of the three formats.
* Header values based on WebP docs, see https://developers.google.com/speed/webp/docs/riff_container.
*/
switch ( substr( $magic, 12, 4 ) ) {
// Lossy WebP.
case 'VP8 ':
$parts = unpack( 'v2', substr( $magic, 26, 4 ) );
$width = (int) ( $parts[1] & 0x3FFF );
$height = (int) ( $parts[2] & 0x3FFF );
$type = 'lossy';
break;
// Lossless WebP.
case 'VP8L':
$parts = unpack( 'C4', substr( $magic, 21, 4 ) );
$width = (int) ( $parts[1] | ( ( $parts[2] & 0x3F ) << 8 ) ) + 1;
$height = (int) ( ( ( $parts[2] & 0xC0 ) >> 6 ) | ( $parts[3] << 2 ) | ( ( $parts[4] & 0x03 ) << 10 ) ) + 1;
$type = 'lossless';
break;
// Animated/alpha WebP.
case 'VP8X':
// Pad 24-bit int.
$width = unpack( 'V', substr( $magic, 24, 3 ) . "\x00" );
$width = (int) ( $width[1] & 0xFFFFFF ) + 1;
// Pad 24-bit int.
$height = unpack( 'V', substr( $magic, 27, 3 ) . "\x00" );
$height = (int) ( $height[1] & 0xFFFFFF ) + 1;
$type = 'animated-alpha';
break;
}
return compact( 'width', 'height', 'type' );
}
/**
* Gets loading optimization attributes.
*
* This function returns an array of attributes that should be merged into the given attributes array to optimize
* loading performance. Potential attributes returned by this function are:
* - `loading` attribute with a value of "lazy"
* - `fetchpriority` attribute with a value of "high"
* - `decoding` attribute with a value of "async"
*
* If any of these attributes are already present in the given attributes, they will not be modified. Note that no
* element should have both `loading="lazy"` and `fetchpriority="high"`, so the function will trigger a warning in case
* both attributes are present with those values.
*
* @since 6.3.0
*
* @global WP_Query $wp_query WordPress Query object.
*
* @param string $tag_name The tag name.
* @param array $attr Array of the attributes for the tag.
* @param string $context Context for the element for which the loading optimization attribute is requested.
* @return array Loading optimization attributes.
*/
function wp_get_loading_optimization_attributes( $tag_name, $attr, $context ) {
global $wp_query;
/**
* Filters whether to short-circuit loading optimization attributes.
*
* Returning an array from the filter will effectively short-circuit the loading of optimization attributes,
* returning that value instead.
*
* @since 6.4.0
*
* @param array|false $loading_attrs False by default, or array of loading optimization attributes to short-circuit.
* @param string $tag_name The tag name.
* @param array $attr Array of the attributes for the tag.
* @param string $context Context for the element for which the loading optimization attribute is requested.
*/
$loading_attrs = apply_filters( 'pre_wp_get_loading_optimization_attributes', false, $tag_name, $attr, $context );
if ( is_array( $loading_attrs ) ) {
return $loading_attrs;
}
$loading_attrs = array();
/*
* Skip lazy-loading for the overall block template, as it is handled more granularly.
* The skip is also applicable for `fetchpriority`.
*/
if ( 'template' === $context ) {
/** This filter is documented in wp-includes/media.php */
return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context );
}
// For now this function only supports images and iframes.
if ( 'img' !== $tag_name && 'iframe' !== $tag_name ) {
/** This filter is documented in wp-includes/media.php */
return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context );
}
/*
* Skip programmatically created images within content blobs as they need to be handled together with the other
* images within the post content or widget content.
* Without this clause, they would already be considered within their own context which skews the image count and
* can result in the first post content image being lazy-loaded or an image further down the page being marked as a
* high priority.
*/
if (
'the_content' !== $context && doing_filter( 'the_content' ) ||
'widget_text_content' !== $context && doing_filter( 'widget_text_content' ) ||
'widget_block_content' !== $context && doing_filter( 'widget_block_content' )
) {
/** This filter is documented in wp-includes/media.php */
return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context );
}
/*
* Add `decoding` with a value of "async" for every image unless it has a
* conflicting `decoding` attribute already present.
*/
if ( 'img' === $tag_name ) {
if ( isset( $attr['decoding'] ) ) {
$loading_attrs['decoding'] = $attr['decoding'];
} else {
$loading_attrs['decoding'] = 'async';
}
}
// For any resources, width and height must be provided, to avoid layout shifts.
if ( ! isset( $attr['width'], $attr['height'] ) ) {
/** This filter is documented in wp-includes/media.php */
return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context );
}
/*
* The key function logic starts here.
*/
$maybe_in_viewport = null;
$increase_count = false;
$maybe_increase_count = false;
// Logic to handle a `loading` attribute that is already provided.
if ( isset( $attr['loading'] ) ) {
/*
* Interpret "lazy" as not in viewport. Any other value can be
* interpreted as in viewport (realistically only "eager" or `false`
* to force-omit the attribute are other potential values).
*/
if ( 'lazy' === $attr['loading'] ) {
$maybe_in_viewport = false;
} else {
$maybe_in_viewport = true;
}
}
// Logic to handle a `fetchpriority` attribute that is already provided.
if ( isset( $attr['fetchpriority'] ) && 'high' === $attr['fetchpriority'] ) {
/*
* If the image was already determined to not be in the viewport (e.g.
* from an already provided `loading` attribute), trigger a warning.
* Otherwise, the value can be interpreted as in viewport, since only
* the most important in-viewport image should have `fetchpriority` set
* to "high".
*/
if ( false === $maybe_in_viewport ) {
_doing_it_wrong(
__FUNCTION__,
__( 'An image should not be lazy-loaded and marked as high priority at the same time.' ),
'6.3.0'
);
/*
* Set `fetchpriority` here for backward-compatibility as we should
* not override what a developer decided, even though it seems
* incorrect.
*/
$loading_attrs['fetchpriority'] = 'high';
} else {
$maybe_in_viewport = true;
}
}
if ( null === $maybe_in_viewport ) {
$header_enforced_contexts = array(
'template_part_' . WP_TEMPLATE_PART_AREA_HEADER => true,
'get_header_image_tag' => true,
);
/**
* Filters the header-specific contexts.
*
* @since 6.4.0
*
* @param array $default_header_enforced_contexts Map of contexts for which elements should be considered
* in the header of the page, as $context => $enabled
* pairs. The $enabled should always be true.
*/
$header_enforced_contexts = apply_filters( 'wp_loading_optimization_force_header_contexts', $header_enforced_contexts );
// Consider elements with these header-specific contexts to be in viewport.
if ( isset( $header_enforced_contexts[ $context ] ) ) {
$maybe_in_viewport = true;
$maybe_increase_count = true;
} elseif ( ! is_admin() && in_the_loop() && is_main_query() ) {
/*
* Get the content media count, since this is a main query
* content element. This is accomplished by "increasing"
* the count by zero, as the only way to get the count is
* to call this function.
* The actual count increase happens further below, based
* on the `$increase_count` flag set here.
*/
$content_media_count = wp_increase_content_media_count( 0 );
$increase_count = true;
// If the count so far is below the threshold, `loading` attribute is omitted.
if ( $content_media_count < wp_omit_loading_attr_threshold() ) {
$maybe_in_viewport = true;
} else {
$maybe_in_viewport = false;
}
} elseif (
// Only apply for main query but before the loop.
$wp_query->before_loop && $wp_query->is_main_query()
/*
* Any image before the loop, but after the header has started should not be lazy-loaded,
* except when the footer has already started which can happen when the current template
* does not include any loop.
*/
&& did_action( 'get_header' ) && ! did_action( 'get_footer' )
) {
$maybe_in_viewport = true;
$maybe_increase_count = true;
}
}
/*
* If the element is in the viewport (`true`), potentially add
* `fetchpriority` with a value of "high". Otherwise, i.e. if the element
* is not not in the viewport (`false`) or it is unknown (`null`), add
* `loading` with a value of "lazy".
*/
if ( $maybe_in_viewport ) {
$loading_attrs = wp_maybe_add_fetchpriority_high_attr( $loading_attrs, $tag_name, $attr );
} else {
// Only add `loading="lazy"` if the feature is enabled.
if ( wp_lazy_loading_enabled( $tag_name, $context ) ) {
$loading_attrs['loading'] = 'lazy';
}
}
/*
* If flag was set based on contextual logic above, increase the content
* media count, either unconditionally, or based on whether the image size
* is larger than the threshold.
*/
if ( $increase_count ) {
wp_increase_content_media_count();
} elseif ( $maybe_increase_count ) {
/** This filter is documented in wp-includes/media.php */
$wp_min_priority_img_pixels = apply_filters( 'wp_min_priority_img_pixels', 50000 );
if ( $wp_min_priority_img_pixels <= $attr['width'] * $attr['height'] ) {
wp_increase_content_media_count();
}
}
/**
* Filters the loading optimization attributes.
*
* @since 6.4.0
*
* @param array $loading_attrs The loading optimization attributes.
* @param string $tag_name The tag name.
* @param array $attr Array of the attributes for the tag.
* @param string $context Context for the element for which the loading optimization attribute is requested.
*/
return apply_filters( 'wp_get_loading_optimization_attributes', $loading_attrs, $tag_name, $attr, $context );
}
/**
* Gets the threshold for how many of the first content media elements to not lazy-load.
*
* This function runs the {@see 'wp_omit_loading_attr_threshold'} filter, which uses a default threshold value of 3.
* The filter is only run once per page load, unless the `$force` parameter is used.
*
* @since 5.9.0
*
* @param bool $force Optional. If set to true, the filter will be (re-)applied even if it already has been before.
* Default false.
* @return int The number of content media elements to not lazy-load.
*/
function wp_omit_loading_attr_threshold( $force = false ) {
static $omit_threshold;
// This function may be called multiple times. Run the filter only once per page load.
if ( ! isset( $omit_threshold ) || $force ) {
/**
* Filters the threshold for how many of the first content media elements to not lazy-load.
*
* For these first content media elements, the `loading` attribute will be omitted. By default, this is the case
* for only the very first content media element.
*
* @since 5.9.0
* @since 6.3.0 The default threshold was changed from 1 to 3.
*
* @param int $omit_threshold The number of media elements where the `loading` attribute will not be added. Default 3.
*/
$omit_threshold = apply_filters( 'wp_omit_loading_attr_threshold', 3 );
}
return $omit_threshold;
}
/**
* Increases an internal content media count variable.
*
* @since 5.9.0
* @access private
*
* @param int $amount Optional. Amount to increase by. Default 1.
* @return int The latest content media count, after the increase.
*/
function wp_increase_content_media_count( $amount = 1 ) {
static $content_media_count = 0;
$content_media_count += $amount;
return $content_media_count;
}
/**
* Determines whether to add `fetchpriority='high'` to loading attributes.
*
* @since 6.3.0
* @access private
*
* @param array $loading_attrs Array of the loading optimization attributes for the element.
* @param string $tag_name The tag name.
* @param array $attr Array of the attributes for the element.
* @return array Updated loading optimization attributes for the element.
*/
function wp_maybe_add_fetchpriority_high_attr( $loading_attrs, $tag_name, $attr ) {
// For now, adding `fetchpriority="high"` is only supported for images.
if ( 'img' !== $tag_name ) {
return $loading_attrs;
}
if ( isset( $attr['fetchpriority'] ) ) {
/*
* While any `fetchpriority` value could be set in `$loading_attrs`,
* for consistency we only do it for `fetchpriority="high"` since that
* is the only possible value that WordPress core would apply on its
* own.
*/
if ( 'high' === $attr['fetchpriority'] ) {
$loading_attrs['fetchpriority'] = 'high';
wp_high_priority_element_flag( false );
}
return $loading_attrs;
}
// Lazy-loading and `fetchpriority="high"` are mutually exclusive.
if ( isset( $loading_attrs['loading'] ) && 'lazy' === $loading_attrs['loading'] ) {
return $loading_attrs;
}
if ( ! wp_high_priority_element_flag() ) {
return $loading_attrs;
}
/**
* Filters the minimum square-pixels threshold for an image to be eligible as the high-priority image.
*
* @since 6.3.0
*
* @param int $threshold Minimum square-pixels threshold. Default 50000.
*/
$wp_min_priority_img_pixels = apply_filters( 'wp_min_priority_img_pixels', 50000 );
if ( $wp_min_priority_img_pixels <= $attr['width'] * $attr['height'] ) {
$loading_attrs['fetchpriority'] = 'high';
wp_high_priority_element_flag( false );
}
return $loading_attrs;
}
/**
* Accesses a flag that indicates if an element is a possible candidate for `fetchpriority='high'`.
*
* @since 6.3.0
* @access private
*
* @param bool $value Optional. Used to change the static variable. Default null.
* @return bool Returns true if high-priority element was marked already, otherwise false.
*/
function wp_high_priority_element_flag( $value = null ) {
static $high_priority_element = true;
if ( is_bool( $value ) ) {
$high_priority_element = $value;
}
return $high_priority_element;
}
Fatal error: Uncaught Error: Call to undefined function _get_custom_object_labels() in /home/islamicf/public_html/wp-includes/taxonomy.php:720
Stack trace:
#0 /home/islamicf/public_html/wp-includes/class-wp-taxonomy.php(486): get_taxonomy_labels(Object(WP_Taxonomy))
#1 /home/islamicf/public_html/wp-includes/class-wp-taxonomy.php(290): WP_Taxonomy->set_props('post', Array)
#2 /home/islamicf/public_html/wp-includes/taxonomy.php(532): WP_Taxonomy->__construct('category', 'post', Array)
#3 /home/islamicf/public_html/wp-includes/taxonomy.php(82): register_taxonomy('category', 'post', Array)
#4 /home/islamicf/public_html/wp-settings.php(499): create_initial_taxonomies()
#5 /home/islamicf/public_html/wp-config.php(99): require_once('/home/islamicf/...')
#6 /home/islamicf/public_html/wp-load.php(50): require_once('/home/islamicf/...')
#7 /home/islamicf/public_html/wp-blog-header.php(13): require_once('/home/islamicf/...')
#8 /home/islamicf/public_html/index.php(17): require('/home/islamicf/...')
#9 {main}
thrown in /home/islamicf/public_html/wp-includes/taxonomy.php on line 720