cp_attributes( string $element, array|string $attrs = array(), string $context = '' )

Provide a way to filter and escape the HTML attributes being output.


Description

To preserve spaces, quotes, ampersands, pass an array instead of string.


Parameters

$element

(Required) The HTML tag the attributes are for.

$attrs

(Optional) Array of attributes for the element.<br>

Default value: array()

$context

(Optional) Name to use on filter.<br> Default '', which is expanded to calling function.

Default value: ''


Return

(string) All the attributes, escaped.


Source

File: wp-includes/formatting.php

function cp_attributes( $element, $attrs = array(), $context = '' ) {
	if ( ! is_array( $attrs ) ) {
		// This can mess up nested quotes, but wp_parse_args will mess up all quotes.
		$attrs = str_replace(
			array( '="', "='", '" ', "' " ),
			array( '=', '=', '&', '&' ),
			trim( $attrs, "' \"" )
		);
	}
	$attrs = wp_parse_args( $attrs );
	if ( empty( $context ) ) {
		$trace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 );
		$context = isset( $trace[1]['function'] ) ? $trace[1]['function'] : '';
		if ( in_array( $context, array( 'include', 'include_once', 'require', 'require_once' ) ) ) {
			$context = wp_basename( $trace[1]['args'][0] );
		}
	}
	/**
	 * Filters the attribute array.
	 *
	 * @since CP-1.5.0
	 *
	 * @param string[] $attrs   Key is attribute name, value is attribute value.
	 * @param string   $element The HTML element the attributes are for.
	 * @param string   $context Identifying information for this element.
	 */
	$attrs = apply_filters( 'cp_attributes', $attrs, $element, $context );
	/**
	 * Filters the attribute array, specifically using context.
	 * The dynamic portion of the hook name, `$context`, refers to the context.
	 *
	 * @since CP-1.5.0
	 *
	 * @param string[] $attrs   Key is attribute name, value is attribute value.
	 * @param string   $element The HTML element the attributes are for.
	 */
	$attrs = apply_filters( "cp_attributes_{$context}", $attrs, $element );

	$out = '';
	foreach ( $attrs as $attr => $value ) {
		if ( is_array( $value ) ) {
			$value = array_map( 'esc_attr', $value );
			$value = implode( ' ', array_unique( $value ) );
			if ( ! empty( $value ) ) {
				$out .= sanitize_key( $attr ) . '="' . $value . '" ';
			}
		} else {
			$value = ( 'href' === $attr || 'src' === $attr || 'action' === $attr ) ?
				esc_url( $value ) : esc_attr( $value );
			$out .= sanitize_key( $attr ) . '="' . $value . '" ';
		}
	}
	return empty( $out ) ? $out : ' ' . trim( $out );
}

Changelog

Changelog
Version Description
CP-1.5.0 Introduced. CP-1.5.0