On many sites that I develop I want to show articles that contains both a teaser text and a body text, and I want to be able to format the teaser different than the body. So…I made a function to accomplish this.
What the function does is that it wraps everything in the post before the ”read more”-tag in a div with the class "post-teaser"
, and everything else in a div with the class "post-body"
. Then it’s a piece of cake to add som styles to those divs with CSS.
I like it and use it a lot. And here it is:
[php]
/**
* This is a nifty little finction that makes is possible to
* format teaser and body differently
*
* It will output:
* – teaser/text before the read-more-thingie wrapped in div.post-teaser
* – body/text after the read-more-thingie wrapped in div.post-body
* – ..but only if each one exists. so you can get teaser + body, or only teaser, or only body
*
* @author Pär Thernström
*
*/
function ma_teaser_and_body($post_id = NULL) {
global $post, $more;
$post_org = $post;
$more_org = $more;
if (!$post_id) {
$post_id = $post->ID;
}
$post = get_post($post_id);
setup_postdata($post);
// Get teaser/text before the "read me"
$content = $post->post_content;
if ( preg_match(’/<!–more(.*?)?–>/’, $content, $matches) ) {
// more-tag exists
$more = 0;
ob_start();
the_content("", true);
$teaser = ob_get_clean();
} else {
$teaser = "";
}
// Get the content/text after "read me"
$more = 1;
ob_start();
the_content(NULL, true);
$body = ob_get_clean();
if ($teaser) {
$teaser = "<div class=’post-teaser’>$teaser</div>";
}
if ($body) {
$body = "<div class=’post-body’>$body</div>";
}
$post = $post_org;
$more = $more_org;
setup_postdata($post);
echo $teaser . $body;
}
[/php]
Changelog
27 mar 2011: Updated code a bit due to a problem that occured when no more-tag existed in post.