Site logo

[Resolved] Using excerpt as meta description

Home Forums Support [Resolved] Using excerpt as meta description

Home Forums Support Using excerpt as meta description

Viewing 6 posts - 16 through 21 (of 21 total)
  • Author
    Posts
  • #1260106
    Anonymous

    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.”?

    #1260377
    Tom
    Lead Developer
    Lead Developer

    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.

    #1260403
    Anonymous

    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 );
    #1261521
    Tom
    Lead Developer
    Lead Developer

    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 );
    #1261769
    Anonymous

    Thanks for the suggestion Tom.

    #1262140
    Tom
    Lead Developer
    Lead Developer

    No problem!

Viewing 6 posts - 16 through 21 (of 21 total)
  • You must be logged in to reply to this topic.