How can I limit the length of the previous/next posts in my WordPress Theme?

I am using the following code to show next/previous posts in my wordpress theme.

<?php
previous_post_link('<span class="left">&larr; %link</span>');
next_post_link('<span class="right">%link &rarr;</span>'); ?> 

It’s working but I want to limit the post title which is displayed in the link to a specific length because too big links don’t work because of the space I have.
And I want to have the arrow within the link so that it shows link and arrow with the same style. Is that possible aswell?

Thank you!

3 Answers
3

Here’s a little coding that should implement this for you:

<?php $max_length = 5; // set max character length here

$next = get_next_post()->ID;
$prev = get_previous_post()->ID;

if( $prev ) {
    $title = get_the_title( $prev );
    $link = get_the_permalink( $prev );
    $post_name = mb_strlen( $title ) > $max_length ? mb_substr( $title, 0, $max_length ) . ' ..' : $title;
    ?>
        <span class="left">
            <a href="https://wordpress.stackexchange.com/questions/227542/<?php echo $link; ?>" rel="prev" title="<?php echo $title; ?>">&larr; <?php echo $post_name; ?></a>
        </span>
    <?php
}
if( $next ) {
    $title = get_the_title( $next );
    $link = get_the_permalink( $next );
    $post_name = mb_strlen( $title ) > $max_length ? mb_substr( $title, 0, $max_length ) . ' ..' : $title;
    ?>
        <span class="right">
            <a href="https://wordpress.stackexchange.com/questions/227542/<?php echo $link; ?>" rel="next" title="<?php echo $title; ?>"><?php echo $post_name; ?> &rarr;</a>
        </span>
    <?php
} ?>

Hope that helps in your template.

Edit: small fix so this could work with multibyte characters. (mb_strlen – mb_substr)

Leave a Comment