Technology

Sprucing up

Opinion

Cooking

Opinion

Space Degree

Opinion

Relaxation

Technology

Round Pebbles

Sillyness Spelled Wrong Intentionally

Custom Excerpts for WordPress

Custom Excerpts for WordPress was penned 10 years ago. It was It was 42°F in Frisco, TX and the sky was clear. was spinning on the ol' iTunes.

So I have already been asked a couple of questions about the new deisgn; namely how do I make WordPress give me the entire commenting history for an individual commenter, and how am I doing my excerpts in the recent entries column.

I thought I would cover the second question first, since it is the easier of the two.  I toyed with using the function the_excerpt(); built into WordPress, but after much deliberation I decided to roll my own so that I could have more control over the output.

Basically my excerpt function takes two variables, the ID of the post, and how many characters to display from that post.  Not too complicated.  I decided to create two seperate functions so that I could maximize flexibility.

Function one: recent()

So the first function hits the DB and find the most recent (n) posts, excluding our current post (which we pass to the function via $post->ID.):

function recent($current) {
   global $wpdb;
   $posts = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE ID 
   != '$current' AND post_status = 'publish' ORDER BY post_date 
   DESC LIMIT 5");
   
   if(is_array($posts)) {
      return $posts;
   } else {
      return array();
   }
}

So let's take a quick look at what we are doing with our recent() function.  First off we of course are globalling the WordPress database object... kind of hard to retrieve data without it.

Next we move onto our SQL query.  Let's take a look at the query on its own, for this example lets assume that we passed our function a post id of 789:

$posts = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE ID != '789' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 5");

Nothing too complex going on here either; we are grabbing all the data from our post table except for our newest post (the WHERE clause), making sure that the posts we are retrieving have been published (the AND) and finally limiting the number of posts that are being returned to 5; oh, we are also saying give them to us in descending order (the ORDER BY bit.).

So by this point we should have all the data we need from the database; since we are requesting multiple pieces of data we will be expecting an array to be returned.

The next bit of code is just some error checking that I do as a rule to make sure that I have an array before I move on; the code we will be using to interact with our retrieved data expects an array to be passed to it, even if it is an empty one (return array() will create an empty array):

   if(is_array($posts)) {
      return $posts;
   } else {
      return array();
   }
}

So now we have all of our recent post data, so now we need to create the function that we will call to create our excerpt text.

Function 2: excerpt()

Now getting on to the fun part, making our excerpt.  One of the things I wanted to be able to do with this function was call it from any number of possible locations, not just from the recent posts area.  To make it as flexible as possible, I decided it would accept two variables: $text and $chars:

function excerpt($text, $chars) {
   $text = $text . " ";
   $text = strip_tags($text);
   $text = substr($text,0,$chars);
   $text = substr($text,0,strrpos($text,' '));
   $text = $text . "...";
   echo $text;
}

What the above function allows us to do is to give it a text stream, and a number of characters to limit that text stream to.  For instance I could call it like so: excerpt('This is my great text', '3');, which would give me:

Thi

Or I could call excerpt('This is my great text', '10'); which would give me:

This is my

I think you get the idea.  So now all that is left is to throw the two functions together in a class file:

class posts {
   function recent($current) {
      global $wpdb;
      //$today = gmdate("Y-m-d G:i:s");
      $posts = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE ID != 
      '$current' AND post_status = 'publish' ORDER BY post_date DESC 
      LIMIT 5");
   
      if(is_array($posts)) {
         return $posts;
      } else {
         return array();
      }
   }

   function excerpt($text, $chars) {
      $text = $text . " ";
      $text = strip_tags($text);
      $text = substr($text,0,$chars);
      $text = substr($text,0,strrpos($text,' '));
      $text = $text . "..";
      echo $text;
   }
}

Now that we have created our posts class, it is time to switch to our front end code.  For this example we are going to be adding this code to our sidebar.php template file, so that when you the root of your site is being viewed (index.php with no arguments) your most recent 5 posts will be shown.

Our code would look something like this:

<p>
<?php if (is_home()) { ?>
   $recent = posts::recent($post->ID); ?>
   <ol>
   <?php foreach ( $recent as $item ) { ?>
      <li>
         <p>
            <a href="<?php echo $item->guid; ?>"><?php echo $item->post_title; ?></a>. <?php posts::excerpt($item->post_content, '125'); ?>.
         </p>
      </li>
   <?php } ?>
   </ol>
<?php } ?>
</p>

So as you can see from the above code, we are calling our recent function, and then passing the array off to our foreach loop for processing.  Here in the loop is where we call our second function, excerpt().

In this example we are passing the post_content for each item in our array to our excerpt() function and limiting the returned content to 125 characters.  Not too difficult.

And that is all she wrote.

For the most part this is the exact code I am running to power my recent entries section.  Let me know via the comments if anything wasn't clear, and I will try to update this post to improve it.

As I said at the beginning, you could easily combine these two functions into one, but I seperated them to allow for using them in unexpected, or unanticipated ways later.  To each his own.

I hope you enjoyed reading Custom Excerpts for WordPress
By becoming a Patron of Sillyness you can ensure quality writing, film, photography and music like this continue to be made available.