Search code examples
wordpresscommentsmetaauthor

Wordpress - let post author pick best comment (frontend)


From the front end, I want to allow the author to pick up the best comment/answer of his post. I am close, but not there yet. Every time I click the button, all comments of that post are selected as best (this is wrong). It should only select one comment per post.

In function.php I have the following:

add_action ('comment_post', 'add_comment_field', 1);
function add_comment_field($comment_id) {
    add_comment_meta($comment_id, 'bestanswer', 'no', false);
}

In comment.php I have the following:

<?php
    $current_author = get_the_author_meta('nickname');
    global $current_user; get_currentuserinfo();
    if ($current_user->nickname == $current_author) {
?>
<?php
    $my_post_meta = get_comment_meta($comment->comment_ID, 'bestanswer', true);
    if ( $my_post_meta == 'yes' ) {
            echo '<h4>Best answer</h4>';
        } else {
        ?>
        <form method="post" action="" id="bestanswer-<?php comment_ID() ?>">
            <input type="submit" name="confirm" value="Best Answer" />
        </form>
        <?php   

        if (isset($_POST['confirm'])) {
            update_comment_meta($comment->comment_ID, 'bestanswer', 'yes');
        }

    }
?>

Thoughts? Suggestions? Any help will be appreciated.


Solution

  • I solved this by adding a link to each comment. The link goes to a page that displays that comment. On this page, the author then selects the comment as best answer. Now the comment meta is only saved for that particular comment. I know is an extra step, but I prefer this method since the author has to make sure that that is the comment he wants to pick. Once the comment is selected as best, author cannot change it.