Skip to main content
WordPress made easy with the drag & drop Total WordPress Theme - 50% OFF for a limited time!Learn More

How to Add Multiple Custom Excerpt Lengths In WordPress

Last updated on:

By default WordPress excerpts are set to 55 words and there is an excerpt_length filter which allows you to change this default value to your length of choice. But what if you wanted a different excerpt length on different sections of your site? For example if you are developing a website with multiple post types you may want to show different excerpt lengths depending on the post type. A blog post may have a longer excerpt than for example a portfolio item.

Custom Excerpt Function

Below you will find a custom function we’ve developed to help you display excerpts at different lengths in WordPress. To use the function simply add it to your functions.php file and then you can go about replacing either the_excerpt or the_content functions throughout your theme so you can different excerpt lengths.

function wpex_get_excerpt( $args = array() ) {

	// Defaults
	$defaults = array(
		'post'            => '',
		'length'          => 40,
		'readmore'        => false,
		'readmore_text'   => esc_html__( 'read more', 'text-domain' ),
		'readmore_after'  => '',
		'custom_excerpts' => true,
		'disable_more'    => false,
	);

	// Apply filters
	$defaults = apply_filters( 'wpex_get_excerpt_defaults', $defaults );

	// Parse args
	$args = wp_parse_args( $args, $defaults );

	// Apply filters to args
	$args = apply_filters( 'wpex_get_excerpt_args', $defaults );

	// Extract
	extract( $args );

	// Get global post data
	if ( ! $post ) {
		global $post;
	}

	// Get post ID
	$post_id = $post->ID;

	// Check for custom excerpt
	if ( $custom_excerpts && has_excerpt( $post_id ) ) {
		$output = $post->post_excerpt;
	}

	// No custom excerpt...so lets generate one
	else {

		// Readmore link
		$readmore_link = '<a href="' . get_permalink( $post_id ) . '" class="readmore">' . $readmore_text . $readmore_after . '</a>';

		// Check for more tag and return content if it exists
		if ( ! $disable_more && strpos( $post->post_content, '<!--more-->' ) ) {
			$output = apply_filters( 'the_content', get_the_content( $readmore_text . $readmore_after ) );
		}

		// No more tag defined so generate excerpt using wp_trim_words
		else {

			// Generate excerpt
			$output = wp_trim_words( strip_shortcodes( $post->post_content ), $length );

			// Add readmore to excerpt if enabled
			if ( $readmore ) {

				$output .= apply_filters( 'wpex_readmore_link', $readmore_link );

			}

		}

	}

	// Apply filters and echo
	return apply_filters( 'wpex_get_excerpt', $output );

}

How To Use The Function

So now instead of using “the_excerpt()” in your loops you can use “wpex_excerpt( $args )”, where $args holds an array of your preferred settings for the specific excerpt.

Example:

<?php echo wpex_get_excerpt ( $defaults = array(
	'length'          => 40,
	'readmore'        => true,
	'readmore_text'   => esc_html__( 'read more', 'wpex-boutique' ),
	'custom_excerpts' => true,
) ); ?>

Function Filters

You may notice that our snippet includes various apply_filters() functions. Why? The reason for this is if you are working on a premium or free theme or plugin for distribution you will want to give the end users the ability to alter their excerpts via their child theme if needed. For example if you defined an excerpt to be a certain length for a section of the site the end user could always use the “wpex_get_excerpt_args” filter to change the excerpt to a different length or customize the text or readmore

Subscribe to the Newsletter

Get our latest news, tutorials, guides, tips & deals delivered to your inbox.

24 Comments

  1. keylime

    FAN-TAS-TIC! thanks!

  2. Kakembo Alex

    I use this alot and it works on pages and post, because its a WordPress function so no need of writing another function.

  3. Shua

    Thanks! this is awesome! 🙂

  4. Kursus Web Designur

    My programming skill is so bad. But it help me to adding multiple excerpt 😉
    Thanks so much AJ

  5. lemonthirst

    Thank you,
    life saver as usual!

  6. Michael Hayes

    Thanks for the wp_trim_words tip. Super handy, and new to me.

  7. dcom

    It’s also handy to know that you can control your titles by altering this code. It definitely helps when you only want to show the headline of a title and limit it for the client.

  8. Jonathan

    Helo AJ I’m developing wp theme and iterested if I can use this code snippet in commercial use? Thanks in advance 🙂

    • AJ Clarke

      Definitely any tutorial on my site you can use as you see fit 😉

  9. Jonathan

    ok. many thanks 🙂

  10. Jordan Smith

    You rock dude, thanks!

  11. Jamie Knop

    Thanks for this AJ. I am having an issue with this code though as it wants to remove the image from the very top of the post (not set by featured).

    How can I make it include images also?

    Thanks

    • AJ Clarke

      You can’t Jamie, because the wp_trim_words function strips all HTML. If you have a look at the function in the codex you’ll see that one of the first things the function does is run the content through wp_strip_all_tags.

      • Jamie Knop

        Cheers for clearing that up AJ. Do you know any alternative methods I could use so it would leave the HTML in tact?

        Thanks

        • AJ Clarke

          Not via any core functions, the only alternative I can think of would be using PHP (maybe substr?)

          • Jamie Knop

            Ok cheers anyway AJ. I’m no coder, so I will just carry on playing to see if I can come up with a solution!

  12. jairo

    You are the best!

  13. 1v4n0

    thank yoo. Just what I was looking for. No idea how it works, but who cares 😀

  14. mat

    tnx for this. is it possible to add “read more” link after trimming the text?

  15. Mohsinur Rahman

    It works perfectly. Thankyou for for this interisting posting.

  16. alon188

    Hi there, I have been using this for a while and works great, is there a way to use this function with the get_post function, it does not seem to work when I try to use it, thanks

  17. Alex

    Great Post! Thank you!

  18. Jitender

    Nice Post. Thanks for share..

Leave a Reply

Your email address will not be published. Required fields are marked *

Learn how your comment data is processed by viewing our privacy policy here.