Site logo

Archived topic

Adding post type name before title on archive page

1 reply · Started by Nikolas on April 25, 2021

Viewing posts 1–2 of 2

Hello,

When you perform a search on my site, the archive page displays a list of all results. Is it possible that the post type would be displayed before the title in the results? I have a few CPT:s and it would be easier for the user to grasp the results if the post type would be seen...

So let's say I perform a search "apples", and then there's results from multiples different post types (for example: "projects", "news"). In the results they would be display as: "News - This is a post about apples", or "Project - Growing apples". Would this be possible to achieve with a hook?

Hi there,

It's definitely possible to display it but I'm not exactly sure how you want it styled.

You can either filter the_title, or use the generate_before_entry_title

Example: using generate_before_entry_title.

add_action('generate_before_entry_title',function(){	
	$post_type = get_post_type( get_the_ID() );
	$post_obj = get_post_type_object( $post_type );
	$post_name = $post_obj->labels->singular_name;

	echo '<h2 class="post-name">'. $post_name .'</h2>';
});

Example #2: using filter.

add_filter( 'the_title', function( $title ){
	$post_type = get_post_type( get_the_ID() );
	$post_obj = get_post_type_object( $post_type );
	$post_name = $post_obj->labels->singular_name;
	return $post_name.' - '.$title;
});
This archived topic is closed to new replies.