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

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