archive: May 2010


There is a way to fix that. 😀 After some major headaches and a few games later I wrote up a neat regex that takes the information outputted by the ‘next_post_link’ and ‘previous_post_link’ function’s filters and made it so it it added a three dot ellipse at the end of the post title after it shortened it up.In this example I will be using code that is on my site. You might have to tailor your regex to match the outputted default format for your theme/site.

<div class="post<?php if ( $location != 'bottom' ) : ?>-top<?php endif; ?>-pagelinks<?php if ( $location == 'bottom' ) : ?> pl-right-side<?php endif;?>"><?php next_post_link('&nbsp;next: %link'); ?></div>
<div class="post<?php if ( $location != 'bottom' ) : ?>-top<?php endif; ?>-pagelinks<?php if ( $location == 'bottom' ) : ?> pl-right-side<?php endif;?>"><?php previous_post_link('prev: %link&nbsp;'); ?></div>

This is how I generate my ‘next post’ and ‘prev post’ for my theme. :)

So… adding to the filters:

add_filter( 'previous_post_link', array(&$this, 'link_shortner'), 10, 2);
add_filter( 'next_post_link', array(&$this, 'link_shortner'), 10, 2);

The heart of the code is in link_shortner.

 * Shortner the link.
 * @since 1.3.0
 * @param $format
 * @param $link
 * @return Echo link.
 function link_shortner($format, $link) {

 //  The RegEx Pattern
 $pattern = '/(.*?)(<a .*?>)(.*?)(<\/a>)/is';
 //  Pattern Of the Next/Previous Links
 preg_match($pattern, $format, $matches);

 if ( strlen($matches[3]) <= 60 )
 return $format;

 //  Replacement
 $replacement = '$1 $2 ' . mb_substr( $matches[3], 0, 60) . '... $4';
 //  Run Preg Replace
 $source = preg_replace($pattern, $replacement, $format, 1);
 return $source;

The highlighted lines process the format that I use in the functions to call the next/prev links. Because we want to make sure we preserve the formatting we run off $format and not $link. After we have determined that the display text is passed a certain length, we are going to run a replacement making sure we keep all the other elements along as well.

And tada! We now have a shortened display link that won’t mess up the theme when the post title is too long. So if you have any questions be sure to ask them!

Comments 0

Commenting is closed

No Comments Yet