WordPress sites are difficult to manage, especially when posts are published by persons who don't have a firm knowledge of how WordPress posts should be formatted and handled. So many posts are published without a featured image or without an excerpt, thus causing many display and formatting problems when they appear in the Loop. In this article I'd like to show you some defense techniques to prevent these issues from happening.
No excerpts
When a post has no excerpt, WordPress extracts a portion of the post content and uses it as an excerpt. The problem is that very often these content portions have also markup elements attached to them, so the first thing you have to do is to remove all the HTML tags:
$excerpt = get_the_excerpt(); echo strip_tags($excerpt);
Sometimes the "Read more" link is also contained within this part of content. When you strip out all the HTML tags, the "Read more" string won't be removed, so you have to manually remove it:
$excerpt = get_the_excerpt(); $stripped = strip_tags($excerpt); echo str_replace('Read more', '', $stripped);
Another approach is to use directly the content of each post. For example, you can extract only the first 200 characters from a post:
$content = strip_tags(get_the_content()); echo substr($content, 0, 200);
When you use this approach, it's often useful to add an ellipsis at the end of the string:
$content = strip_tags(get_the_content()); echo substr($content, 0, 200) . ' ...';
No featured images
Thumbnails depend directly from setting a featured image on each post. Generally speaking, most of our clients will simply forget to specify a featured image and they will prefer to insert a floated image into the post content.
In this case, we have to set a default thumbnail for our posts and insert it only when no other image has been inserted at the beginning of the post. Here's the code:
add_filter( 'post_thumbnail_html', 'post_thumbnail_default', 10, 3 ); function post_thumbnail_default( $html, $post_id, $post_image_id ) { global $post; $content = $post->post_content; if( '' == $html && !preg_match('/<p><img[^>]*\/>/', $content) ) { $html = '<img src="' . get_bloginfo('template_url') . '/images/default-thumbnail.jpg' . '"/>'; } return $html; }
This filter simply provides a default thumbnail when a post doesn't have a featured image or an embedded image.