WordPress: function to format teaser different from body

Skrivet lördag 26 mars, 2011 | Inga kommentarer

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:

/**
 * 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;

}

Changelog
27 mar 2011: Updated code a bit due to a problem that occured when no more-tag existed in post.

CMS Tree Page View recommended at WordCamp Australia

Skrivet onsdag 09 mars, 2011 | Inga kommentarer

Troy Dean of Video User Manuals did a presentation at WordCamp Australia called ”Better WordPress For Clients”. About 16 minutes in the talk he recommends my WordPress plugin CMS Tree Page View for managing pages in sites with more than 10 pages. Thanks for telling Australia, Troy! :)

Howdy! This is the personal website of Swedish web developer Pär Thernström. You can contact me directly at par.thernstrom@gmail.com or through Twitter at twitter.com/eskapism/.

Besök arkivet för en lista med alla inlägg.