How to trim the number of returned characters?

Hi all,

We are designing a (wordpress based) website for a client, on which we would like to show all available subpages of a certain parent page; which works fine.

We would like the returned $content to be limited to 70 characters, in stead of the entire text. I understand that PHP uses a “rtrim” function to accomplish this, but I have no idea on how to use this in our code. Is it used in the apply_filters part?

This is the code we use:

<!-- load practice areas -->
<div class="three_col_wide">
    $mypages = get_pages( array( 'child_of' => $post->ID, 'sort_column' => 'post_date', 'sort_order' => 'asc' ) );

    foreach( $mypages as $page ) {        
        $content = $page->post_content;
        if ( ! $content ) // Check for empty page

        $content = apply_filters( 'the_content', $content );
    <div class="column"><h2><?php echo $page->post_title; ?></h2>
    <?php echo $content; ?><p><a href="<?php echo get_page_link( $page->ID ); ?>" class="button"><?php _e('[:nl]meer info[:fr]en lire plus[:en]more info'); ?></a></p></div>

Any help would be greatly appreciated.

For this I’d suggest using the substr() function. It accepts three arguments, the first being the strings content, the second is the start value (number of characters through the content), and the third (optional) is the number of characters to grab. It can be easily applied like so:


$content =  'This is some text.';

echo substr($content, 0, 10); #gets the first 10 characters

#Outputs: This is so

Although that will work, keep in mind that WordPress stores HTML tags too. So you may be grabbing the first 10 characters that includes an opening <p> tag and not a closing tag.

Personally, I think you need to use the Excerpt field in WordPress and pull that field instead of the content, or you need to at least strip all of the tags from the content before grabbing the first 10 characters.

$content = strip_tags(apply_filters( 'the_content', $content ));
$content = substr($content, 0, 10); #gets the first 10 characters 

Another technique can use str_word_count

$content = strip_tags(apply_filters( 'the_content', $content ));
$words = str_word_count($content, 1);
$wordChunks = array_chunk($words, 50); // chunk the words into groups of 50
$first50words = implode(' ', $words[0]); // makes a paragraph of the first 50 words

Thank you so much for the replies. Works great!