【问题标题】:Load in words, not letters [WordPress/PHP]加载文字,而不是字母 [WordPress/PHP]
【发布时间】:2013-04-08 09:41:53
【问题描述】:

希望有人能帮帮我。

我正在一个安装了 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);

【问题讨论】:

    标签: php string wordpress function content-management-system


    【解决方案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
    

    【讨论】:

    • 非常感谢您的快速回答,但这是一个不同的问题。我知道我必须将 10 更改为 32 才能加载前 32 个字母,但我想要的是我可以加载第一个单词。 (因为其他页面中的文字每天都可能不同,我不想一直数字母。我只想让脚本自动加载第一个单词:)
    • 使用strlen函数会自动计算字符串的长度,这里是手册php.net/manual/en/function.strlen.php
    • 所以你只想输出第一个单词?
    • 前 10 个单词作为输出 :)
    • @ErwinvanEkeren 检查我编辑的答案,它将帮助您提取字符串的前 10 个单词
    【解决方案2】:

    How to select first 10 words of a sentence? - 同样的问题。只需使用implode(' ', array_slice(explode(' ', $text_out), 0, $num_words)); 而不是substr($text_out,0,$num_words);

    【讨论】:

    • 结合我上面贴的代码,这是最好最快的解决方案,谢谢!
    【解决方案3】:

    wordpress 有一个功能:

    the_excerpt();
    

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

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

    【讨论】:

    • 感谢您的回答!我也发现了一个,但不知何故我无法将它连接到某个 pageID。它只加载我当前所在页面的前 10 个单词,并且不会从另一个页面输出内容
    • 因为您可能必须加载包含函数或类似内容的文件。
    • 我的php水平比你刚才说的低哈哈!
    【解决方案4】:

    这里$num_words = 10

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

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

    echo getPageContent(89,32);
    

    【讨论】:

      猜你喜欢
      • 2016-01-14
      • 1970-01-01
      • 2013-08-26
      • 2012-03-16
      • 1970-01-01
      • 2021-05-23
      • 2017-02-02
      • 1970-01-01
      • 2019-01-19
      相关资源
      最近更新 更多