Skip to content

WordPress – Add Post Type Labels to Post Titles

If you want to add a label to your post titles to help your viewers identify what type of content it is then this might help. It’s useful in situations where you share taxonomies with different post types, or yield search results from multiple post types.

function add_post_type_label_to_title($title, $id = null) {
 
    // The html before the insert after title
    $html_first         = '<span class="example-post-type-label">';
 
    // Title after defaults to false
    $title_after        = false;
 
    // The html after the insert after title
    $html_after         = '</span>';
 
    // Allowed post types
    $allowed_post_types = array(
        'post',
        'quickie'
    );
 
    // Make sure we're filtering title in the loop
    // Note: This will also filter singular titles
    if(in_the_loop()) {
        $post_type          = get_post_type();
 
        // Uncomment if you don't want the label to appear on singular templates
        // if(!is_singular($post_type) && !is_single()) {
            if(in_array($post_type, $allowed_post_types)) {
                $post_type_obj  = get_post_type_object($post_type);
                $title_after    = $post_type_obj->labels->singular_name;
            }
        // }
 
    }
 
    // If we have a post type
    if($title_after) {
        return $title . $html_first . $title_after . $html_after;
    }
 
    return $title;
 
}
 
add_filter( 'the_title', 'add_post_type_label_to_title', 10, 2 );

I’ve also added a bit of CSS for demonstration purposes.

// This is just some example styling.
// Do something more fancy than this
add_action('wp_head', 'add_post_type_label_eg_css');
function add_post_type_label_eg_css() {
    $output="<style>
    .example-post-type-label {
        background-color : #f1f1f1;
        font-weight:bold;
        font-size:13px;
        padding:5px;
        margin-left:15px;
        display:inline-block;
    }
    </style>";
    echo $output;
}

About 

10 years + experience in web development working with lots of different technology.

Published inPHPWordPress

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *