Conditional Excerpt with custom read more link

Peter put this piece of code together for digital coffee websites. It detects if there is and excerpt or not and adds in a custom read more link to the article.
This code elimates a common issue experienced with excerpts where the more link is always on a new line. The use of variables circumvents this issue.

Step 01:
Add this code to the functions.php file.

<?php
# Custom excerpt more link text
function new_excerpt_more($more) {
       global $post;
	return ' ... <a href="'. get_permalink($post->ID) . '">' . 'Read the full article.' . '</a>';
}
add_filter('excerpt_more', 'new_excerpt_more');
?>

Also add this function for creating your own custom excerpts when they don’t exist:

<?php
# Custom excerpt for those that are too short
function excerpt($excerpt_length) {
  global $post;
	$content = $post->post_content;
	$words = explode(' ', $content, $excerpt_length + 1);
	if(count($words) > $excerpt_length) :
		array_pop($words);
		array_push($words, ' ');
		$content = implode(' ', $words);
	endif;
  
  $content = strip_tags($content);
  
	echo $content;

}
?>

Step 02:
Add this code where you want the article excerpt to be displayed. Note that you can change the length of the automatically generated excerpt with the

			<?php
                //We won't use the standard excerpt which has been commented below/
                //We will check for an excerpt and create one if necessary.
                //We aslo add article links to the end of the excerpt.
                //the_excerpt();
                
                //Here are variables for creating and displaying our excerpts
                $myExcerptTitle = get_the_title($post->ID);
                $myExcerptLink = get_permalink($post->ID);
                
                if (function_exists('has_excerpt') && has_excerpt()) 
                    {
                    // This is what is shown if there is an excerpt
                    $myExcerpt = get_the_excerpt();
                    
                        if ($myExcerpt != '') {
                            // This is a double check just incase there is no excerpt
                        }
                    echo $myExcerpt; echo " ... <a href="$myExcerptLink">Read the full '$myExcerptTitle' article.</a>"; // Outputs the processed value to the page	
                    } 
                
                else
                    {
                    // This is what is happens if we need to create an excerpt
                    // We use the excerpt($excerpt_length) function from the functions file
                    $excerptLength = 40;
                    excerpt($excerptLength); echo " ... <a href="$myExcerptLink">Read the full '$myExcerptTitle' article.</a>"; // Outputs the processed value to the page	
                    }
            ?>  

Revisions

There are no revisions for this post.

Tags: , , , ,

No comments yet.

Leave a Reply