WP-Mix

A fresh mix of code snippets and tutorials

Limit Characters in WordPress Navigation Links

Here is are two jQuery techniques to limit the number of characters in a string, applied to WordPress navigation links.

Limit Characters in Both Nav Links

Add the following to your theme’s JavaScript file (or via settings or whatever):

$('.single-nav a').each(function() {
	n = 20;
	l = $(this).text().length;
	if (l > n) $(this).text($(this).text().substr(0, n) + '...');
});

This assumes that your template code looks like this:

<div class="single-nav">
	<?php previous_post_link(); ?>
	<?php next_post_link(); ?>
</div>

In the jQuery snippet, make sure to change the value of n to the maximum number of characters. You can also change the ellipses, ..., or remove it entirely.

Limit Characters in Either Nav Link

The previous snippet limits characters in both the previous and next navigation tags. To only limit characters in one or the other (or both), consider the following code:

$('.prev a').text($('.prev a').text().substring(0, 50));
$('.next a').text($('.next a').text().substring(0, 50));

This will limit both previous and next links to 50 characters. Edit either 50 to suit your needs. Note that for this snippet to work, we need to add a .prev and .next class to each nav link. Here is one way to do it:

<div class="single-nav">
	<?php previous_post_link('<div class="prev">%link</div>', '« %title'); ?>
	<?php next_post_link('<div class="next">%link</div>', '%title »'); ?>
</div>

These WP tags display nav links for single post views. The same general technique can be used to limit characters for index/archive navigation, just change the tags and done.

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress