Archived topic
Using excerpt as meta description
20 replies · Started by Chad on August 7, 2019
Hi Tom,
Can you elaborate further on "That code doesn’t return anything if you’re not on the blog page, which will likely prevent excerpts from appearing at all."?
It's the way filters work in WordPress. You always need to return something: https://pippinsplugins.com/a-quick-introduction-to-using-filters/
In your case, you're only returning something if a condition is true, but nothing is returning if that condition isn't true.
Thanks Tom.
That's clearer. I imagine that given the scope of the excerpts only displaying on a blog or search page, I presume it's a non-issue if it is false.
Are there other sections/pages or the like excerpts are displayed?
For example, I noticed that they are also displayed in the search results page and tweaked the code as follows.
function replace_excerpt_with_content( $excerpt ){
if ( is_home() || is_search() ) {
$more = '<p class="read-more-container"><a title="' . get_the_title() . '" class="read-more button" href="' . get_permalink() . '">Read More<span class="screen-reader-text">' . get_the_title() . '</span></a></p>';
$content = force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 20, $more ) ) );
return $content;
}
}
add_filter( 'the_excerpt', 'replace_excerpt_with_content', 10, 1 );
Archives will likely be missing excerpts with that code, and it may break some plugins.
To be safe, you can just do this:
function replace_excerpt_with_content( $excerpt ){
if ( is_home() || is_search() ) {
$more = '<p class="read-more-container"><a title="' . get_the_title() . '" class="read-more button" href="' . get_permalink() . '">Read More<span class="screen-reader-text">' . get_the_title() . '</span></a></p>';
$content = force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( wpautop(get_the_content()) ), 20, $more ) ) );
return $content;
}
return $excerpt;
}
add_filter( 'the_excerpt', 'replace_excerpt_with_content', 10, 1 );
Thanks for the suggestion Tom.
No problem!