WordPress.org

Ready to get started?Download WordPress

Forums

Limit Number of characters in sidebar (6 posts)

  1. colincameron
    Member
    Posted 8 years ago #

    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; ?>

  2. ladydelaluna
    Member
    Posted 8 years ago #

    <dd>"> - for starters, this is invalid code...

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

  3. colincameron
    Member
    Posted 8 years ago #

    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; ?>

  4. Kafkaesqui

    Posted 8 years ago #

    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:
    http://php.net/substr
    http://php.net/strlen

  5. colincameron
    Member
    Posted 8 years ago #

    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!!

  6. silencematters
    Member
    Posted 8 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic