Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.