Load in words, not letters [WordPress/PHP]

I hope someone can help me out.

I’m working on a website where I installed WordPress. On the frontpage I have a small div where I want to output the first 10 words from another page with pageID.
At the moment it’s almost working but instead of loading in 10 words it’s loading in 10 letters.

Read More

Example:
Instead of: Hello my name is Erwin and this is a test
It loads: Hello my nam

What am I doing wrong?

I Use the following php in functions.php:

if(!function_exists('getPageContent'))
{
    function getPageContent($pageId,$num_words)
    {
        if(!is_numeric($pageId))
        {
            return;
        }
        global $wpdb;
        $nsquery = 'SELECT DISTINCT * FROM ' . $wpdb->posts .
        ' WHERE ' . $wpdb->posts . '.ID=' . $pageId;
        $post_data = $wpdb->get_results($nsquery);
        if(!empty($post_data))
        {
            foreach($post_data as $post)
            {
                $text_out=nl2br($post->post_content);
                $text_out=str_replace(']]>', ']]>', $text_out);
                $text_out = strip_tags($text_out);
                return substr($text_out,0,$num_words);

            }
        }
    }}

And I use the following string to load in the content:
(Where 89 is my Page ID)

echo getPageContent(89,10);

Related posts

Leave a Reply

4 comments

  1. This will extract first 10 words of your string

    $text_out = "Hello my name is Erwin and this is a test and this is another test";
    $num_words = 10;
    echo implode(' ', array_slice(explode(' ', $text_out), 0, $num_words));
    

    Output

    Hello my name is Erwin and this is a test
    
  2. Here $num_words = 10

    it means substr breaks the string from character 0 to 10

    if you want whole string then you have to echo

    echo getPageContent(89,32);