Content Type Labels in Search Results
Shows a small label such as "Page", "Post" or "Product" in front of each search result title, so visitors can tell results apart at a glance.
Opens WPIDE on
Code
add_filter( 'post_class', function ( $classes, $extra, $post_id ) {
if ( is_search() && ! is_admin() ) {
$classes[] = 'wpide-result-type-' . sanitize_html_class( get_post_type( $post_id ) );
}
return $classes;
}, 10, 3 );
add_action( 'wp_head', function () {
if ( ! is_search() ) {
return;
}
$css = '';
foreach ( get_post_types( array( 'exclude_from_search' => false ), 'objects' ) as $type ) {
$label = str_replace( array( '\\', '"', '<', '>' ), '', $type->labels->singular_name );
$css .= '.wpide-result-type-' . sanitize_html_class( $type->name ) . ' :is(.entry-title,.wp-block-post-title)::before{content:"' . $label . '";}';
}
// A small pill in front of each result title, such as "Page" or "Product".
$css .= '[class*="wpide-result-type-"] :is(.entry-title,.wp-block-post-title)::before{display:inline-block;margin-right:.5em;padding:.15em .6em;border-radius:999px;border:1px solid currentColor;font-size:.55em;font-weight:600;letter-spacing:.03em;line-height:1.4;text-transform:uppercase;vertical-align:middle}';
echo '<style id="wpide-result-type-labels">' . $css . '</style>'; // phpcs:ignore WordPress.Security.EscapeOutput -- labels stripped of quotes and markup above.
} );
Notes
Uses the singular name of each post type; works with themes that use the standard entry-title or Post Title block classes.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.