Wordpress - get_comment_author() returns anonymous

2019-09-07 05:37发布

I have developed a wordpress plugin that inserts a JS script in the head of every page of the site. I am trying to pass a couple variables to the script (in PHP) such as the name, the email, and the website of the author of the comment, when there's a comment.

I have tried to use the get_comment_author(), get_comment_author_url() and get_comment_author_email() but it always returns "Anonymous", even if I just entered a name, website and mail adress when posting a comment.

Here is the code:

add_action('wp_head', 'insert_script');

function insert_script(){


  $name = get_comment_author();
  $website = get_comment_author_url();
  $email = get_comment_author_email();



    echo " <script type='text/javascript'>

                var _gigo= _gigo || {};
                _gigo['firstname'] = '' ;
                _gigo['lastname'] = '".$name."' ;
                _gigo['company'] = '".$website."' ;
                _gigo['email'] = '".$email."' ;
           </script>";
}

Do you know why the functions return an anonymous author and how I could fix it ? Thanks in advance.

1条回答
老娘就宠你
2楼-- · 2019-09-07 05:47

As can be seen on this page, you need to supply an ID to that function, or it needs to be inside the loop. Because neither is true in your case, it returns anonymous.

Description Retrieve the author of the current comment. If the comment has an empty comment_author field, then 'Anonymous' person is assumed. This function is meant to live inside of the WordPress loop.

Usage

<?php $author = get_comment_author( $comment_ID ); ?>

To get comments by post, you can use the get_comments() function. You could use it as follows:

<?php
global $post; // get the current post
$postId = $post->ID; // get the current post ID
$comments = get_comments('post_id=' . $postId); // This gets all comments from current post
?>

You can check the link on how you can use the output that follows.

If this is still unclear, let me know.

查看更多
登录 后发表回答