Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've the below php to display the content of the post id#9 on my 'home page' of my site, so that whenever the client updates the page, it's reflected on the homepage as well - rather than having to make the change twice.

At the moment all the post content is being shown, I need to strip it down to about 100 words...

Any ideas?

<?php $id=9; $post = get_page($id); $content = apply_filters('the_content', $post->post_content); echo $content;  ?>
share|improve this question
Words or characters? – toscho Nov 21 '12 at 11:02
Words if possible? I've googled it - but all the other solutions seem to be quite chunky. This seems the neatest way of doing it? – V Neal Nov 21 '12 at 11:04

1 Answer

For the excerpt, you can use this function but for the content, it will create problems with the html, so you'll have to handle that yourself

function limit_words($phrase, $len) {
    $len = (int) $len;
    if (str_word_count($phrase) > $len) {
        $keys = array_keys(str_word_count($phrase, 2));
        $phrase = substr($phrase, 0, $keys[$len]);
    }
    return $phrase;
}

The above goes into functions.php. Then you can use it anywhere inside your template files or even your functions.php file. For eg. in a template file

$excerpt = get_the_excerpt();
$new_excerpt = limit_words($excerpt, 10);
// change 10 to the number of words
echo $new_excerpt;
share|improve this answer
Hiya - would that go in the functions file? – V Neal Nov 21 '12 at 11:48
Added an example to the answer above – Mridul Aggarwal Nov 21 '12 at 11:58
Ah i see.. although wouldn't this do a similar job? add_post_type_support( 'page', 'excerpt' ); And yes, the HTML is stripped in both versions - not ideal for what I wanted really. – V Neal Nov 21 '12 at 12:22
that line just tells wordpress that a 'page' can also have an 'excerpt'. – Mridul Aggarwal Nov 21 '12 at 13:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.