Skip to content

Instantly share code, notes, and snippets.

@westonruter
Last active December 16, 2024 01:40
Show Gist options
  • Save westonruter/6088b04ff28dd9c509be53d0685076f0 to your computer and use it in GitHub Desktop.
Save westonruter/6088b04ff28dd9c509be53d0685076f0 to your computer and use it in GitHub Desktop.
<?php
/**
* Constructs a CSS selector for the current tag.
*
* @param WP_HTML_Processor $processor Processor.
* @return string Selector.
*/
function get_css_selector( WP_HTML_Processor $processor ): string {
$selector = join( ' > ', $processor->get_breadcrumbs() );
$id = $processor->get_attribute( 'id' );
if ( is_string( $id ) ) {
$selector .= '#' . $id;
}
$class_attr = $processor->get_attribute( 'class' );
if ( is_string( $class_attr ) ) {
$selector .= join(
'',
array_map(
static function ( string $class_name ): string {
return '.' . $class_name;
},
array_filter(
(array) preg_split( '/\s+/', trim( $class_attr ) )
)
)
);
}
return $selector;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment