Site logo

Archived topic

Custom Excerpt - Limit Length only on Homepage

5 replies · Started by KC on December 1, 2021

Viewing posts 1–6 of 6

Hello,

I am having troubles configuring my Generatepress theme (using Read template) to limit the custom excerpt length but only on homepage.

I am using this code

add_filter( 'wp_trim_excerpt', 'tu_excerpt_metabox_more' );
function tu_excerpt_metabox_more( $excerpt ) {
    $output = $excerpt;

    if ( has_excerpt() ) {
        $output = sprintf( '%1$s <p class="read-more-button-container"><a class="button" href="%2$s">%3$s</a></p>',
            wp_trim_words( $excerpt, 2, '...' ),
            get_permalink(),
            __( 'Read more', 'generatepress' )
        );
    }
	
    return $output;
}

from: https://generatepress.com/forums/topic/trouble-setting-the-excerpt-length/#post-1562738

It works brilliantly, but the problem is I only want this custom excerpt length limit to execute only on the homepage, not in the category/archive page. And also, to not show the "Read more" button.

I tried tweaking the above code with:

if ( has_excerpt() && ( is_home() || is_front_page() ) )

But snippets plugin returns a 403 error, which I think it isn't working.

If someone can enlighten and help me on this...

Hi there,

The condition if ( has_excerpt() && is_home() ) should suffice. Condition nesting like if(is_home()) { if( has_excerpt() ) { ... } } should work as well.

The 403 error is unusual though. 403 error is a permission error on the server side which is usually from a corrupted .htaccess file or server folder permission restrictions. A PHP code like this wouldn't be able to change permission of things.

You may have to ask your webhost about the 403 error you're getting.

Hi Elvin!

Thank you so much for your response.

Okay, so I re-login and the code was saved without any issues. I tried the condition you put and played around and here's my current code:

add_filter( 'wp_trim_excerpt', 'tu_excerpt_metabox_more' );
function tu_excerpt_metabox_more( $excerpt ) {
    $output = $excerpt;

    if(is_home()) { if( has_excerpt() ) {
        $output = sprintf(wp_trim_words( $excerpt, 20, '...' )
        );
    }
				  }
    return $output;
				  
}

But now the custom excerpt limit isn't working anymore.

It is very strange... It seems that whenever I use the is_home() condition, it immediately breaks the code.

But when I omit or remove the is_home() condition, the code works again - custom excerpt gets limited.

Oh wait, I figured it out.

It is because the Read template is using a 'front page' for the homepage.

I just changed the condition from is_home() to is_front_page() and it is working now.

Thanks!

Stay safe everyone!

The loop may not be the blog index then. Glad you got it sorted. Thanks for letting us know. :D

This archived topic is closed to new replies.