1

我希望有人可以帮助我。

我正在一个安装了 Wordpress 的网站上工作。在首页我有一个小 div,我想用 pageID 从另一个页面输出前 10 个单词。目前它几乎可以工作,但不是加载 10 个单词,而是加载 10 个字母。

示例:
而不是:你好,我的名字是 Erwin,这是一个测试
它加载:你好我的名字

我究竟做错了什么?

我在functions.php中使用以下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);

            }
        }
    }}



我使用以下字符串加载内容:(
其中 89 是我的页面 ID)

echo getPageContent(89,10);
4

4 回答 4

1

这将提取字符串的前 10 个单词

$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));

输出

Hello my name is Erwin and this is a test
于 2013-04-08T09:47:53.067 回答
0

wordpress有一个功能:

the_excerpt();

正是这样做的。它显示...文章或页面的摘录以及末尾的链接。您可以使用the_excerpt($length)稍微修改函数的参数来自定义长度。

资料来源:http ://codex.wordpress.org/Function_Reference/the_excerpt

于 2013-04-08T09:51:23.193 回答
0

如何选择句子的前 10 个单词?- 同样的问题。只需使用implode(' ', array_slice(explode(' ', $text_out), 0, $num_words));而不是substr($text_out,0,$num_words);

于 2013-04-08T10:22:02.803 回答
0

这里$num_words = 10

这意味着substr从字符中断开字符串0 to 10

如果你想要整个字符串,那么你必须回显

echo getPageContent(89,32);
于 2013-04-08T10:44:20.863 回答