简体   繁体   中英

how do you change the my-account title “Howdy” text in wordpress admin toolbar

Could someone please explain why the code below does not change the my-account node?

I have tried variations of every tutorial and guide that I can find to change the 'my-account' node text in Wordpress 4.8 and nothing that I do seems to work. I have tried variations of code from these sites (including the code below) on 2 different sites with 2 different themes and the behavior is the same - there is no change to the targeted node(s) in the admin toolbar.

I left a commented out variation that should simply replace the node at the foot of the function in case someone can tell me why that did not work. I've scoured the Wordpress Codex trying to figure this out as well, but to no avail.

I have also tried setting the priority to 999, but that had no affect as well.

    /* --- change the greeting for the admin bar --- */
add_action( 'admin_bar_menu', 'update_admin_bar_user_node', 250 );
function update_admin_bar_user_node( $wp_admin_bar ) {
    $user_id = get_current_user_id();
    $current_user = wp_get_current_user();
    $profile_url = get_edit_profile_url( $user_id );

    if ( ! $user_id )
            return;

    if ( current_user_can( 'read' ) ) {
        $profile_url = get_edit_profile_url( $user_id );
    } elseif ( is_multisite() ) {
        $profile_url = get_dashboard_url( $user_id, 'profile.php' );
    } else {
        $profile_url = false;
    }

    $avatar = get_avatar( $user_id, 26);
    $msgtext = fancy_greeting_text();

    $newtitle = sprintf( __( '%1$s, %2$s' ), $msgtext, '<span class="display-name">' . $current_user->display_name . '</span>' );
    $class    = empty( $avatar ) ? '' : 'with-avatar';

    // remove the current my-account node
    $wp_admin_bar->remove_node( 'my-account' );
    // add the node back with the updates
    $wp_admin_bar->add_node( array( 
        'id'        => 'my-account',
        'parent'    => 'top-secondary',
        'title'     => $newtitle . $avatar,
        'href'      => $profile_url,
        'meta'      => array(
            'class'     => $class,
        ),
    ) );

    // lets go ahead and add the users website to the sub-menu if they have one 
    // will need to rebuild the rest of the user-actions menu if we have to remove the node above
    $my_account = $wp_admin_bar->get_node( 'my-account' );
    if( ! empty( $current_user->user_url ) && $my_account ){
        $wp_admin_bar->add_node( array(
            'parent'    => 'user-actions',
            'id'        => 'user-url',
            'title'     => '<span class="user-url">' . __( 'My Website' ) . '</span>',
            'href'      => esc_url( $current_user->user_url )
        ) );
    }

//      $my_account = $wp_admin_bar->get_node('my-account');
//      $msgtext = fancy_greeting_text();
//      $newtitle = str_replace( 'Howdy', $msgtext, $my_account->title );
//      $args = array(
//          'id'    => 'my-account',
//          'title' => $newtitle,
//      );
//      $wp_admin_bar->add_node( $args );
}

function fancy_greeting_text() {
    //date_default_timezone_set('America/Denver');
    $date = date('d-m');
    $hour = date('G');
    switch($date) {
        case '01-01':
            $message = 'Happy New Year';
            break;
        case '25-12':
            $message = 'Merry Christmas';
            break;
        default:
            //$message = 'Welcome';
            //$message = "Logged in as";
            if ( $hour >= 5 && $hour <= 11 ) {
                $message = "Good morning";
            } else if ( $hour >= 12 && $hour <= 18 ) {
                $message = "Good afternoon";
            } else if ( $hour >= 19 || $hours <= 4 ) {
                $message = "Good evening";
            }
    }
    return $message;
}

So after days of fiddling on and off, I finally figured out what was happening, and while it was something simple-stupid, I took the opportunity to clean up the code just a tad in the process. So the real reason this did not work was a function intended to manipulate the date and time from the client had a curly apostrophe in a section of code that I had pasted from an article elsewhere while trying to figure out how to get the users time to the server to customize the greeting for time of day. It should probably be noted the offending piece of code was BEFORE this function and affecting everything after it.

Ultimately I opted for a simpler and slightly different approach to accomplishing my goals using javascript... the resulting code is posted below.

I also know there are probably areas where this code could be improved, but since I am using an older hosting account, simplicity and backward compatibility are a factor. I also modified the fancy_greeting_text function and kept it as a fallback in the event javascript is disabled on the client or it fails to run for some other reason. The sprintf was changed to wrap the greeting in a span tag so the javascript could later access and change it. Something else that is changed, the line to remove the my-account node was unnecessary, it seemed to have no affect on rendering the toolbar with my desired changes.

Anyway, the updated functions.php code that worked, including the client based Holiday and Time of Day greeting is as follows:

    //-----------------------------------------------------------------------------
/* --- change the greeting for the admin bar --- */
add_action( 'admin_bar_menu', 'update_admin_bar_user_node', 250 );
function update_admin_bar_user_node( $wp_admin_bar ) {
    $user_id = get_current_user_id();
    $current_user = wp_get_current_user();
    $profile_url = get_edit_profile_url( $user_id );

    if ( ! $user_id )
            return;

    if ( current_user_can( 'read' ) ) {
        $profile_url = get_edit_profile_url( $user_id );
    } elseif ( is_multisite() ) {
        $profile_url = get_dashboard_url( $user_id, 'profile.php' );
    } else {
        $profile_url = false;
    }

    $avatar = get_avatar( $user_id, 26);
    $greeting = fancy_greeting_text();
    /* tokens: [%1: greeting text] [%2: current user's display name] */
    $newtitle = sprintf( __( '%1$s, %2$s' ), '<span id="title-greeting" class="greeting">' . $greeting . '</span>', '<span class="display-name">' . $current_user->display_name . '</span>' );
    $class    = empty( $avatar ) ? '' : 'with-avatar';

    // update the node with the changes
    $wp_admin_bar->add_node( array( 
        'id'        => 'my-account',
        'parent'    => 'top-secondary',
        'title'     => $newtitle . $avatar,
        'href'      => $profile_url,
        'meta'      => array(
            'class'     => $class,
        ),
    ) );

    // Add the users website/link to the user-actions sub-menu if they have one 
    $my_account = $wp_admin_bar->get_node( 'my-account' );
    if( ! empty( $current_user->user_url ) && $my_account ){
        $wp_admin_bar->add_node( array(
            'parent'    => 'user-actions',
            'id'        => 'user-url',
            'title'     => '<span class="user-url">' . __( 'My Website' ) . '</span>',
            'href'      => esc_url( $current_user->user_url )
        ) );
    }       
}
function fancy_greeting_text() {
    /* -- greeting message based on server values - fallback -- */
    if ( !date_default_timezone_get() ) {
        //set a default timezone
        date_default_timezone_set('America/Chicago');
    }
    $date = date('d-m');
    $hour = date('G');
    switch($date) {
        case '01-01':
            $message = 'Happy New Year';
            break;
        case '25-12':
            $message = 'Merry Christmas';
            break;
        default:
            $message = 'Welcome';
    }
    //debug//$message.= " (".$hour.")"; // view the hour variable used to determine greeting

    return $message;
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
/* --- Display custom Time of Day Greeting in Wordpress Admin Toolbar --- */
add_action( 'wp_after_admin_bar_render', 'custom_title_greeting', 9999 );
function custom_title_greeting() {
?>
<script type=text/javascript>
var now = new Date();
var mm = now.getMonth()+1;//January is 0!`
var dd = now.getDate();
var hr = now.getHours();
var holidate = dd+'-'+mm;
//console.log('hr->'+hr);
switch (holidate) {
    case '01-01':
        $greeting = 'Happy New Year';
        break;
    case '25-12':
        $greeting = 'Merry Christmas';
        break;
    default:
        if ( hr >= 5 && hr <= 11 ) {
            $greeting = 'Good Morning';
        } else if ( hr >= 12 && hr <= 18 ) {
            $greeting = 'Good Afternoon';
        } else if ( hr >= 19 && hr <= 4 ) {
            $greeting = 'Good Evening';
        } else {
            $greeting = 'Welcome';
        }
}
// update the existing fallback greeting with new client based greeting 
document.getElementById('title-greeting').innerHTML = $greeting;

</script>
<?php
}
//-----------------------------------------------------------------------------

For those who are new to Wordpress, like myself, I should also probably point out that since the admin toolbar is not rendered until near the end of the page itself being rendered, you MUST use the following Wordpress Action Reference (I believe that is the correct term) - wp_after_admin_bar_render - to update the toolbar using javascript from within the functions.php file, otherwise you will get undefined "null" errors as the id title-greeting would not be available in the DOM at the time it is needed if you only used the - admin_bar_menu - action reference.

I'm sure a better commentary could be written, but I think this covers the reasons why it did not work at first and what was done to improve the code, correct the errors and accomplish the desired functionality.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM