【问题标题】:Wordpress display name string manipulationWordpress 显示名称字符串操作
【发布时间】:2013-08-26 22:15:21
【问题描述】:

我已使用以下函数将显示名称设置为同时显示名字和姓氏。如何操作 LAST NAME 以仅提取该字符串的第一个字母?例如,如果您注册为 John Doe(名字 = John,姓氏 = Doe),我希望您的显示名称为 John D。

谢谢

function force_pretty_displaynames($user_login, $user) {

$outcome = trim(get_user_meta($user->ID, 'first_name', true) . " " . get_user_meta($user->ID, 'last_name', true));
if (!empty($outcome) && ($user->data->display_name!=$outcome)) {
    wp_update_user( array ('ID' => $user->ID, 'display_name' => $outcome));    
}
}
add_action('wp_login','force_pretty_displaynames',10,2); 

【问题讨论】:

    标签: php string wordpress function


    【解决方案1】:

    这就是我使用 PHP 的 substr() 函数解决它的方法:

      $outcome = trim(
    get_user_meta( $user->ID, 'first_name', true ) 
    . ' ' 
    . substr( get_user_meta( $user->ID, 'last_name', true ), 0, 1 )
    . '.'
    );
    

    以上代码感谢 Pat J

    在 wordpress 中显示名字和姓氏首字母的完整代码如下。如果其他人想使用它,请记住将其粘贴到主题的 function.php 文件中

    function force_pretty_displaynames($user_login, $user) {
    
    $outcome = trim(
    get_user_meta( $user->ID, 'first_name', true ) 
    . ' ' 
    . substr( get_user_meta( $user->ID, 'last_name', true ), 0, 1 )
    . '.'
    );
    if (!empty($outcome) && ($user->data->display_name!=$outcome)) {
        wp_update_user( array ('ID' => $user->ID, 'display_name' => $outcome));    
    }
    }
    add_action('wp_login','force_pretty_displaynames',10,2); 
    

    【讨论】:

      【解决方案2】:

      只需从get_user_meta($user->ID, 'last_name', true) 获取第一个字符。您可以将字符串用作字符数组(因为它是字符数组:))所以要获得第一个字符,您将编写$string[0]

      $lastName = (string) get_user_meta($user->ID, 'last_name', true);
      $firstChar = $lastName[0];
      

      【讨论】:

      • Elon 能否通过将您的答案插入我的代码中来澄清一下?当我尝试它时,我得到了致命错误:无法使用 WP_User 类型的对象作为数组。谢谢!
      • 已编辑答案,我认为现在使用该解决方案会很容易;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-23
      • 1970-01-01
      • 2022-12-04
      • 2021-06-02
      • 2015-09-17
      • 2014-08-02
      相关资源
      最近更新 更多