Skip to content

Instantly share code, notes, and snippets.

@mustardBees
Last active December 17, 2015 14:39
Show Gist options
  • Save mustardBees/5626366 to your computer and use it in GitHub Desktop.
Save mustardBees/5626366 to your computer and use it in GitHub Desktop.
Get an excerpt from a specific post ID or post object with a variable excerpt length
<?php
/**
* Get the excerpt of a specific post ID or object
*
* @author Pippin Williamson
* @link http://goo.gl/lhtZD
* @param object/int $post The ID or object of the post to get the excerpt of
* @param int $length The length of the excerpt in words
* @param string $tags The allowed HTML tags. These will not be stripped out
* @param string $extra Text to append to the end of the excerpt
*/
function iweb_get_excerpt_by_id( $post, $length = 10, $tags = '<a><em><strong>', $extra = '&hellip;' ) {
if ( is_numeric( $post ) ) {
$post = get_post( $post );
} elseif( ! is_object( $post ) ) {
return false;
}
if ( has_excerpt( $post->ID ) ) {
$the_excerpt = $post->post_excerpt;
return apply_filters( 'the_content', $the_excerpt );
} else {
$the_excerpt = $post->post_content;
}
$the_excerpt = strip_shortcodes( strip_tags( $the_excerpt, $tags ) );
$the_excerpt = preg_split( '/\b/', $the_excerpt, $length * 2 + 1 );
$excerpt_waste = array_pop( $the_excerpt );
$the_excerpt = implode( $the_excerpt );
$the_excerpt .= $extra;
return apply_filters( 'the_content', $the_excerpt );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment