0

Attempting to write some Javascript for a Wordpress install.

I have this in my header:

<div id="loginWarningRed">
You Must
<a href="#/?edit-account">Log In</a>
To See Pricing
</div>

and then

.logged-in #loginWarningRed {display:none;}

and it's working fine, but I would like to write some Javascript to welcome the user when logged in.

Something like:

if (jQuery('body').hasClass('logged-in')) {
  document.getElementById(loginWarningRed);innerHTML = "Welcome %USER%";
}

However, when I put this snippet in my custom js text-area, nothing happens. I have no error message in the console.

Also, for the record, I have changed css to /*.logged-in {display:none;}*/.

RobBenz
  • 589
  • 1
  • 7
  • 21

2 Answers2

1

You shouldn't use JavaScript for this, but PHP, editing the header template containing <div id="loginWarningRed">:

<div id="loginWarningRed">

    <?php if( is_user_logged_in() ): $current_user = wp_get_current_user(); ?>

        Welcome <?php echo $current_user->user_login; ?>

    <?php else: ?>

        You Must
        <a href="#/?edit-account">Log In</a>
        To See Pricing

    <?php endif; ?>

</div>
d79
  • 3,699
  • 1
  • 22
  • 36
  • Thank you very much, would you mind explaining why I should be using php instead of javascript... just a sentence or two please, thank you very much. – RobBenz Apr 06 '15 at 20:16
  • well one reason is that javascript is client side (that is works on the user browser) and php is server side: in your case you need to retrieve something from the server (the user infos), hence the php. for other reasons please take a look at [this anwer](http://stackoverflow.com/a/6369454/3236352). – d79 Apr 06 '15 at 21:24
  • Thanks again, I want to modify the `if` to change `user_login` to `display_name` if `display_name` exists. that way it wont say "Welcome Jsmith1234" it will say "Welcome John Smith" – RobBenz Apr 07 '15 at 14:45
  • you can use `$current_user->display_name`, so you let the user decide which name to display (setting on user profile), otherwise use `$current_user->user_firstname . ' ' . $current_user->user_lastname`. for more info: [wp_get_current_user](https://codex.wordpress.org/Function_Reference/wp_get_current_user) – d79 Apr 07 '15 at 16:56
0

Considering you are already using jQuery, you can try this:

$('div#loginWarningRed').empty().text('Welcome %USER%')
Touhid Alam
  • 343
  • 1
  • 5
  • thanks, but this didn't work, also the text needs to change for a user who is logged-in vs a user who is not logged-in, Is this suppose to be part of an `if` statement? – RobBenz Apr 06 '15 at 19:47