WordPress.org

Ready to get started?Download WordPress

Forums

show only the first 30 words in the_content() (5 posts)

  1. yonthebeach
    Member
    Posted 7 years ago #

    Hi,

    how can i show the first 30 words within the_content(); ?

    i have tried to wirte it in a variable and then cut it but thats not possible. can someone helpl?

    thanks
    yavuz

  2. koeln
    Member
    Posted 7 years ago #

    show me your cut-code

  3. yonthebeach
    Member
    Posted 7 years ago #

    ok here it is:

    <?php
    function getWords($text, $limit)
    {
    $array = explode(" ", $text, $limit+1);

    if (count($array) > $limit)
    {
    unset($array[$limit]);
    }
    return implode(" ", $array);
    }
    ?>

  4. yonthebeach
    Member
    Posted 7 years ago #

    when i use it like this:

    <?php
    $text = "Dies ist ein Text mit fünfzehn Wörtern, von dem wir die ersten vier haben wollen.";

    echo getWords($text, 4);
    ?>

    it works fine, but when i use it like this:

    <?php
    $mycontent = the_content();
    echo getWords($mycontent, 4);
    ?>

    it doesn't work!

    thanks
    yavuz

  5. Kafkaesqui

    Posted 7 years ago #

    <?php
    $mycontent = get_the_content();
    echo getWords($mycontent, 4);
    ?>

    the_content() just echoes, whereas get_the_content() allows you to pass the post content to a variable. Also note that no text formatting occurs within get_the_content(), so if you don't like the 'raw' output, try this:

    <?php
    $mycontent = getWords(get_the_content(), 4);
    echo apply_filters('the_content', $mycontent);
    ?>

    Final warning: HTML elements can cause problems when excerpting post content, in that there's no way (using the code above) to verify a tag has been closed within your cut.

Topic Closed

This topic has been closed to new replies.

About this Topic