Created
August 30, 2011 01:50
-
-
Save billerickson/1179950 to your computer and use it in GitHub Desktop.
Shorten excerpt in display posts shortcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ) . '…</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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment