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.
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);
This will extract first 10 words of your string
Output
How to select first 10 words of a sentence? – same question. Just use
implode(' ', array_slice(explode(' ', $text_out), 0, $num_words));
instead ofsubstr($text_out,0,$num_words);
There is a function from wordpress:
which does that exactly. It shows … the excerpt of the article or page and a link at the end. You can customize the length using the argument
the_excerpt($length)
modifiing the function a bit.Source: http://codex.wordpress.org/Function_Reference/the_excerpt
Here
$num_words = 10
it means
substr
breaks the string from character0 to 10
if you want whole string then you have to echo