ibutes containing the text direction and language * information for the page. * * @since 2.1.0 * @since 4.3.0 Converted into a wrapper for get_language_attributes(). * * @param string $doctype Optional. The type of HTML document. Accepts 'xhtml' or 'html'. Default 'html'. */ function language_attributes( $doctype = 'html' ) { echo get_language_attributes( $doctype ); } /** * Retrieves paginated links for archive post pages. * * Technically, the function can be used to create paginated link list for any * area. The 'base' argument is used to reference the url, which will be used to * create the paginated links. The 'format' argument is then used for replacing * the page number. It is however, most likely and by default, to be used on the * archive post pages. * * The 'type' argument controls format of the returned value. The default is * 'plain', which is just a string with the links separated by a newline * character. The other possible values are either 'array' or 'list'. The * 'array' value will return an array of the paginated link list to offer full * control of display. The 'list' value will place all of the paginated links in * an unordered HTML list. * * The 'total' argument is the total amount of pages and is an integer. The * 'current' argument is the current page number and is also an integer. * * An example of the 'base' argument is "http://example.com/all_posts.php%_%" * and the '%_%' is required. The '%_%' will be replaced by the contents of in * the 'format' argument. An example for the 'format' argument is "?page=%#%" * and the '%#%' is also required. The '%#%' will be replaced with the page * number. * * You can include the previous and next links in the list by setting the * 'prev_next' argument to true, which it is by default. You can set the * previous text, by using the 'prev_text' argument. You can set the next text * by setting the 'next_text' argument. * * If the 'show_all' argument is set to true, then it will show all of the pages * instead of a short list of the pages near the current page. By default, the * 'show_all' is set to false and controlled by the 'end_size' and 'mid_size' * arguments. The 'end_size' argument is how many numbers on either the start * and the end list edges, by default is 1. The 'mid_size' argument is how many * numbers to either side of current page, but not including current page. * * It is possible to add query vars to the link by using the 'add_args' argument * and see add_query_arg() for more information. * * The 'before_page_number' and 'after_page_number' arguments allow users to * augment the links themselves. Typically this might be to add context to the * numbered links so that screen reader users understand what the links are for. * The text strings are added before and after the page number - within the * anchor tag. * * @since 2.1.0 * @since 4.9.0 Added the `aria_current` argument. * * @global WP_Query $wp_query WordPress Query object. * @global WP_Rewrite $wp_rewrite WordPress rewrite component. * * @param string|array $args { * Optional. Array or string of arguments for generating paginated links for archives. * * @type string $base Base of the paginated url. Default empty. * @type string $format Format for the pagination structure. Default empty. * @type int $total The total amount of pages. Default is the value WP_Query's * `max_num_pages` or 1. * @type int $current The current page number. Default is 'paged' query var or 1. * @type string $aria_current The value for the aria-current attribute. Possible values are 'page', * 'step', 'location', 'date', 'time', 'true', 'false'. Default is 'page'. * @type bool $show_all Whether to show all pages. Default false. * @type int $end_size How many numbers on either the start and the end list edges. * Default 1. * @type int $mid_size How many numbers to either side of the current pages. Default 2. * @type bool $prev_next Whether to include the previous and next links in the list. Default true. * @type string $prev_text The previous page text. Default '« Previous'. * @type string $next_text The next page text. Default 'Next »'. * @type string $type Controls format of the returned value. Possible values are 'plain', * 'array' and 'list'. Default is 'plain'. * @type array $add_args An array of query args to add. Default false. * @type string $add_fragment A string to append to each link. Default empty. * @type string $before_page_number A string to appear before the page number. Default empty. * @type string $after_page_number A string to append after the page number. Default empty. * } * @return string|string[]|void String of page links or array of page links, depending on 'type' argument. * Void if total number of pages is less than 2. */ function paginate_links( $args = '' ) { global $wp_query, $wp_rewrite; // Setting up default values based on the current URL. $pagenum_link = html_entity_decode( get_pagenum_link() ); $url_parts = explode( '?', $pagenum_link ); // Get max pages and current page out of the current query, if available. $total = isset( $wp_query->max_num_pages ) ? $wp_query->max_num_pages : 1; $current = get_query_var( 'paged' ) ? (int) get_query_var( 'paged' ) : 1; // Append the format placeholder to the base URL. $pagenum_link = trailingslashit( $url_parts[0] ) . '%_%'; // URL base depends on permalink settings. $format = $wp_rewrite->using_index_permalinks() && ! strpos( $pagenum_link, 'index.php' ) ? 'index.php/' : ''; $format .= $wp_rewrite->using_permalinks() ? user_trailingslashit( $wp_rewrite->pagination_base . '/%#%', 'paged' ) : '?paged=%#%'; $defaults = array( 'base' => $pagenum_link, // http://example.com/all_posts.php%_% : %_% is replaced by format (below). 'format' => $format, // ?page=%#% : %#% is replaced by the page number. 'total' => $total, 'current' => $current, 'aria_current' => 'page', 'show_all' => false, 'prev_next' => true, 'prev_text' => __( '« Previous' ), 'next_text' => __( 'Next »' ), 'end_size' => 1, 'mid_size' => 2, 'type' => 'plain', 'add_args' => array(), // Array of query args to add. 'add_fragment' => '', 'before_page_number' => '', 'after_page_number' => '', ); $args = wp_parse_args( $args, $defaults ); if ( ! is_array( $args['add_args'] ) ) { $args['add_args'] = array(); } // Merge additional query vars found in the original URL into 'add_args' array. if ( isset( $url_parts[1] ) ) { // Find the format argument. $format = explode( '?', str_replace( '%_%', $args['format'], $args['base'] ) ); $format_query = isset( $format[1] ) ? $format[1] : ''; wp_parse_str( $format_query, $format_args ); // Find the query args of the requested URL. wp_parse_str( $url_parts[1], $url_query_args ); // Remove the format argument from the array of query arguments, to avoid overwriting custom format. foreach ( $format_args as $format_arg => $format_arg_value ) { unset( $url_query_args[ $format_arg ] ); } $args['add_args'] = array_merge( $args['add_args'], urlencode_deep( $url_query_args ) ); } // Who knows what else people pass in $args. $total = (int) $args['total']; if ( $total < 2 ) { return; } $current = (int) $args['current']; $end_size = (int) $args['end_size']; // Out of bounds? Make it the default. if ( $end_size < 1 ) { $end_size = 1; } $mid_size = (int) $args['mid_size']; if ( $mid_size < 0 ) { $mid_size = 2; } $add_args = $args['add_args']; $r = ''; $page_links = array(); $dots = false; if ( $args['prev_next'] && $current && 1 < $current ) : $link = str_replace( '%_%', 2 == $current ? '' : $args['format'], $args['base'] ); $link = str_replace( '%#%', $current - 1, $link ); if ( $add_args ) { $link = add_query_arg( $add_args, $link ); } $link .= $args['add_fragment']; $page_links[] = sprintf( '', /** * Filters the paginated links for the given archive pages. * * @since 3.0.0 * * @param string $link The paginated link URL. */ esc_url( apply_filters( 'paginate_links', $link ) ), $args['prev_text'] ); endif; for ( $n = 1; $n <= $total; $n++ ) : if ( $n == $current ) : $page_links[] = sprintf( '%s', esc_attr( $args['aria_current'] ), $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number'] ); $dots = true; else : if ( $args['show_all'] || ( $n <= $end_size || ( $current && $n >= $current - $mid_size && $n <= $current + $mid_size ) || $n > $total - $end_size ) ) : $link = str_replace( '%_%', 1 == $n ? '' : $args['format'], $args['base'] ); $link = str_replace( '%#%', $n, $link ); if ( $add_args ) { $link = add_query_arg( $add_args, $link ); } $link .= $args['add_fragment']; $page_links[] = sprintf( '%s', /** This filter is documented in wp-includes/general-template.php */ esc_url( apply_filters( 'paginate_links', $link ) ), $args['before_page_number'] . number_format_i18n( $n ) . $args['after_page_number'] ); $dots = true; elseif ( $dots && ! $args['show_all'] ) : $page_links[] = '' . __( '…' ) . ''; $dots = false; endif; endif; endfor; if ( $args['prev_next'] && $current && $current < $total ) : $link = str_replace( '%_%', $args['format'], $args['base'] ); $link = str_replace( '%#%', $current + 1, $link ); if ( $add_args ) { $link = add_query_arg( $add_args, $link ); } $link .= $args['add_fragment']; $page_links[] = sprintf( '', /** This filter is documented in wp-includes/general-template.php */ esc_url( apply_filters( 'paginate_links', $link ) ), $args['next_text'] ); endif; switch ( $args['type'] ) { case 'array': return $page_links; case 'list': $r .= "\n"; break; default: $r = implode( "\n", $page_links ); break; } /** * Filters the HTML output of paginated links for archives. * * @since 5.7.0 * * @param string $r HTML output. * @param array $args An array of arguments. See paginate_links() * for information on accepted arguments. */ $r = apply_filters( 'paginate_links_output', $r, $args ); return $r; } /** * Registers an admin color scheme css file. * * Allows a plugin to register a new admin color scheme. For example: * * wp_admin_css_color( 'classic', __( 'Classic' ), admin_url( "css/colors-classic.css" ), array( * '#07273E', '#14568A', '#D54E21', '#2683AE' * ) ); * * @since 2.5.0 * * @global array $_wp_admin_css_colors * * @param string $key The unique key for this theme. * @param string $name The name of the theme. * @param string $url The URL of the CSS file containing the color scheme. * @param array $colors Optional. An array of CSS color definition strings which are used * to give the user a feel for the theme. * @param array $icons { * Optional. CSS color definitions used to color any SVG icons. * * @type string $base SVG icon base color. * @type string $focus SVG icon color on focus. * @type string $current SVG icon color of current admin menu link. * } */ function wp_admin_css_color( $key, $name, $url, $colors = array(), $icons = array() ) { global $_wp_admin_css_colors; if ( ! isset( $_wp_admin_css_colors ) ) { $_wp_admin_css_colors = array(); } $_wp_admin_css_colors[ $key ] = (object) array( 'name' => $name, 'url' => $url, 'colors' => $colors, 'icon_colors' => $icons, ); } /** * Registers the default admin color schemes. * * Registers the initial set of eight color schemes in the Profile section * of the dashboard which allows for styling the admin menu and toolbar. * * @see wp_admin_css_color() * * @since 3.0.0 */ function register_admin_color_schemes() { $suffix = is_rtl() ? '-rtl' : ''; $suffix .= SCRIPT_DEBUG ? '' : '.min'; wp_admin_css_color( 'fresh', _x( 'Default', 'admin color scheme' ), false, array( '#1d2327', '#2c3338', '#2271b1', '#72aee6' ), array( 'base' => '#a7aaad', 'focus' => '#72aee6', 'current' => '#fff', ) ); wp_admin_css_color( 'light', _x( 'Light', 'admin color scheme' ), admin_url( "css/colors/light/colors$suffix.css" ), array( '#e5e5e5', '#999', '#d64e07', '#04a4cc' ), array( 'base' => '#999', 'focus' => '#ccc', 'current' => '#ccc', ) ); wp_admin_css_color( 'modern', _x( 'Modern', 'admin color scheme' ), admin_url( "css/colors/modern/colors$suffix.css" ), array( '#1e1e1e', '#3858e9', '#33f078' ), array( 'base' => '#f3f1f1', 'focus' => '#fff', 'current' => '#fff', ) ); wp_admin_css_color( 'blue', _x( 'Blue', 'admin color scheme' ), admin_url( "css/colors/blue/colors$suffix.css" ), array( '#096484', '#4796b3', '#52accc', '#74B6CE' ), array( 'base' => '#e5f8ff', 'focus' => '#fff', 'current' => '#fff', ) ); wp_admin_css_color( 'midnight', _x( 'Midnight', 'admin color scheme' ), admin_url( "css/colors/midnight/colors$suffix.css" ), array( '#25282b', '#363b3f', '#69a8bb', '#e14d43' ), array( 'base' => '#f1f2f3', 'focus' => '#fff', 'current' => '#fff', ) ); wp_admin_css_color( 'sunrise', _x( 'Sunrise', 'admin color scheme' ), admin_url( "css/colors/sunrise/colors$suffix.css" ), array( '#b43c38', '#cf4944', '#dd823b', '#ccaf0b' ), array( 'base' => '#f3f1f1', 'focus' => '#fff', 'current' => '#fff', ) ); wp_admin_css_color( 'ectoplasm', _x( 'Ectoplasm', 'admin color scheme' ), admin_url( "css/colors/ectoplasm/colors$suffix.css" ), array( '#413256', '#523f6d', '#a3b745', '#d46f15' ), array( 'base' => '#ece6f6', 'focus' => '#fff', 'current' => '#fff', ) ); wp_admin_css_color( 'ocean', _x( 'Ocean', 'admin color scheme' ), admin_url( "css/colors/ocean/colors$suffix.css" ), array( '#627c83', '#738e96', '#9ebaa0', '#aa9d88' ), array( 'base' => '#f2fcff', 'focus' => '#fff', 'current' => '#fff', ) ); wp_admin_css_color( 'coffee', _x( 'Coffee', 'admin color scheme' ), admin_url( "css/colors/coffee/colors$suffix.css" ), array( '#46403c', '#59524c', '#c7a589', '#9ea476' ), array( 'base' => '#f3f2f1', 'focus' => '#fff', 'current' => '#fff', ) ); } /** * Displays the URL of a WordPress admin CSS file. * * @see WP_Styles::_css_href() and its {@see 'style_loader_src'} filter. * * @since 2.3.0 * * @param string $file file relative to wp-admin/ without its ".css" extension. * @return string */ function wp_admin_css_uri( $file = 'wp-admin' ) { if ( defined( 'WP_INSTALLING' ) ) { $_file = "./$file.css"; } else { $_file = admin_url( "$file.css" ); } $_file = add_query_arg( 'version', get_bloginfo( 'version' ), $_file ); /** * Filters the URI of a WordPress admin CSS file. * * @since 2.3.0 * * @param string $_file Relative path to the file with query arguments attached. * @param string $file Relative path to the file, minus its ".css" extension. */ return apply_filters( 'wp_admin_css_uri', $_file, $file ); } /** * Enqueues or directly prints a stylesheet link to the specified CSS file. * * "Intelligently" decides to enqueue or to print the CSS file. If the * {@see 'wp_print_styles'} action has *not* yet been called, the CSS file will be * enqueued. If the {@see 'wp_print_styles'} action has been called, the CSS link will * be printed. Printing may be forced by passing true as the $force_echo * (second) parameter. * * For backward compatibility with WordPress 2.3 calling method: If the $file * (first) parameter does not correspond to a registered CSS file, we assume * $file is a file relative to wp-admin/ without its ".css" extension. A * stylesheet link to that generated URL is printed. * * @since 2.3.0 * * @param string $file Optional. Style handle name or file name (without ".css" extension) relative * to wp-admin/. Defaults to 'wp-admin'. * @param bool $force_echo Optional. Force the stylesheet link to be printed rather than enqueued. */ function wp_admin_css( $file = 'wp-admin', $force_echo = false ) { // For backward compatibility. $handle = str_starts_with( $file, 'css/' ) ? substr( $file, 4 ) : $file; if ( wp_styles()->query( $handle ) ) { if ( $force_echo || did_action( 'wp_print_styles' ) ) { // We already printed the style queue. Print this one immediately. wp_print_styles( $handle ); } else { // Add to style queue. wp_enqueue_style( $handle ); } return; } $stylesheet_link = sprintf( "\n", esc_url( wp_admin_css_uri( $file ) ) ); /** * Filters the stylesheet link to the specified CSS file. * * If the site is set to display right-to-left, the RTL stylesheet link * will be used instead. * * @since 2.3.0 * @param string $stylesheet_link HTML link element for the stylesheet. * @param string $file Style handle name or filename (without ".css" extension) * relative to wp-admin/. Defaults to 'wp-admin'. */ echo apply_filters( 'wp_admin_css', $stylesheet_link, $file ); if ( function_exists( 'is_rtl' ) && is_rtl() ) { $rtl_stylesheet_link = sprintf( "\n", esc_url( wp_admin_css_uri( "$file-rtl" ) ) ); /** This filter is documented in wp-includes/general-template.php */ echo apply_filters( 'wp_admin_css', $rtl_stylesheet_link, "$file-rtl" ); } } /** * Enqueues the default ThickBox js and css. * * If any of the settings need to be changed, this can be done with another js * file similar to media-upload.js. That file should * require array('thickbox') to ensure it is loaded after. * * @since 2.5.0 */ function add_thickbox() { wp_enqueue_script( 'thickbox' ); wp_enqueue_style( 'thickbox' ); if ( is_network_admin() ) { add_action( 'admin_head', '_thickbox_path_admin_subfolder' ); } } /** * Displays the XHTML generator that is generated on the wp_head hook. * * See {@see 'wp_head'}. * * @since 2.5.0 */ function wp_generator() { /** * Filters the output of the XHTML generator tag. * * @since 2.5.0 * * @param string $generator_type The XHTML generator. */ the_generator( apply_filters( 'wp_generator_type', 'xhtml' ) ); } /** * Displays the generator XML or Comment for RSS, ATOM, etc. * * Returns the correct generator type for the requested output format. Allows * for a plugin to filter generators overall the {@see 'the_generator'} filter. * * @since 2.5.0 * * @param string $type The type of generator to output - (html|xhtml|atom|rss2|rdf|comment|export). */ function the_generator( $type ) { /** * Filters the output of the XHTML generator tag for display. * * @since 2.5.0 * * @param string $generator_type The generator output. * @param string $type The type of generator to output. Accepts 'html', * 'xhtml', 'atom', 'rss2', 'rdf', 'comment', 'export'. */ echo apply_filters( 'the_generator', get_the_generator( $type ), $type ) . "\n"; } /** * Creates the generator XML or Comment for RSS, ATOM, etc. * * Returns the correct generator type for the requested output format. Allows * for a plugin to filter generators on an individual basis using the * {@see 'get_the_generator_$type'} filter. * * @since 2.5.0 * * @param string $type The type of generator to return - (html|xhtml|atom|rss2|rdf|comment|export). * @return string|void The HTML content for the generator. */ function get_the_generator( $type = '' ) { if ( empty( $type ) ) { $current_filter = current_filter(); if ( empty( $current_filter ) ) { return; } switch ( $current_filter ) { case 'rss2_head': case 'commentsrss2_head': $type = 'rss2'; break; case 'rss_head': case 'opml_head': $type = 'comment'; break; case 'rdf_header': $type = 'rdf'; break; case 'atom_head': case 'comments_atom_head': case 'app_head': $type = 'atom'; break; } } switch ( $type ) { case 'html': $gen = ''; break; case 'xhtml': $gen = ''; break; case 'atom': $gen = 'WordPress'; break; case 'rss2': $gen = '' . sanitize_url( 'https://wordpress.org/?v=' . get_bloginfo_rss( 'version' ) ) . ''; break; case 'rdf': $gen = ''; break; case 'comment': $gen = ''; break; case 'export': $gen = ''; break; } /** * Filters the HTML for the retrieved generator type. * * The dynamic portion of the hook name, `$type`, refers to the generator type. * * Possible hook names include: * * - `get_the_generator_atom` * - `get_the_generator_comment` * - `get_the_generator_export` * - `get_the_generator_html` * - `get_the_generator_rdf` * - `get_the_generator_rss2` * - `get_the_generator_xhtml` * * @since 2.5.0 * * @param string $gen The HTML markup output to wp_head(). * @param string $type The type of generator. Accepts 'html', 'xhtml', 'atom', * 'rss2', 'rdf', 'comment', 'export'. */ return apply_filters( "get_the_generator_{$type}", $gen, $type ); } /** * Outputs the HTML checked attribute. * * Compares the first two arguments and if identical marks as checked. * * @since 1.0.0 * * @param mixed $checked One of the values to compare. * @param mixed $current Optional. The other value to compare if not just true. * Default true. * @param bool $display Optional. Whether to echo or just return the string. * Default true. * @return string HTML attribute or empty string. */ function checked( $checked, $current = true, $display = true ) { return __checked_selected_helper( $checked, $current, $display, 'checked' ); } /** * Outputs the HTML selected attribute. * * Compares the first two arguments and if identical marks as selected. * * @since 1.0.0 * * @param mixed $selected One of the values to compare. * @param mixed $current Optional. The other value to compare if not just true. * Default true. * @param bool $display Optional. Whether to echo or just return the string. * Default true. * @return string HTML attribute or empty string. */ function selected( $selected, $current = true, $display = true ) { return __checked_selected_helper( $selected, $current, $display, 'selected' ); } /** * Outputs the HTML disabled attribute. * * Compares the first two arguments and if identical marks as disabled. * * @since 3.0.0 * * @param mixed $disabled One of the values to compare. * @param mixed $current Optional. The other value to compare if not just true. * Default true. * @param bool $display Optional. Whether to echo or just return the string. * Default true. * @return string HTML attribute or empty string. */ function disabled( $disabled, $current = true, $display = true ) { return __checked_selected_helper( $disabled, $current, $display, 'disabled' ); } /** * Outputs the HTML readonly attribute. * * Compares the first two arguments and if identical marks as readonly. * * @since 5.9.0 * * @param mixed $readonly_value One of the values to compare. * @param mixed $current Optional. The other value to compare if not just true. * Default true. * @param bool $display Optional. Whether to echo or just return the string. * Default true. * @return string HTML attribute or empty string. */ function wp_readonly( $readonly_value, $current = true, $display = true ) { return __checked_selected_helper( $readonly_value, $current, $display, 'readonly' ); } /* * Include a compat `readonly()` function on PHP < 8.1. Since PHP 8.1, * `readonly` is a reserved keyword and cannot be used as a function name. * In order to avoid PHP parser errors, this function was extracted * to a separate file and is only included conditionally on PHP < 8.1. */ if ( PHP_VERSION_ID < 80100 ) { require_once __DIR__ . '/php-compat/readonly.php'; } /** * Private helper function for checked, selected, disabled and readonly. * * Compares the first two arguments and if identical marks as `$type`. * * @since 2.8.0 * @access private * * @param mixed $helper One of the values to compare. * @param mixed $current The other value to compare if not just true. * @param bool $display Whether to echo or just return the string. * @param string $type The type of checked|selected|disabled|readonly we are doing. * @return string HTML attribute or empty string. */ function __checked_selected_helper( $helper, $current, $display, $type ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore if ( (string) $helper === (string) $current ) { $result = " $type='$type'"; } else { $result = ''; } if ( $display ) { echo $result; } return $result; } /** * Assigns a visual indicator for required form fields. * * @since 6.1.0 * * @return string Indicator glyph wrapped in a `span` tag. */ function wp_required_field_indicator() { /* translators: Character to identify required form fields. */ $glyph = __( '*' ); $indicator = '' . esc_html( $glyph ) . ''; /** * Filters the markup for a visual indicator of required form fields. * * @since 6.1.0 * * @param string $indicator Markup for the indicator element. */ return apply_filters( 'wp_required_field_indicator', $indicator ); } /** * Creates a message to explain required form fields. * * @since 6.1.0 * * @return string Message text and glyph wrapped in a `span` tag. */ function wp_required_field_message() { $message = sprintf( '%s', /* translators: %s: Asterisk symbol (*). */ sprintf( __( 'Required fields are marked %s' ), wp_required_field_indicator() ) ); /** * Filters the message to explain required form fields. * * @since 6.1.0 * * @param string $message Message text and glyph wrapped in a `span` tag. */ return apply_filters( 'wp_required_field_message', $message ); } /** * Default settings for heartbeat. * * Outputs the nonce used in the heartbeat XHR. * * @since 3.6.0 * * @param array $settings * @return array Heartbeat settings. */ function wp_heartbeat_settings( $settings ) { if ( ! is_admin() ) { $settings['ajaxurl'] = admin_url( 'admin-ajax.php', 'relative' ); } if ( is_user_logged_in() ) { $settings['nonce'] = wp_create_nonce( 'heartbeat-nonce' ); } return $settings; } property * of `WP_Block_Type`. See WP_Block_Type::__construct() for information * on accepted arguments. Default empty array. * @return WP_Block_Type|false The registered block type on success, or false on failure. */ function register_block_type_from_metadata( $file_or_folder, $args = array() ) { /* * Get an array of metadata from a PHP file. * This improves performance for core blocks as it's only necessary to read a single PHP file * instead of reading a JSON file per-block, and then decoding from JSON to PHP. * Using a static variable ensures that the metadata is only read once per request. */ static $core_blocks_meta; if ( ! $core_blocks_meta ) { $core_blocks_meta = require ABSPATH . WPINC . '/blocks/blocks-json.php'; } $metadata_file = ( ! str_ends_with( $file_or_folder, 'block.json' ) ) ? trailingslashit( $file_or_folder ) . 'block.json' : $file_or_folder; $is_core_block = str_starts_with( $file_or_folder, ABSPATH . WPINC ); if ( ! $is_core_block && ! file_exists( $metadata_file ) ) { return false; } // Try to get metadata from the static cache for core blocks. $metadata = false; if ( $is_core_block ) { $core_block_name = str_replace( ABSPATH . WPINC . '/blocks/', '', $file_or_folder ); if ( ! empty( $core_blocks_meta[ $core_block_name ] ) ) { $metadata = $core_blocks_meta[ $core_block_name ]; } } // If metadata is not found in the static cache, read it from the file. if ( ! $metadata ) { $metadata = wp_json_file_decode( $metadata_file, array( 'associative' => true ) ); } if ( ! is_array( $metadata ) || empty( $metadata['name'] ) ) { return false; } $metadata['file'] = wp_normalize_path( realpath( $metadata_file ) ); /** * Filters the metadata provided for registering a block type. * * @since 5.7.0 * * @param array $metadata Metadata for registering a block type. */ $metadata = apply_filters( 'block_type_metadata', $metadata ); // Add `style` and `editor_style` for core blocks if missing. if ( ! empty( $metadata['name'] ) && str_starts_with( $metadata['name'], 'core/' ) ) { $block_name = str_replace( 'core/', '', $metadata['name'] ); if ( ! isset( $metadata['style'] ) ) { $metadata['style'] = "wp-block-$block_name"; } if ( current_theme_supports( 'wp-block-styles' ) && wp_should_load_separate_core_block_assets() ) { $metadata['style'] = (array) $metadata['style']; $metadata['style'][] = "wp-block-{$block_name}-theme"; } if ( ! isset( $metadata['editorStyle'] ) ) { $metadata['editorStyle'] = "wp-block-{$block_name}-editor"; } } $settings = array(); $property_mappings = array( 'apiVersion' => 'api_version', 'title' => 'title', 'category' => 'category', 'parent' => 'parent', 'ancestor' => 'ancestor', 'icon' => 'icon', 'description' => 'description', 'keywords' => 'keywords', 'attributes' => 'attributes', 'providesContext' => 'provides_context', 'usesContext' => 'uses_context', 'selectors' => 'selectors', 'supports' => 'supports', 'styles' => 'styles', 'variations' => 'variations', 'example' => 'example', ); $textdomain = ! empty( $metadata['textdomain'] ) ? $metadata['textdomain'] : null; $i18n_schema = get_block_metadata_i18n_schema(); foreach ( $property_mappings as $key => $mapped_key ) { if ( isset( $metadata[ $key ] ) ) { $settings[ $mapped_key ] = $metadata[ $key ]; if ( $textdomain && isset( $i18n_schema->$key ) ) { $settings[ $mapped_key ] = translate_settings_using_i18n_schema( $i18n_schema->$key, $settings[ $key ], $textdomain ); } } } $script_fields = array( 'editorScript' => 'editor_script_handles', 'script' => 'script_handles', 'viewScript' => 'view_script_handles', ); foreach ( $script_fields as $metadata_field_name => $settings_field_name ) { if ( ! empty( $metadata[ $metadata_field_name ] ) ) { $scripts = $metadata[ $metadata_field_name ]; $processed_scripts = array(); if ( is_array( $scripts ) ) { for ( $index = 0; $index < count( $scripts ); $index++ ) { $result = register_block_script_handle( $metadata, $metadata_field_name, $index ); if ( $result ) { $processed_scripts[] = $result; } } } else { $result = register_block_script_handle( $metadata, $metadata_field_name ); if ( $result ) { $processed_scripts[] = $result; } } $settings[ $settings_field_name ] = $processed_scripts; } } $style_fields = array( 'editorStyle' => 'editor_style_handles', 'style' => 'style_handles', ); foreach ( $style_fields as $metadata_field_name => $settings_field_name ) { if ( ! empty( $metadata[ $metadata_field_name ] ) ) { $styles = $metadata[ $metadata_field_name ]; $processed_styles = array(); if ( is_array( $styles ) ) { for ( $index = 0; $index < count( $styles ); $index++ ) { $result = register_block_style_handle( $metadata, $metadata_field_name, $index ); if ( $result ) { $processed_styles[] = $result; } } } else { $result = register_block_style_handle( $metadata, $metadata_field_name ); if ( $result ) { $processed_styles[] = $result; } } $settings[ $settings_field_name ] = $processed_styles; } } if ( ! empty( $metadata['render'] ) ) { $template_path = wp_normalize_path( realpath( dirname( $metadata['file'] ) . '/' . remove_block_asset_path_prefix( $metadata['render'] ) ) ); if ( $template_path ) { /** * Renders the block on the server. * * @since 6.1.0 * * @param array $attributes Block attributes. * @param string $content Block default content. * @param WP_Block $block Block instance. * * @return string Returns the block content. */ $settings['render_callback'] = static function( $attributes, $content, $block ) use ( $template_path ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable ob_start(); require $template_path; return ob_get_clean(); }; } } /** * Filters the settings determined from the block type metadata. * * @since 5.7.0 * * @param array $settings Array of determined settings for registering a block type. * @param array $metadata Metadata provided for registering a block type. */ $settings = apply_filters( 'block_type_metadata_settings', array_merge( $settings, $args ), $metadata ); return WP_Block_Type_Registry::get_instance()->register( $metadata['name'], $settings ); } /** * Registers a block type. The recommended way is to register a block type using * the metadata stored in the `block.json` file. * * @since 5.0.0 * @since 5.8.0 First parameter now accepts a path to the `block.json` file. * * @param string|WP_Block_Type $block_type Block type name including namespace, or alternatively * a path to the JSON file with metadata definition for the block, * or a path to the folder where the `block.json` file is located, * or a complete WP_Block_Type instance. * In case a WP_Block_Type is provided, the $args parameter will be ignored. * @param array $args Optional. Array of block type arguments. Accepts any public property * of `WP_Block_Type`. See WP_Block_Type::__construct() for information * on accepted arguments. Default empty array. * * @return WP_Block_Type|false The registered block type on success, or false on failure. */ function register_block_type( $block_type, $args = array() ) { if ( is_string( $block_type ) && file_exists( $block_type ) ) { return register_block_type_from_metadata( $block_type, $args ); } return WP_Block_Type_Registry::get_instance()->register( $block_type, $args ); } /** * Unregisters a block type. * * @since 5.0.0 * * @param string|WP_Block_Type $name Block type name including namespace, or alternatively * a complete WP_Block_Type instance. * @return WP_Block_Type|false The unregistered block type on success, or false on failure. */ function unregister_block_type( $name ) { return WP_Block_Type_Registry::get_instance()->unregister( $name ); } /** * Determines whether a post or content string has blocks. * * This test optimizes for performance rather than strict accuracy, detecting * the pattern of a block but not validating its structure. For strict accuracy, * you should use the block parser on post content. * * @since 5.0.0 * * @see parse_blocks() * * @param int|string|WP_Post|null $post Optional. Post content, post ID, or post object. * Defaults to global $post. * @return bool Whether the post has blocks. */ function has_blocks( $post = null ) { if ( ! is_string( $post ) ) { $wp_post = get_post( $post ); if ( ! $wp_post instanceof WP_Post ) { return false; } $post = $wp_post->post_content; } return str_contains( (string) $post, '', $serialized_block_name, $serialized_attributes ); } return sprintf( '%s', $serialized_block_name, $serialized_attributes, $block_content, $serialized_block_name ); } /** * Returns the content of a block, including comment delimiters, serializing all * attributes from the given parsed block. * * This should be used when preparing a block to be saved to post content. * Prefer `render_block` when preparing a block for display. Unlike * `render_block`, this does not evaluate a block's `render_callback`, and will * instead preserve the markup as parsed. * * @since 5.3.1 * * @param array $block A representative array of a single parsed block object. See WP_Block_Parser_Block. * @return string String of rendered HTML. */ function serialize_block( $block ) { $block_content = ''; $index = 0; foreach ( $block['innerContent'] as $chunk ) { $block_content .= is_string( $chunk ) ? $chunk : serialize_block( $block['innerBlocks'][ $index++ ] ); } if ( ! is_array( $block['attrs'] ) ) { $block['attrs'] = array(); } return get_comment_delimited_block_content( $block['blockName'], $block['attrs'], $block_content ); } /** * Returns a joined string of the aggregate serialization of the given * parsed blocks. * * @since 5.3.1 * * @param array[] $blocks An array of representative arrays of parsed block objects. See serialize_block(). * @return string String of rendered HTML. */ function serialize_blocks( $blocks ) { return implode( '', array_map( 'serialize_block', $blocks ) ); } /** * Filters and sanitizes block content to remove non-allowable HTML * from parsed block attribute values. * * @since 5.3.1 * * @param string $text Text that may contain block content. * @param array[]|string $allowed_html Optional. An array of allowed HTML elements and attributes, * or a context name such as 'post'. See wp_kses_allowed_html() * for the list of accepted context names. Default 'post'. * @param string[] $allowed_protocols Optional. Array of allowed URL protocols. * Defaults to the result of wp_allowed_protocols(). * @return string The filtered and sanitized content result. */ function filter_block_content( $text, $allowed_html = 'post', $allowed_protocols = array() ) { $result = ''; if ( str_contains( $text, '' ) ) { $text = preg_replace_callback( '%%', '_filter_block_content_callback', $text ); } $blocks = parse_blocks( $text ); foreach ( $blocks as $block ) { $block = filter_block_kses( $block, $allowed_html, $allowed_protocols ); $result .= serialize_block( $block ); } return $result; } /** * Callback used for regular expression replacement in filter_block_content(). * * @private * @since 6.2.1 * * @param array $matches Array of preg_replace_callback matches. * @return string Replacement string. */ function _filter_block_content_callback( $matches ) { return ''; } /** * Filters and sanitizes a parsed block to remove non-allowable HTML * from block attribute values. * * @since 5.3.1 * * @param WP_Block_Parser_Block $block The parsed block object. * @param array[]|string $allowed_html An array of allowed HTML elements and attributes, * or a context name such as 'post'. See wp_kses_allowed_html() * for the list of accepted context names. * @param string[] $allowed_protocols Optional. Array of allowed URL protocols. * Defaults to the result of wp_allowed_protocols(). * @return array The filtered and sanitized block object result. */ function filter_block_kses( $block, $allowed_html, $allowed_protocols = array() ) { $block['attrs'] = filter_block_kses_value( $block['attrs'], $allowed_html, $allowed_protocols ); if ( is_array( $block['innerBlocks'] ) ) { foreach ( $block['innerBlocks'] as $i => $inner_block ) { $block['innerBlocks'][ $i ] = filter_block_kses( $inner_block, $allowed_html, $allowed_protocols ); } } return $block; } /** * Filters and sanitizes a parsed block attribute value to remove * non-allowable HTML. * * @since 5.3.1 * * @param string[]|string $value The attribute value to filter. * @param array[]|string $allowed_html An array of allowed HTML elements and attributes, * or a context name such as 'post'. See wp_kses_allowed_html() * for the list of accepted context names. * @param string[] $allowed_protocols Optional. Array of allowed URL protocols. * Defaults to the result of wp_allowed_protocols(). * @return string[]|string The filtered and sanitized result. */ function filter_block_kses_value( $value, $allowed_html, $allowed_protocols = array() ) { if ( is_array( $value ) ) { foreach ( $value as $key => $inner_value ) { $filtered_key = filter_block_kses_value( $key, $allowed_html, $allowed_protocols ); $filtered_value = filter_block_kses_value( $inner_value, $allowed_html, $allowed_protocols ); if ( $filtered_key !== $key ) { unset( $value[ $key ] ); } $value[ $filtered_key ] = $filtered_value; } } elseif ( is_string( $value ) ) { return wp_kses( $value, $allowed_html, $allowed_protocols ); } return $value; } /** * Parses blocks out of a content string, and renders those appropriate for the excerpt. * * As the excerpt should be a small string of text relevant to the full post content, * this function renders the blocks that are most likely to contain such text. * * @since 5.0.0 * * @param string $content The content to parse. * @return string The parsed and filtered content. */ function excerpt_remove_blocks( $content ) { $allowed_inner_blocks = array( // Classic blocks have their blockName set to null. null, 'core/freeform', 'core/heading', 'core/html', 'core/list', 'core/media-text', 'core/paragraph', 'core/preformatted', 'core/pullquote', 'core/quote', 'core/table', 'core/verse', ); $allowed_wrapper_blocks = array( 'core/columns', 'core/column', 'core/group', ); /** * Filters the list of blocks that can be used as wrapper blocks, allowing * excerpts to be generated from the `innerBlocks` of these wrappers. * * @since 5.8.0 * * @param string[] $allowed_wrapper_blocks The list of names of allowed wrapper blocks. */ $allowed_wrapper_blocks = apply_filters( 'excerpt_allowed_wrapper_blocks', $allowed_wrapper_blocks ); $allowed_blocks = array_merge( $allowed_inner_blocks, $allowed_wrapper_blocks ); /** * Filters the list of blocks that can contribute to the excerpt. * * If a dynamic block is added to this list, it must not generate another * excerpt, as this will cause an infinite loop to occur. * * @since 5.0.0 * * @param string[] $allowed_blocks The list of names of allowed blocks. */ $allowed_blocks = apply_filters( 'excerpt_allowed_blocks', $allowed_blocks ); $blocks = parse_blocks( $content ); $output = ''; foreach ( $blocks as $block ) { if ( in_array( $block['blockName'], $allowed_blocks, true ) ) { if ( ! empty( $block['innerBlocks'] ) ) { if ( in_array( $block['blockName'], $allowed_wrapper_blocks, true ) ) { $output .= _excerpt_render_inner_blocks( $block, $allowed_blocks ); continue; } // Skip the block if it has disallowed or nested inner blocks. foreach ( $block['innerBlocks'] as $inner_block ) { if ( ! in_array( $inner_block['blockName'], $allowed_inner_blocks, true ) || ! empty( $inner_block['innerBlocks'] ) ) { continue 2; } } } $output .= render_block( $block ); } } return $output; } /** * Parses footnotes markup out of a content string, * and renders those appropriate for the excerpt. * * @since 6.3.0 * * @param string $content The content to parse. * @return string The parsed and filtered content. */ function excerpt_remove_footnotes( $content ) { if ( ! str_contains( $content, 'data-fn=' ) ) { return $content; } return preg_replace( '_\s*\d+\s*_', '', $content ); } /** * Renders inner blocks from the allowed wrapper blocks * for generating an excerpt. * * @since 5.8.0 * @access private * * @param array $parsed_block The parsed block. * @param array $allowed_blocks The list of allowed inner blocks. * @return string The rendered inner blocks. */ function _excerpt_render_inner_blocks( $parsed_block, $allowed_blocks ) { $output = ''; foreach ( $parsed_block['innerBlocks'] as $inner_block ) { if ( ! in_array( $inner_block['blockName'], $allowed_blocks, true ) ) { continue; } if ( empty( $inner_block['innerBlocks'] ) ) { $output .= render_block( $inner_block ); } else { $output .= _excerpt_render_inner_blocks( $inner_block, $allowed_blocks ); } } return $output; } /** * Renders a single block into a HTML string. * * @since 5.0.0 * * @global WP_Post $post The post to edit. * * @param array $parsed_block A single parsed block object. * @return string String of rendered HTML. */ function render_block( $parsed_block ) { global $post; $parent_block = null; /** * Allows render_block() to be short-circuited, by returning a non-null value. * * @since 5.1.0 * @since 5.9.0 The `$parent_block` parameter was added. * * @param string|null $pre_render The pre-rendered content. Default null. * @param array $parsed_block The block being rendered. * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block. */ $pre_render = apply_filters( 'pre_render_block', null, $parsed_block, $parent_block ); if ( ! is_null( $pre_render ) ) { return $pre_render; } $source_block = $parsed_block; /** * Filters the block being rendered in render_block(), before it's processed. * * @since 5.1.0 * @since 5.9.0 The `$parent_block` parameter was added. * * @param array $parsed_block The block being rendered. * @param array $source_block An un-modified copy of $parsed_block, as it appeared in the source content. * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block. */ $parsed_block = apply_filters( 'render_block_data', $parsed_block, $source_block, $parent_block ); $context = array(); if ( $post instanceof WP_Post ) { $context['postId'] = $post->ID; /* * The `postType` context is largely unnecessary server-side, since the ID * is usually sufficient on its own. That being said, since a block's * manifest is expected to be shared between the server and the client, * it should be included to consistently fulfill the expectation. */ $context['postType'] = $post->post_type; } /** * Filters the default context provided to a rendered block. * * @since 5.5.0 * @since 5.9.0 The `$parent_block` parameter was added. * * @param array $context Default context. * @param array $parsed_block Block being rendered, filtered by `render_block_data`. * @param WP_Block|null $parent_block If this is a nested block, a reference to the parent block. */ $context = apply_filters( 'render_block_context', $context, $parsed_block, $parent_block ); $block = new WP_Block( $parsed_block, $context ); return $block->render(); } /** * Parses blocks out of a content string. * * @since 5.0.0 * * @param string $content Post content. * @return array[] Array of parsed block objects. */ function parse_blocks( $content ) { /** * Filter to allow plugins to replace the server-side block parser. * * @since 5.0.0 * * @param string $parser_class Name of block parser class. */ $parser_class = apply_filters( 'block_parser_class', 'WP_Block_Parser' ); $parser = new $parser_class(); return $parser->parse( $content ); } /** * Parses dynamic blocks out of `post_content` and re-renders them. * * @since 5.0.0 * * @param string $content Post content. * @return string Updated post content. */ function do_blocks( $content ) { $blocks = parse_blocks( $content ); $output = ''; foreach ( $blocks as $block ) { $output .= render_block( $block ); } // If there are blocks in this content, we shouldn't run wpautop() on it later. $priority = has_filter( 'the_content', 'wpautop' ); if ( false !== $priority && doing_filter( 'the_content' ) && has_blocks( $content ) ) { remove_filter( 'the_content', 'wpautop', $priority ); add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 ); } return $output; } /** * If do_blocks() needs to remove wpautop() from the `the_content` filter, this re-adds it afterwards, * for subsequent `the_content` usage. * * @since 5.0.0 * @access private * * @param string $content The post content running through this filter. * @return string The unmodified content. */ function _restore_wpautop_hook( $content ) { $current_priority = has_filter( 'the_content', '_restore_wpautop_hook' ); add_filter( 'the_content', 'wpautop', $current_priority - 1 ); remove_filter( 'the_content', '_restore_wpautop_hook', $current_priority ); return $content; } /** * Returns the current version of the block format that the content string is using. * * If the string doesn't contain blocks, it returns 0. * * @since 5.0.0 * * @param string $content Content to test. * @return int The block format version is 1 if the content contains one or more blocks, 0 otherwise. */ function block_version( $content ) { return has_blocks( $content ) ? 1 : 0; } /** * Registers a new block style. * * @since 5.3.0 * * @link https://developer.wordpress.org/block-editor/reference-guides/block-api/block-styles/ * * @param string $block_name Block type name including namespace. * @param array $style_properties Array containing the properties of the style name, label, * style_handle (name of the stylesheet to be enqueued), * inline_style (string containing the CSS to be added). * @return bool True if the block style was registered with success and false otherwise. */ function register_block_style( $block_name, $style_properties ) { return WP_Block_Styles_Registry::get_instance()->register( $block_name, $style_properties ); } /** * Unregisters a block style. * * @since 5.3.0 * * @param string $block_name Block type name including namespace. * @param string $block_style_name Block style name. * @return bool True if the block style was unregistered with success and false otherwise. */ function unregister_block_style( $block_name, $block_style_name ) { return WP_Block_Styles_Registry::get_instance()->unregister( $block_name, $block_style_name ); } /** * Checks whether the current block type supports the feature requested. * * @since 5.8.0 * * @param WP_Block_Type $block_type Block type to check for support. * @param array $feature Path to a specific feature to check support for. * @param mixed $default_value Optional. Fallback value for feature support. Default false. * @return bool Whether the feature is supported. */ function block_has_support( $block_type, $feature, $default_value = false ) { $block_support = $default_value; if ( $block_type && property_exists( $block_type, 'supports' ) ) { $block_support = _wp_array_get( $block_type->supports, $feature, $default_value ); } return true === $block_support || is_array( $block_support ); } /** * Converts typography keys declared under `supports.*` to `supports.typography.*`. * * Displays a `_doing_it_wrong()` notice when a block using the older format is detected. * * @since 5.8.0 * * @param array $metadata Metadata for registering a block type. * @return array Filtered metadata for registering a block type. */ function wp_migrate_old_typography_shape( $metadata ) { if ( ! isset( $metadata['supports'] ) ) { return $metadata; } $typography_keys = array( '__experimentalFontFamily', '__experimentalFontStyle', '__experimentalFontWeight', '__experimentalLetterSpacing', '__experimentalTextDecoration', '__experimentalTextTransform', 'fontSize', 'lineHeight', ); foreach ( $typography_keys as $typography_key ) { $support_for_key = _wp_array_get( $metadata['supports'], array( $typography_key ), null ); if ( null !== $support_for_key ) { _doing_it_wrong( 'register_block_type_from_metadata()', sprintf( /* translators: 1: Block type, 2: Typography supports key, e.g: fontSize, lineHeight, etc. 3: block.json, 4: Old metadata key, 5: New metadata key. */ __( 'Block "%1$s" is declaring %2$s support in %3$s file under %4$s. %2$s support is now declared under %5$s.' ), $metadata['name'], "$typography_key", 'block.json', "supports.$typography_key", "supports.typography.$typography_key" ), '5.8.0' ); _wp_array_set( $metadata['supports'], array( 'typography', $typography_key ), $support_for_key ); unset( $metadata['supports'][ $typography_key ] ); } } return $metadata; } /** * Helper function that constructs a WP_Query args array from * a `Query` block properties. * * It's used in Query Loop, Query Pagination Numbers and Query Pagination Next blocks. * * @since 5.8.0 * @since 6.1.0 Added `query_loop_block_query_vars` filter and `parents` support in query. * * @param WP_Block $block Block instance. * @param int $page Current query's page. * * @return array Returns the constructed WP_Query arguments. */ function build_query_vars_from_query_block( $block, $page ) { $query = array( 'post_type' => 'post', 'order' => 'DESC', 'orderby' => 'date', 'post__not_in' => array(), ); if ( isset( $block->context['query'] ) ) { if ( ! empty( $block->context['query']['postType'] ) ) { $post_type_param = $block->context['query']['postType']; if ( is_post_type_viewable( $post_type_param ) ) { $query['post_type'] = $post_type_param; } } if ( isset( $block->context['query']['sticky'] ) && ! empty( $block->context['query']['sticky'] ) ) { $sticky = get_option( 'sticky_posts' ); if ( 'only' === $block->context['query']['sticky'] ) { /* * Passing an empty array to post__in will return have_posts() as true (and all posts will be returned). * Logic should be used before hand to determine if WP_Query should be used in the event that the array * being passed to post__in is empty. * * @see https://core.trac.wordpress.org/ticket/28099 */ $query['post__in'] = ! empty( $sticky ) ? $sticky : array( 0 ); $query['ignore_sticky_posts'] = 1; } else { $query['post__not_in'] = array_merge( $query['post__not_in'], $sticky ); } } if ( ! empty( $block->context['query']['exclude'] ) ) { $excluded_post_ids = array_map( 'intval', $block->context['query']['exclude'] ); $excluded_post_ids = array_filter( $excluded_post_ids ); $query['post__not_in'] = array_merge( $query['post__not_in'], $excluded_post_ids ); } if ( isset( $block->context['query']['perPage'] ) && is_numeric( $block->context['query']['perPage'] ) ) { $per_page = absint( $block->context['query']['perPage'] ); $offset = 0; if ( isset( $block->context['query']['offset'] ) && is_numeric( $block->context['query']['offset'] ) ) { $offset = absint( $block->context['query']['offset'] ); } $query['offset'] = ( $per_page * ( $page - 1 ) ) + $offset; $query['posts_per_page'] = $per_page; } // Migrate `categoryIds` and `tagIds` to `tax_query` for backwards compatibility. if ( ! empty( $block->context['query']['categoryIds'] ) || ! empty( $block->context['query']['tagIds'] ) ) { $tax_query = array(); if ( ! empty( $block->context['query']['categoryIds'] ) ) { $tax_query[] = array( 'taxonomy' => 'category', 'terms' => array_filter( array_map( 'intval', $block->context['query']['categoryIds'] ) ), 'include_children' => false, ); } if ( ! empty( $block->context['query']['tagIds'] ) ) { $tax_query[] = array( 'taxonomy' => 'post_tag', 'terms' => array_filter( array_map( 'intval', $block->context['query']['tagIds'] ) ), 'include_children' => false, ); } $query['tax_query'] = $tax_query; } if ( ! empty( $block->context['query']['taxQuery'] ) ) { $query['tax_query'] = array(); foreach ( $block->context['query']['taxQuery'] as $taxonomy => $terms ) { if ( is_taxonomy_viewable( $taxonomy ) && ! empty( $terms ) ) { $query['tax_query'][] = array( 'taxonomy' => $taxonomy, 'terms' => array_filter( array_map( 'intval', $terms ) ), 'include_children' => false, ); } } } if ( isset( $block->context['query']['order'] ) && in_array( strtoupper( $block->context['query']['order'] ), array( 'ASC', 'DESC' ), true ) ) { $query['order'] = strtoupper( $block->context['query']['order'] ); } if ( isset( $block->context['query']['orderBy'] ) ) { $query['orderby'] = $block->context['query']['orderBy']; } if ( isset( $block->context['query']['author'] ) ) { if ( is_array( $block->context['query']['author'] ) ) { $query['author__in'] = array_filter( array_map( 'intval', $block->context['query']['author'] ) ); } elseif ( is_string( $block->context['query']['author'] ) ) { $query['author__in'] = array_filter( array_map( 'intval', explode( ',', $block->context['query']['author'] ) ) ); } elseif ( is_int( $block->context['query']['author'] ) && $block->context['query']['author'] > 0 ) { $query['author'] = $block->context['query']['author']; } } if ( ! empty( $block->context['query']['search'] ) ) { $query['s'] = $block->context['query']['search']; } if ( ! empty( $block->context['query']['parents'] ) && is_post_type_hierarchical( $query['post_type'] ) ) { $query['post_parent__in'] = array_filter( array_map( 'intval', $block->context['query']['parents'] ) ); } } /** * Filters the arguments which will be passed to `WP_Query` for the Query Loop Block. * * Anything to this filter should be compatible with the `WP_Query` API to form * the query context which will be passed down to the Query Loop Block's children. * This can help, for example, to include additional settings or meta queries not * directly supported by the core Query Loop Block, and extend its capabilities. * * Please note that this will only influence the query that will be rendered on the * front-end. The editor preview is not affected by this filter. Also, worth noting * that the editor preview uses the REST API, so, ideally, one should aim to provide * attributes which are also compatible with the REST API, in order to be able to * implement identical queries on both sides. * * @since 6.1.0 * * @param array $query Array containing parameters for `WP_Query` as parsed by the block context. * @param WP_Block $block Block instance. * @param int $page Current query's page. */ return apply_filters( 'query_loop_block_query_vars', $query, $block, $page ); } /** * Helper function that returns the proper pagination arrow HTML for * `QueryPaginationNext` and `QueryPaginationPrevious` blocks based * on the provided `paginationArrow` from `QueryPagination` context. * * It's used in QueryPaginationNext and QueryPaginationPrevious blocks. * * @since 5.9.0 * * @param WP_Block $block Block instance. * @param bool $is_next Flag for handling `next/previous` blocks. * @return string|null The pagination arrow HTML or null if there is none. */ function get_query_pagination_arrow( $block, $is_next ) { $arrow_map = array( 'none' => '', 'arrow' => array( 'next' => '→', 'previous' => '←', ), 'chevron' => array( 'next' => '»', 'previous' => '«', ), ); if ( ! empty( $block->context['paginationArrow'] ) && array_key_exists( $block->context['paginationArrow'], $arrow_map ) && ! empty( $arrow_map[ $block->context['paginationArrow'] ] ) ) { $pagination_type = $is_next ? 'next' : 'previous'; $arrow_attribute = $block->context['paginationArrow']; $arrow = $arrow_map[ $block->context['paginationArrow'] ][ $pagination_type ]; $arrow_classes = "wp-block-query-pagination-$pagination_type-arrow is-arrow-$arrow_attribute"; return ""; } return null; } /** * Helper function that constructs a comment query vars array from the passed * block properties. * * It's used with the Comment Query Loop inner blocks. * * @since 6.0.0 * * @param WP_Block $block Block instance. * @return array Returns the comment query parameters to use with the * WP_Comment_Query constructor. */ function build_comment_query_vars_from_block( $block ) { $comment_args = array( 'orderby' => 'comment_date_gmt', 'order' => 'ASC', 'status' => 'approve', 'no_found_rows' => false, ); if ( is_user_logged_in() ) { $comment_args['include_unapproved'] = array( get_current_user_id() ); } else { $unapproved_email = wp_get_unapproved_comment_author_email(); if ( $unapproved_email ) { $comment_args['include_unapproved'] = array( $unapproved_email ); } } if ( ! empty( $block->context['postId'] ) ) { $comment_args['post_id'] = (int) $block->context['postId']; } if ( get_option( 'thread_comments' ) ) { $comment_args['hierarchical'] = 'threaded'; } else { $comment_args['hierarchical'] = false; } if ( get_option( 'page_comments' ) === '1' || get_option( 'page_comments' ) === true ) { $per_page = get_option( 'comments_per_page' ); $default_page = get_option( 'default_comments_page' ); if ( $per_page > 0 ) { $comment_args['number'] = $per_page; $page = (int) get_query_var( 'cpage' ); if ( $page ) { $comment_args['paged'] = $page; } elseif ( 'oldest' === $default_page ) { $comment_args['paged'] = 1; } elseif ( 'newest' === $default_page ) { $max_num_pages = (int) ( new WP_Comment_Query( $comment_args ) )->max_num_pages; if ( 0 !== $max_num_pages ) { $comment_args['paged'] = $max_num_pages; } } // Set the `cpage` query var to ensure the previous and next pagination links are correct // when inheriting the Discussion Settings. if ( 0 === $page && isset( $comment_args['paged'] ) && $comment_args['paged'] > 0 ) { set_query_var( 'cpage', $comment_args['paged'] ); } } } return $comment_args; } /** * Helper function that returns the proper pagination arrow HTML for * `CommentsPaginationNext` and `CommentsPaginationPrevious` blocks based on the * provided `paginationArrow` from `CommentsPagination` context. * * It's used in CommentsPaginationNext and CommentsPaginationPrevious blocks. * * @since 6.0.0 * * @param WP_Block $block Block instance. * @param string $pagination_type Optional. Type of the arrow we will be rendering. * Accepts 'next' or 'previous'. Default 'next'. * @return string|null The pagination arrow HTML or null if there is none. */ function get_comments_pagination_arrow( $block, $pagination_type = 'next' ) { $arrow_map = array( 'none' => '', 'arrow' => array( 'next' => '→', 'previous' => '←', ), 'chevron' => array( 'next' => '»', 'previous' => '«', ), ); if ( ! empty( $block->context['comments/paginationArrow'] ) && ! empty( $arrow_map[ $block->context['comments/paginationArrow'] ][ $pagination_type ] ) ) { $arrow_attribute = $block->context['comments/paginationArrow']; $arrow = $arrow_map[ $block->context['comments/paginationArrow'] ][ $pagination_type ]; $arrow_classes = "wp-block-comments-pagination-$pagination_type-arrow is-arrow-$arrow_attribute"; return ""; } return null; } /** * Strips all HTML from the content of footnotes, and sanitizes the ID. * This function expects slashed data on the footnotes content. * * @access private * @since 6.3.2 * * @param string $footnotes JSON encoded string of an array containing the content and ID of each footnote. * @return string Filtered content without any HTML on the footnote content and with the sanitized id. */ function _wp_filter_post_meta_footnotes( $footnotes ) { $footnotes_decoded = json_decode( $footnotes, true ); if ( ! is_array( $footnotes_decoded ) ) { return ''; } $footnotes_sanitized = array(); foreach ( $footnotes_decoded as $footnote ) { if ( ! empty( $footnote['content'] ) && ! empty( $footnote['id'] ) ) { $footnotes_sanitized[] = array( 'id' => sanitize_key( $footnote['id'] ), 'content' => wp_unslash( wp_filter_post_kses( wp_slash( $footnote['content'] ) ) ), ); } } return wp_json_encode( $footnotes_sanitized ); } /** * Adds the filters to filter footnotes meta field. * * @access private * @since 6.3.2 */ function _wp_footnotes_kses_init_filters() { add_filter( 'sanitize_post_meta_footnotes', '_wp_filter_post_meta_footnotes' ); } /** * Removes the filters that filter footnotes meta field. * * @access private * @since 6.3.2 */ function _wp_footnotes_remove_filters() { remove_filter( 'sanitize_post_meta_footnotes', '_wp_filter_post_meta_footnotes' ); } /** * Registers the filter of footnotes meta field if the user does not have unfiltered_html capability. * * @access private * @since 6.3.2 */ function _wp_footnotes_kses_init() { _wp_footnotes_remove_filters(); if ( ! current_user_can( 'unfiltered_html' ) ) { _wp_footnotes_kses_init_filters(); } } /** * Initializes footnotes meta field filters when imported data should be filtered. * * This filter is the last being executed on force_filtered_html_on_import. * If the input of the filter is true it means we are in an import situation and should * enable kses, independently of the user capabilities. * So in that case we call _wp_footnotes_kses_init_filters; * * @access private * @since 6.3.2 * * @param string $arg Input argument of the filter. * @return string Input argument of the filter. */ function _wp_footnotes_force_filtered_html_on_import_filter( $arg ) { // force_filtered_html_on_import is true we need to init the global styles kses filters. if ( $arg ) { _wp_footnotes_kses_init_filters(); } return $arg; }