public
Created

Shorten excerpt in display posts shortcode

  • Download Gist
gistfile1.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
<?php
 
/**
* Shorten excerpt in display posts shortcode
* @author Bill Erickson
* @link http://wordpress.org/extend/plugins/display-posts-shortcode/
* @link http://www.billerickson.net/shortcode-to-display-posts/comment-page-1/#comment-4508
*
* @param $output string, the original markup for an individual post
* @param $atts array, all the attributes passed to the shortcode
* @param $image string, the image part of the output
* @param $title string, the title part of the output
* @param $date string, the date part of the output
* @param $excerpt string, the excerpt part of the output
* @return $output string, the modified markup for an individual post
*/
 
add_filter( 'display_posts_shortcode_output', 'be_customize_display_posts', 10, 6 );
function be_customize_display_posts( $output, $atts, $image, $title, $date, $excerpt ) {
 
// First check if an excerpt is included by looking at the shortcode $atts
if ( $atts['include_excerpt'] )
// Now let's shorten the excerpt if needed
$excerpt = '<p class="excerpt">' . be_truncate_phrase( get_the_excerpt(), 50 ) . '&hellip;</p>';
else $excerpt = '';
// Add a <p> around the title
$title = '<p><a class="title" href="'. get_permalink() .'">'. get_the_title() .'</a></p>';
 
// Pull in the custom field 'be_buy_button' that contains a shortcode
global $post;
$buy = get_post_meta( $post->ID, 'be_buy_button', true );
 
// If buy isn't empty, wrap it in a <p> and do the shortcodes
if ( !empty( $buy ) ) $buy = '<p class="buy">' . do_shortcode( $buy ) . '</p>'; else $buy = '';
 
// Now let's rebuild the output.
$output = '<li>' . $image . $title . $date . $excerpt . $buy . '</li>';
// Finally we'll return the modified output
return $output;
}
 
/**
* Truncate Excerpt
*
*/
function be_truncate_phrase($phrase, $max_characters) {
 
$phrase = trim( $phrase );
 
if ( strlen($phrase) > $max_characters ) {
 
// Truncate $phrase to $max_characters + 1
$phrase = substr($phrase, 0, $max_characters + 1);
 
// Truncate to the last space in the truncated string.
$phrase = trim(substr($phrase, 0, strrpos($phrase, ' ')));
}
 
return $phrase;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.