Start Your Domain Search

Markit Media Blog

A Better Recent Posts Widget…

The ‘Recent Posts’ widget is probably the most commonly used widget in WordPress. Without much for options, the Recent Posts Widget leaves website owners wanting more. Here at Markit Media, Our WordPress Experts have found many clients want post excerpts on their custom WordPress websites. So we thought we would share our widget for anyone doing custom WordPress development.

Step 1) Open up your preferred FTP client and code editor.

Step 2) Navigate to your theme directory and open your functions.php and your style.css.

Step 3) In your functions.php, paste the following code:

<?php
function mini_posts $number_of_posts$excerpt_length$read_more$title_link  ) { 
// Set Defaults
        
if ( isset( $number_of_posts ) ) { $numberofposts $number_of_posts; }
 else { 
$numberofposts 3; }
        if ( isset( 
$excerpt_length ) ) { $excerptlength $excerpt_length; }
 else { 
$excerptlength 250; }
        if ( isset( 
$read_more ) ) { $readmore $read_more; }
 else { 
$readmore true; }
        if ( isset( 
$title_link ) ) { $titlelink $title_link; }
 else { 
$titlelink false; }
// The Query
        
$the_query = new WP_Query'post_type=post&orderby=date&order=asc&posts_per_page='
 
$numberofposts );
// The Loop
        
echo '<div id="recent_posts_excerpts">';
            while ( 
$the_query->have_posts() ) : $the_query->the_post();
                global 
$post;
                echo 
'<p class="recentpost_title">';
                if ( 
$titlelink ) { ?><a href="<?php the_permalink() ?>"><?php }
                echo 
$post->post_title;
                echo 
'</p>';
                if ( 
$titlelink ) { ?></a><?php }
                echo 
'<p class=ecentpost_content">' substr(strip_tags($post->post_content), 0$excerptlength) . '...';
                if ( 
$readmore ) { ?><br /><a href="<?php the_permalink() ?>">Read More &#8250;</a></p><?php }
            endwhile;
        echo 
'</div>';
// Reset Post Data
        
wp_reset_postdata();
}
?>


Step 4) Paste the following code into your stylesheet(style.css) and style to match you theme:


.recentpost_title {
    font-weight: bold;
}
.recentpost_content {
}
.recentpost_content a {
    text-decoration: none;
}
.recentpost_content a:hover {
    text-decoration: underline;
}

Step 5) Paste the following code into your templates files where you want your new Recent Posts Widget to appear:

<?php mini_posts($number_of_posts,$excerpt_length,$read_more,$title_link); ?>

Step 6) Pat yourself on the back for a job well done!

Be Sociable, Share!
Posted in Tips & Tricks, WordPress | Tagged , , |
Be Sociable, Share!