change wordpress excerpt length depending on post class

I am using the following PHP in WordPress to apply different classes to posts on my homepage depending on their position:

<article id="post-<?php the_ID(); ?>"
<?php 
    $extra = ( ( $wp_query->current_post % 5 == 0 && !is_page() ) ? 'full' : 'half' ) . ( ( ( $wp_query->current_post % 5 == 1 || $wp_query->current_post % 5 == 3 ) && !is_page() ) ? ' left' : '' );
    post_class($extra);
?>>

In my functions.php I am using the following to change the excerpt length of these posts:

Read More
function twentytwelvechild_custom_excerpt_length( $length ) {
    global $wp_query;
    if( $wp_query->current_post%5 == 0 ) return 30;
    else return 12;
}
add_filter( 'excerpt_length', 'twentytwelvechild_custom_excerpt_length', 12 );`

This gives the first post of every 5 an excerpt length of 30 and the rest 12, but I dont want to do it this way.

How can I use PHP to change the excerpt length of the posts with the class ‘full’ to 30 words and the ones with the class half to 12 words?

Hope this makes sense

James

Related posts

Leave a Reply

2 comments

  1. Option 1:

    Make them all 30 using the excerpt length filter then use wp_trim_words() to strip some down on the page itself.

    Option 2:

    Remove the conditional from your original filter hook and return 30. Create a new function that will return 12 but don’t actually hook it.

    function twentytwelvechild_custom_excerpt_length( $length ) {
        return 30;
    }
    add_filter( 'excerpt_length', 'twentytwelvechild_custom_excerpt_length', 12 );
    
    function twentytwelvechild_custom_excerpt_short( $length ) {
        return 12;
    } 
    

    Then on the page use the following when you want to show the shorter excerpt.

    add_filter( 'excerpt_length', 'twentytwelvechild_custom_excerpt_short', 20 );
    the_excerpt();
    remove_filter( 'excerpt_length', 'twentytwelvechild_custom_excerpt_short', 20 );
    

    By adding the filter before you output the excerpt you’re changing the length to 12. You’re showing the excerpt then removing the filter so any following posts will go back to the normal 30.

  2. I have solved it!! Basically the PHP i used above was having an effect on every single post page – archives, blog page, search results. I asked the question because I am styling my search page and wanted the search results to look different to the archive and homepage layout. So i just made the above conditional ‘more conditional’

    function twentytwelvechild_custom_excerpt_length( $length ) {
        global $wp_query;
        if( $wp_query->current_post%5 == 0 && ( is_home() || is_archive() ) )
            return 30;
        else return 12;
    }
    add_filter( 'excerpt_length', 'twentytwelvechild_custom_excerpt_length', 12 );