Wordpress - get_comment_author() returns anonymous

坚强是说给别人听的谎言 提交于 2019-12-12 02:05:52

问题


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:


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.



来源:https://stackoverflow.com/questions/25627526/wordpress-get-comment-author-returns-anonymous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!