• I am using get_posts to list the last few entries i have made. Some title are longer than the width of my sidebar and id like to limit the number of characters. Is there a way to do this easily with php?

    this is my code so far:

    <dt>Recent Entries</dt>
    <?php $posts = get_posts('numberposts=5&offset=0'); foreach($posts as $post) : ?>
    <dd><a>"><?php the_title(); ?></a></dd>
    <?php endforeach; ?>

Viewing 5 replies - 1 through 5 (of 5 total)
  • <dd>"> – for starters, this is invalid code…

    please use backticks ( ` ) to enclose the code so we can see it properly.

    Thread Starter colincameron

    (@colincameron)

    Sorry about that. The invalid code isnt on my site, it must have been added because I forgot the backticks.

    <?php $posts = get_posts('numberposts=5&offset=0'); foreach($posts as $post) : ?>
    <dd><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></dd>
    <?php endforeach; ?>

    Try this as a replacement to your title line:

    <dd><a href="<?php the_permalink(); ?>"><?php echo substr(get_the_title(), 0, 20); ?></a></dd>

    Change 20 to the number of characters in the title you want to display. A bit more complicated version adds “…” if more than 20 (or whatever):

    <dd><a href="<?php the_permalink(); ?>"><?php echo substr(get_the_title(), 0, 20); if(strlen(get_the_title()) > 20) echo '...'; ?></a></dd>

    Info links:
    https://php.net/substr
    https://php.net/strlen

    Thread Starter colincameron

    (@colincameron)

    Great this is exactly what I was looking for but when I looked at the substr function I wasn’t sure it would work like this. Thanks!!

    Wow,.. I just wated to say thank you as well! This is Awesome!

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Limit Number of characters in sidebar’ is closed to new replies.