Custom excerpt length & Read More link WordPress
Posted on 26th May, 2014 3 Comments
I often want to use a custom excerpt length in my themes. Custom excerpts can be really useful whether they are being used for the archives, home page or even when being used in meta description! Being able to add just the right amount of copy to a section is easy with this snippet.
New Excerpt Length
Functions.php
Add this to your functions.php:
/* * NEW EXCERPT LENGTH *************************************************************/ function content($limit) { $content = explode(' ', get_the_content(), $limit); if (count($content)>=$limit) { array_pop($content); $content = implode(" ",$content).'…'; } else { $content = implode(" ",$content); } $content = preg_replace('/[.+]/','', $content); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); return $content; }
Then to display this excerpt in your theme add this:
// Change the '38' to which ever number of words you would like to display <?php $content = get_the_content(); echo wp_trim_words( $content , '38' ); ?>
If you would like to use this new excerpt for your page meta description then you may want to use this. In your header.php add your meta description with this.
<?php if (is_single() || is_page() ) : if ( have_posts() ) : while ( have_posts() ) : the_post(); // IF WE'RE ON THE SINGLE POST, A PAGE USE THE EXCERPT AS THE DESCRIPTION ?> <meta name="description" content="<?php $content = get_the_content(); echo wp_trim_words( $content , '38' ); ?>" /> <?php endwhile; endif; elseif(is_home()) : // IF WE'RE ON THE HOME PAGE THEN USE THE BLOG DESCRIPTION ?> <meta name="description" content="<?php bloginfo('description'); ?>" /> <?php endif; ?>
Read More Links
If you’re adding a custom excerpt then why not add a nice new read-more link.
functions.php
/* * READ MORE *************************************************************/ function new_excerpt_more($more) { global $post; // This will automatically be added where the read-more link normally appears. // Change the '<b>+</b> Read More' to your own message... return '… <div class="read-more"><a class="button" href="'. get_permalink($post->ID) . '">' . '<b>+</b> Read More' . '</a></div>'; } add_filter('excerpt_more', 'new_excerpt_more');
Comments
To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:
Gary Sands
30th, Jan, 15I had a similar problem, excerpt lengths in loops being affected by the length of the post titles. So I wrote a quick function to dynamically adjust their lengths. http://www.gdswebdesign.co.uk/blog/coding/dynamic-excerpt-lengths-in-wordpress/
By the way, I like your blog:)
G.
Aaron
02nd, Feb, 15Gary, I like your thinking. Good post mate 🙂
techno69
03rd, Jun, 15Took me ages to find an article that explained this as easy as your, so thanks, hope to read more of your wordpress hacks.