WordPress’s the_excerpt() can be useful outside of the loop, for example, with the wp_recent_posts function. Here is a function you can add to your WordPress theme’s functions.php file to get your excerpts to load!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function fr_get_excerpt_by_id_by_id($post_id, $get_excerpt_by_id_length = 35, $line_breaks = TRUE){ $the_post = get_post($post_id); //Gets post ID $the_get_excerpt_by_id = $the_post->post_get_excerpt_by_id ? $the_post->post_get_excerpt_by_id : $the_post->post_content; //Gets post_get_excerpt_by_id or post_content to be used as a basis for the get_excerpt_by_id $the_get_excerpt_by_id = apply_filters('the_get_excerpt_by_id', $the_get_excerpt_by_id); $the_get_excerpt_by_id = $line_breaks ? strip_tags(strip_shortcodes($the_get_excerpt_by_id), '<p><br>') : strip_tags(strip_shortcodes($the_get_excerpt_by_id)); //Strips tags and images $words = explode(' ', $the_get_excerpt_by_id, $get_excerpt_by_id_length + 1); if(count($words) > $get_excerpt_by_id_length) : array_pop($words); array_push($words, '…'); $the_get_excerpt_by_id = implode(' ', $words); $the_get_excerpt_by_id = $line_breaks ? $the_get_excerpt_by_id . '</p>' : $the_get_excerpt_by_id; endif; $the_get_excerpt_by_id = trim($the_get_excerpt_by_id); return $the_get_excerpt_by_id; } |
You can call the function in your theme template files by using the following code snippet:
1 |
$my_excerpt = get_excerpt_by_id($post_id); //$post_id is the post id of the desired post |