[resolved] How to get the comment authors name. (5 posts)

  1. BloggerDesign
    Posted 7 years ago #


    What I'd like to do is get the comment authors name and be able to re-use it in PHP.

    Here is a simple example:

    $filenameauthor = comment_author();
    echo "-".$filenameauthor."-";

    Desired outcome: -Thomas-
    Actual outcome: Thomas--

    What's happening the comment_author() is not returning a name, but rather running an function that doesn't allow the comment author name to be associated with $filenameauthor.

    Any ideas how I can get the desired outcome?


  2. Adam Brown
    Posted 7 years ago #

    comment_author does not return the name of the comment author, it prints it to the screen.

    If you're not sure about the difference between returning and echoing, check the functions section in this: php tutorial.

    Put something like this in your theme's functions.php:

    function hyphens_around_author($author){
      return "-{$author}-";
    add_filter('comment_author', 'hyphens_around_author');
  3. BloggerDesign
    Posted 7 years ago #

    Thanks adamrbrown

    That worked, but it did to much.

    My goal in all this is to extract the author name and use it to pull an image.

    What I need to do is pull the authors name and put it in a variable so that I can put it in code like:
    <img src="/images/<? echo $authorname; ?>.jpg">

    Your code worked, but it modified an existing function and I don't want to do that.

    Does that help describe what I'm looking for?


  4. BloggerDesign
    Posted 7 years ago #

    I think found it. I needed to use get_comment_author not comment_author.


  5. Adam Brown
    Posted 7 years ago #

    That works too, but if you've got any existing plugins that hook into the comment_author filter, they won't work anymore, FYI.


    it modified an existing function

    No, it didn't. It created a brand-new function, then it plugged it in using WP's comment_author hook. This is generally the best way to do the sort of thing you want to do.

Topic Closed

This topic has been closed to new replies.

About this Topic