WordPress.org

Forums

[resolved] How to change excerpt length depending on class of post (3 posts)

  1. jamo_dodger
    Member
    Posted 1 year ago #

    Hello I am using a child theme:

    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:

    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

  2. kevin heath
    Member
    Posted 1 year ago #

    I would probably opt to use jquery in this situation.

    Then you can insert a different except for each class using DOM innerHTML options

  3. jamo_dodger
    Member
    Posted 1 year ago #

    Thanks Kevin I sorted it.

    The problem arose because I wanted to style the search page results differently to the homepage/blog and archive pages (which use the above PHP).

    All I did is made the conditional in the second block of code 'more conditional' so it only applies to the homepage and archive pages:

    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 );

Topic Closed

This topic has been closed to new replies.

About this Topic