【问题标题】:How to display the first character from a WordPress title如何显示 WordPress 标题的第一个字符
【发布时间】:2019-08-01 03:45:45
【问题描述】:

在 WordPress 中,我们使用代码 <?php the_title(); ?> 来显示帖子的标题。现在,我只想在不同的地方显示标题的第一个字母。我该怎么做?

这个我试过了,还是不行:

<?php $my_title = the_title(); ?>

<?php
    $first_char = $my_title[0];
    echo $first_char;
?>

【问题讨论】:

    标签: php wordpress string substr


    【解决方案1】:

    你可以这样做:

    <?php echo get_the_title()[0]; ?>
    

    只要标题不为空。或者:

     <?php echo substr(get_the_title(),0,1); ?>
    
     <?php echo preg_replace('/^(\w).+/','\1',get_the_title()); ?>
    
     <?php echo str_split(get_the_title())[0]; ?>
    
     <?php printf("%.1s", get_the_title()); ?> //echo sprintf
    

    等等……

    或者如果你想变得复杂,你可以使用“流”耶!:

       $f = fopen('php://memory', 'w+');
       fputs($f, get_the_title());
       rewind($f);
       echo fgetc($f);
       fclose($f);
    

    哈哈——这是我能想到的最难的方法,它做了它应该做的事情并且没有任何不必要的步骤(好吧,除了fclose,但在这种情况下我们可以恢复内存);

    Sandbox

    【讨论】:

    • 我最喜欢你的第一个建议,如果你这样做,它仍然可以使用空标题(在 php7+ 中):get_the_title()[0] ?? ''
    【解决方案2】:
    // Get the first character.
    // $firstCharacter = $string[0];
    
    $my_title = get_the_title();
    
    
    // Get the first character using substr.
    $firstCharacter = substr($my_title, 0, 1);
    echo $firstCharacter;
    

    如果 echo 参数未设置为 false,the_title() 函数将默认打印它。 get_the_title() 将检索标题。

    【讨论】:

    • 你把简单的事情复杂化了。更不用说OP的代码应该可以工作
    • @MarcinOrlowski the_title() 函数将默认打印它,如果 echo 参数未设置为 false。 get_the_title() 将检索标题。
    • 我说的是使用 substr() instrad {x} 和 3 行代码来实现真正的 oneliner。
    • @MarcinOrlowski - 我也是这么想的,直到我意识到 the_title() 是那些回显它的输出而不是返回它的 wordpress 函数之一。
    • @DebanjanB 用描述更新了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    相关资源
    最近更新 更多