Archived topic
Custom search results > title with cpt label
5 replies · Started by anita on September 20, 2021
Hi,
We would like to add the custom-post-type name (label) to the search results article title.
Formerly, with twentynineteen we changed the search like this:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php
if ( is_sticky() && is_home() && ! is_paged() ) {
printf( '<span class="sticky-post">%s</span>', _x( 'Featured', 'post', 'twentynineteen' ) );
}
echo '<h3>';
the_title( sprintf( '<a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '' );
if( 'xxx' == get_post_type() ) {
echo ' - ' . get_post_type_object(get_post_type($r->id))->labels->singular_name . '';
}
else if ( 'yyy' == get_post_type() ) {
echo ' - ' . get_post_type_object(get_post_type($r->id))->labels->singular_name . '';
}
else if ( 'zzz' == get_post_type() ) {
echo ' - ' . get_post_type_object(get_post_type($r->id))->labels->singular_name . '';
}
echo '</a></h3>';
?>
</header><!-- .entry-header -->
</article>
How to achieve this with GP?
Thanks!
Hi Anita,
You'll have to create a child theme template for your search results page.
Here's the default from the parent theme.
https://github.com/tomusborne/generatepress/blob/master/search.php
You can base your new child theme from this one and replace the <header> tag logic with your own. :)
Hi Elvin,
I created a child-theme file "content-search.php" (a copy of content.php) and replaced
the generate_show_title part with:
if ( generate_show_title() ) {
the_title( sprintf( '<h2 class="entry-title"%2$s><a href="%s" rel="bookmark">', esc_url( get_permalink() ), 'microdata' === generate_get_schema_type() ? ' itemprop="headline"' : '' ), '' );
if( 'xxx' == get_post_type() ) {
echo ' <span class="searchresult-type">- ' . get_post_type_object(get_post_type($r->id))->labels->singular_name . '</span>';
}
else if ( 'yyy' == get_post_type() ) {
echo ' <span class="searchresult-type">- ' . get_post_type_object(get_post_type($r->id))->labels->singular_name . '</span>';
}
else if ( 'zzz' == get_post_type() ) {
echo ' <span class="searchresult-type">- ' . get_post_type_object(get_post_type($r->id))->labels->singular_name . '</span>';
}
echo '</a></h2>';
}
Is this the right way?
You'll need to create a new copy of search.php on your child theme folder.
You then copy the default code of the parent theme found here:
https://github.com/tomusborne/generatepress/blob/master/search.php
You then modify this part, which is the same <header> tag and add the conditions you want within the <header ...> ... </header>
https://github.com/tomusborne/generatepress/blob/2c7c8a76d3b58b0b97e82b3a7a5ebf022a1ddfbe/search.php#L28-L38
Hi Elvin,
I need to change the search results article titels, not the search result page title.
Anyway, the solution with content-search.php template file works, so problem solved :)
Thanks,
Anita
Thanks for letting us know. Glad you got it sorted. :D