最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Add Star Rating Above WordPress Comments & Hide After Rating - Stack Overflow

programmeradmin2浏览0评论

I’m working with a Blocksy child theme and have implemented a star rating system for posts. However, I’m facing an issue where:

I need the star rating to appear above the default WordPress comment form. The rating should be hidden after a user submits a rating, but they should still be able to post unlimited comments. The star rating does not display for logged-in users—it only appears for guests. I have placed my code in the Blocksy child theme’s functions.php file. Everything else works fine, except the issues mentioned above.

If anyone can help me fix this, I’d really appreciate it!

<?php
if (!defined('ABSPATH')) {
    die('Direct access forbidden.');
}

// Enqueue styles and scripts
add_action('wp_enqueue_scripts', function () {
    wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css');
    wp_enqueue_style('font-awesome', '.15.3/css/all.min.css');
    wp_enqueue_script('jquery');

    // Custom script for comment functionality
    wp_enqueue_script('comment-rating-script', get_stylesheet_directory_uri() . '/reviews/reviews.js', array('jquery'), '1.0', true);
    wp_localize_script('comment-rating-script', 'ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('comment_edit_delete_nonce')
    ));
});

// Step 1: Add rating field to comment form
function add_rating_field_to_comment_form($fields) {
    $rating_field = '<p class="comment-form-rating">
        <label for="rating">Rating:</label>
        <span class="rating-stars">
            <input type="radio" id="rating-5" name="rating" value="5" required>
            <label for="rating-5"><i class="fas fa-star"></i></label>
            <input type="radio" id="rating-4" name="rating" value="4">
            <label for="rating-4"><i class="fas fa-star"></i></label>
            <input type="radio" id="rating-3" name="rating" value="3">
            <label for="rating-3"><i class="fas fa-star"></i></label>
            <input type="radio" id="rating-2" name="rating" value="2">
            <label for="rating-2"><i class="fas fa-star"></i></label>
            <input type="radio" id="rating-1" name="rating" value="1">
            <label for="rating-1"><i class="fas fa-star"></i></label>
        </span>
    </p>';
    
    $fields = array_merge(['rating' => $rating_field], $fields);
    return $fields;
}
add_filter('comment_form_fields', 'add_rating_field_to_comment_form');

// Step 2: Save rating data
function save_rating_data($comment_id) {
    if (isset($_POST['rating'])) {
        $rating = intval($_POST['rating']);
        if ($rating >= 1 && $rating <= 5) {
            update_comment_meta($comment_id, 'rating', $rating);
        }
    }
}
add_action('comment_post', 'save_rating_data');

// Step 3: Display rating stars in comments
function display_rating_stars($comment_id) {
    $rating = get_comment_meta($comment_id, 'rating', true);
    if ($rating) {
        $stars = '';
        for ($i = 1; $i <= 5; $i++) {
            if ($i <= $rating) {
                $stars .= '<i class="fas fa-star" style="color: #ffd700;"></i>';
            } else {
                $stars .= '<i class="far fa-star" style="color: #ffd700;"></i>';
            }
        }
        return '<div class="comment-rating">' . $stars . '</div>';
    }
    return '';
}

function add_rating_to_comment($comment_text, $comment) {
    return display_rating_stars($comment->comment_ID) . $comment_text;
}
add_filter('comment_text', 'add_rating_to_comment', 10, 2);

// Include edit and delete functionality
// Step 5: Add edit/delete links to comments
function add_comment_edit_delete_link($comment_text, $comment) {
    // Only show edit/delete for logged in users who authored the comment
    if (is_user_logged_in() && $comment->user_id == get_current_user_id()) {
        $edit_nonce = wp_create_nonce('edit-comment_' . $comment->comment_ID);
        $delete_nonce = wp_create_nonce('delete-comment_' . $comment->comment_ID);
        
        $buttons = '<div class="comment-actions">';
        $buttons .= '<a href="#" class="comment-edit-link" data-comment-id="' . $comment->comment_ID . '">Edit</a> | ';
        $buttons .= '<a href="#" class="comment-delete-link" data-comment-id="' . $comment->comment_ID . '">Delete</a>';
        $buttons .= '</div>';
        
        $comment_text .= $buttons;
    }
    return $comment_text;
}
add_filter('comment_text', 'add_comment_edit_delete_link', 20, 2);

// Step 6: Add JavaScript for edit/delete functionality
function comment_edit_delete_scripts() {
    if (is_singular() && comments_open()) {
        ?>
        <script>
        jQuery(document).ready(function($) {
            // Function to create a modal
            function createModal(content) {
                const modal = document.createElement('div');
                modal.className = 'custom-modal';
                modal.innerHTML = `
                    <div class="modal-content">
                        <span class="close-modal">&times;</span>
                        ${content}
                    </div>
                `;
                document.body.appendChild(modal);
                $(modal).find('.close-modal').on('click', function() {
                    $(modal).remove();
                });
                return modal;
            }

            // Handle Edit Comment
            $(document).on('click', 'ment-edit-link', function(e) {
                e.preventDefault();
                
                const commentId = $(this).data('comment-id');
                const commentElement = document.getElementById('comment-' + commentId);
                const commentContent = $(commentElement).find('ment-content p').text().trim();
                
                const form = `
                    <form id="edit-comment-form">
                        <textarea name="comment" rows="5">${commentContent}</textarea>
                        <p>Rating cannot be changed.</p>
                        <input type="hidden" name="comment_id" value="${commentId}">
                        <input type="hidden" name="action" value="edit_comment">
                        <input type="hidden" name="security" value="${ajax_object.nonce}">
                        <button type="submit" class="button">Save</button>
                        <button type="button" class="close-modal button">Cancel</button>
                    </form>
                `;
                
                const modal = createModal(form);
                
                $(modal).find('#edit-comment-form').on('submit', function(e) {
                    e.preventDefault();
                    
                    const formData = new FormData(this);
                    
                    fetch(ajax_object.ajax_url, {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            $(commentElement).find('ment-content').html(data.datament_content);
                            $(modal).remove();
                        }
                    });
                });
            });

            // Handle Delete Comment
            $(document).on('click', 'ment-delete-link', function(e) {
                e.preventDefault();
                
                const commentId = $(this).data('comment-id');
                
                const confirmBox = `
                    <p>Are you sure you want to delete this comment?</p>
                    <button id="confirm-delete" class="button">Delete</button>
                    <button class="close-modal button">Cancel</button>
                `;
                
                const modal = createModal(confirmBox);
                
                $(modal).find('#confirm-delete').on('click', function() {
                    const formData = new FormData();
                    formData.append('action', 'delete_comment');
                    formData.append('comment_id', commentId);
                    formData.append('security', ajax_object.nonce);
                    
                    fetch(ajax_object.ajax_url, {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            $('#comment-' + commentId).remove();
                            $(modal).remove();
                        }
                    });
                });
            });
        });
        </script>
        <style>
            /* Rating stars styling */
            .rating-stars {
                display: flex;
                flex-direction: row-reverse;
                justify-content: flex-end;
            }
            .rating-stars input {
                display: none;
            }
            .rating-stars label {
                cursor: pointer;
                font-size: 25px;
                padding: 0 5px;
                color: #ddd;
            }
            .rating-stars label:hover,
            .rating-stars label:hover ~ label,
            .rating-stars input:checked ~ label {
                color: #ffd700;
            }
            ment-rating {
                margin-bottom: 10px;
            }
            
            /* Edit/Delete styling */
            ment-actions {
                margin-top: 10px;
                font-size: 0.9em;
            }
            ment-edit-form {
                margin-top: 10px;
            }
            ment-edit-form textarea {
                width: 100%;
                margin-bottom: 10px;
            }
            ment-edit-form button {
                margin-right: 10px;
            }
            
            /* Modal styling */
            .custom-modal {
                position: fixed;
                z-index: 9999;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0,0,0,0.4);
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .modal-content {
                background-color: #fefefe;
                padding: 20px;
                border-radius: 5px;
                width: 80%;
                max-width: 500px;
            }
            .close-modal {
                cursor: pointer;
            }
            #edit-comment-form textarea {
                width: 100%;
                margin-bottom: 10px;
            }
            #edit-comment-form button {
                margin-right: 10px;
            }
        </style>
        <?php
    }
}
add_action('wp_footer', 'comment_edit_delete_scripts');

// Step 7: Handle AJAX requests for comment editing
function handle_edit_comment() {
    check_ajax_referer('comment_edit_delete_nonce', 'security');
    
    $comment_id = isset($_POST['comment_id']) ? intval($_POST['comment_id']) : 0;
    $comment_content = isset($_POST['comment']) ? sanitize_textarea_field($_POST['comment']) : '';
    
    // Check if user can edit this comment
    $comment = get_comment($comment_id);
    
    if (!$comment || $comment->user_id != get_current_user_id()) {
        wp_send_json_error('Permission denied');
    }
    
    // Update the comment
    $comment_data = array(
        'comment_ID' => $comment_id,
        'comment_content' => $comment_content
    );
    
    $updated = wp_update_comment($comment_data);
    
    if ($updated) {
        wp_send_json_success(array(
            'comment_content' => apply_filters('comment_text', $comment_content, $comment)
        ));
    } else {
        wp_send_json_error('Failed to update comment');
    }
}
add_action('wp_ajax_edit_comment', 'handle_edit_comment');

// Step 8: Handle AJAX requests for comment deletion
function handle_delete_comment() {
    check_ajax_referer('comment_edit_delete_nonce', 'security');
    
    $comment_id = isset($_POST['comment_id']) ? intval($_POST['comment_id']) : 0;
    
    // Check if user can delete this comment
    $comment = get_comment($comment_id);
    
    if (!$comment || $comment->user_id != get_current_user_id()) {
        wp_send_json_error('Permission denied');
    }
    
    // Trash the comment
    $deleted = wp_trash_comment($comment_id);
    
    if ($deleted) {
        wp_send_json_success();
    } else {
        wp_send_json_error('Failed to delete comment');
    }
}
add_action('wp_ajax_delete_comment', 'handle_delete_comment');

// Average Rating and Total Reviews Shortcode
function average_rating_shortcode() {
    $args = array(
        'post_id' => get_the_ID(),
        'status' => 'approve',
    );
    $comments = get_comments($args);
    $total_ratings = 0;
    $total_comments = 0;
    
    foreach ($comments as $comment) {
        $rating = get_comment_meta($comment->comment_ID, 'rating', true);
        if ($rating) {
            $total_ratings += $rating;
            $total_comments++;
        }
    }
    
    if ($total_comments > 0) {
        $average_rating = $total_ratings / $total_comments;
        $average_rating = round($average_rating, 1);
        $output = '<span class="average-rating">' . $average_rating . ' <i class="fas fa-star" style="color: #ffd700;"></i> (' . $total_comments . ' ' . _n('review', 'reviews', $total_comments) . ')</span>';
    } else {
        $output = '<span class="average-rating">No ratings yet</span>';
    }
    
    return $output;
}
add_shortcode('average_rating', 'average_rating_shortcode');

// Individual Reviews Shortcode
function individual_reviews_shortcode() {
    $args = array(
        'post_id' => get_the_ID(),
        'status' => 'approve',
    );
    $comments = get_comments($args);
    $output = '';
    
    foreach ($comments as $comment) {
        $rating = get_comment_meta($comment->comment_ID, 'rating', true);
        if ($rating) {
            $output .= '<div class="individual-review">';
            $output .= '<img src="' . get_avatar_url($comment->user_id) . '" alt="' . get_comment_author($comment->comment_ID) . '">';
            $output .= '<span class="review-author">' . get_comment_author($comment->comment_ID) . '</span>';
            $output .= '<span class="review-rating">';
            
            for ($i = 1; $i <= 5; $i++) {
                if ($i <= $rating) {
                    $output .= '<i class="fas fa-star" style="color: #ffd700;"></i>';
                } else {
                    $output .= '<i class="far fa-star" style="color: #ffd700;"></i>';
                }
            }
            
            $output .= '</span>';
            $output .= '<p class="review-content">' . get_comment_text($comment->comment_ID) . '</p>';
            $output .= '</div>';
        }
    }
    
    return $output;
}
add_shortcode('individual_reviews', 'individual_reviews_shortcode');

I tried modifying my Blocksy child theme’s functions.php to add the star rating above the WordPress comment form. I expected it to display properly for all users, disappear after rating while still allowing unlimited comments, and work for both guests and logged-in users.

However, the star rating does not appear for logged-in users. I also attempted using JavaScript and PHP conditions to hide the rating after submission, but it didn't work as expected.

I even tried asking AI to evaluate the code, but no luck. The issue persists, and I need help figuring out what’s wrong.

I’m working with a Blocksy child theme and have implemented a star rating system for posts. However, I’m facing an issue where:

I need the star rating to appear above the default WordPress comment form. The rating should be hidden after a user submits a rating, but they should still be able to post unlimited comments. The star rating does not display for logged-in users—it only appears for guests. I have placed my code in the Blocksy child theme’s functions.php file. Everything else works fine, except the issues mentioned above.

If anyone can help me fix this, I’d really appreciate it!

<?php
if (!defined('ABSPATH')) {
    die('Direct access forbidden.');
}

// Enqueue styles and scripts
add_action('wp_enqueue_scripts', function () {
    wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css');
    wp_enqueue_style('font-awesome', 'https://cdnjs.cloudflare/ajax/libs/font-awesome/5.15.3/css/all.min.css');
    wp_enqueue_script('jquery');

    // Custom script for comment functionality
    wp_enqueue_script('comment-rating-script', get_stylesheet_directory_uri() . '/reviews/reviews.js', array('jquery'), '1.0', true);
    wp_localize_script('comment-rating-script', 'ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('comment_edit_delete_nonce')
    ));
});

// Step 1: Add rating field to comment form
function add_rating_field_to_comment_form($fields) {
    $rating_field = '<p class="comment-form-rating">
        <label for="rating">Rating:</label>
        <span class="rating-stars">
            <input type="radio" id="rating-5" name="rating" value="5" required>
            <label for="rating-5"><i class="fas fa-star"></i></label>
            <input type="radio" id="rating-4" name="rating" value="4">
            <label for="rating-4"><i class="fas fa-star"></i></label>
            <input type="radio" id="rating-3" name="rating" value="3">
            <label for="rating-3"><i class="fas fa-star"></i></label>
            <input type="radio" id="rating-2" name="rating" value="2">
            <label for="rating-2"><i class="fas fa-star"></i></label>
            <input type="radio" id="rating-1" name="rating" value="1">
            <label for="rating-1"><i class="fas fa-star"></i></label>
        </span>
    </p>';
    
    $fields = array_merge(['rating' => $rating_field], $fields);
    return $fields;
}
add_filter('comment_form_fields', 'add_rating_field_to_comment_form');

// Step 2: Save rating data
function save_rating_data($comment_id) {
    if (isset($_POST['rating'])) {
        $rating = intval($_POST['rating']);
        if ($rating >= 1 && $rating <= 5) {
            update_comment_meta($comment_id, 'rating', $rating);
        }
    }
}
add_action('comment_post', 'save_rating_data');

// Step 3: Display rating stars in comments
function display_rating_stars($comment_id) {
    $rating = get_comment_meta($comment_id, 'rating', true);
    if ($rating) {
        $stars = '';
        for ($i = 1; $i <= 5; $i++) {
            if ($i <= $rating) {
                $stars .= '<i class="fas fa-star" style="color: #ffd700;"></i>';
            } else {
                $stars .= '<i class="far fa-star" style="color: #ffd700;"></i>';
            }
        }
        return '<div class="comment-rating">' . $stars . '</div>';
    }
    return '';
}

function add_rating_to_comment($comment_text, $comment) {
    return display_rating_stars($comment->comment_ID) . $comment_text;
}
add_filter('comment_text', 'add_rating_to_comment', 10, 2);

// Include edit and delete functionality
// Step 5: Add edit/delete links to comments
function add_comment_edit_delete_link($comment_text, $comment) {
    // Only show edit/delete for logged in users who authored the comment
    if (is_user_logged_in() && $comment->user_id == get_current_user_id()) {
        $edit_nonce = wp_create_nonce('edit-comment_' . $comment->comment_ID);
        $delete_nonce = wp_create_nonce('delete-comment_' . $comment->comment_ID);
        
        $buttons = '<div class="comment-actions">';
        $buttons .= '<a href="#" class="comment-edit-link" data-comment-id="' . $comment->comment_ID . '">Edit</a> | ';
        $buttons .= '<a href="#" class="comment-delete-link" data-comment-id="' . $comment->comment_ID . '">Delete</a>';
        $buttons .= '</div>';
        
        $comment_text .= $buttons;
    }
    return $comment_text;
}
add_filter('comment_text', 'add_comment_edit_delete_link', 20, 2);

// Step 6: Add JavaScript for edit/delete functionality
function comment_edit_delete_scripts() {
    if (is_singular() && comments_open()) {
        ?>
        <script>
        jQuery(document).ready(function($) {
            // Function to create a modal
            function createModal(content) {
                const modal = document.createElement('div');
                modal.className = 'custom-modal';
                modal.innerHTML = `
                    <div class="modal-content">
                        <span class="close-modal">&times;</span>
                        ${content}
                    </div>
                `;
                document.body.appendChild(modal);
                $(modal).find('.close-modal').on('click', function() {
                    $(modal).remove();
                });
                return modal;
            }

            // Handle Edit Comment
            $(document).on('click', 'ment-edit-link', function(e) {
                e.preventDefault();
                
                const commentId = $(this).data('comment-id');
                const commentElement = document.getElementById('comment-' + commentId);
                const commentContent = $(commentElement).find('ment-content p').text().trim();
                
                const form = `
                    <form id="edit-comment-form">
                        <textarea name="comment" rows="5">${commentContent}</textarea>
                        <p>Rating cannot be changed.</p>
                        <input type="hidden" name="comment_id" value="${commentId}">
                        <input type="hidden" name="action" value="edit_comment">
                        <input type="hidden" name="security" value="${ajax_object.nonce}">
                        <button type="submit" class="button">Save</button>
                        <button type="button" class="close-modal button">Cancel</button>
                    </form>
                `;
                
                const modal = createModal(form);
                
                $(modal).find('#edit-comment-form').on('submit', function(e) {
                    e.preventDefault();
                    
                    const formData = new FormData(this);
                    
                    fetch(ajax_object.ajax_url, {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            $(commentElement).find('ment-content').html(data.datament_content);
                            $(modal).remove();
                        }
                    });
                });
            });

            // Handle Delete Comment
            $(document).on('click', 'ment-delete-link', function(e) {
                e.preventDefault();
                
                const commentId = $(this).data('comment-id');
                
                const confirmBox = `
                    <p>Are you sure you want to delete this comment?</p>
                    <button id="confirm-delete" class="button">Delete</button>
                    <button class="close-modal button">Cancel</button>
                `;
                
                const modal = createModal(confirmBox);
                
                $(modal).find('#confirm-delete').on('click', function() {
                    const formData = new FormData();
                    formData.append('action', 'delete_comment');
                    formData.append('comment_id', commentId);
                    formData.append('security', ajax_object.nonce);
                    
                    fetch(ajax_object.ajax_url, {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            $('#comment-' + commentId).remove();
                            $(modal).remove();
                        }
                    });
                });
            });
        });
        </script>
        <style>
            /* Rating stars styling */
            .rating-stars {
                display: flex;
                flex-direction: row-reverse;
                justify-content: flex-end;
            }
            .rating-stars input {
                display: none;
            }
            .rating-stars label {
                cursor: pointer;
                font-size: 25px;
                padding: 0 5px;
                color: #ddd;
            }
            .rating-stars label:hover,
            .rating-stars label:hover ~ label,
            .rating-stars input:checked ~ label {
                color: #ffd700;
            }
            ment-rating {
                margin-bottom: 10px;
            }
            
            /* Edit/Delete styling */
            ment-actions {
                margin-top: 10px;
                font-size: 0.9em;
            }
            ment-edit-form {
                margin-top: 10px;
            }
            ment-edit-form textarea {
                width: 100%;
                margin-bottom: 10px;
            }
            ment-edit-form button {
                margin-right: 10px;
            }
            
            /* Modal styling */
            .custom-modal {
                position: fixed;
                z-index: 9999;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0,0,0,0.4);
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .modal-content {
                background-color: #fefefe;
                padding: 20px;
                border-radius: 5px;
                width: 80%;
                max-width: 500px;
            }
            .close-modal {
                cursor: pointer;
            }
            #edit-comment-form textarea {
                width: 100%;
                margin-bottom: 10px;
            }
            #edit-comment-form button {
                margin-right: 10px;
            }
        </style>
        <?php
    }
}
add_action('wp_footer', 'comment_edit_delete_scripts');

// Step 7: Handle AJAX requests for comment editing
function handle_edit_comment() {
    check_ajax_referer('comment_edit_delete_nonce', 'security');
    
    $comment_id = isset($_POST['comment_id']) ? intval($_POST['comment_id']) : 0;
    $comment_content = isset($_POST['comment']) ? sanitize_textarea_field($_POST['comment']) : '';
    
    // Check if user can edit this comment
    $comment = get_comment($comment_id);
    
    if (!$comment || $comment->user_id != get_current_user_id()) {
        wp_send_json_error('Permission denied');
    }
    
    // Update the comment
    $comment_data = array(
        'comment_ID' => $comment_id,
        'comment_content' => $comment_content
    );
    
    $updated = wp_update_comment($comment_data);
    
    if ($updated) {
        wp_send_json_success(array(
            'comment_content' => apply_filters('comment_text', $comment_content, $comment)
        ));
    } else {
        wp_send_json_error('Failed to update comment');
    }
}
add_action('wp_ajax_edit_comment', 'handle_edit_comment');

// Step 8: Handle AJAX requests for comment deletion
function handle_delete_comment() {
    check_ajax_referer('comment_edit_delete_nonce', 'security');
    
    $comment_id = isset($_POST['comment_id']) ? intval($_POST['comment_id']) : 0;
    
    // Check if user can delete this comment
    $comment = get_comment($comment_id);
    
    if (!$comment || $comment->user_id != get_current_user_id()) {
        wp_send_json_error('Permission denied');
    }
    
    // Trash the comment
    $deleted = wp_trash_comment($comment_id);
    
    if ($deleted) {
        wp_send_json_success();
    } else {
        wp_send_json_error('Failed to delete comment');
    }
}
add_action('wp_ajax_delete_comment', 'handle_delete_comment');

// Average Rating and Total Reviews Shortcode
function average_rating_shortcode() {
    $args = array(
        'post_id' => get_the_ID(),
        'status' => 'approve',
    );
    $comments = get_comments($args);
    $total_ratings = 0;
    $total_comments = 0;
    
    foreach ($comments as $comment) {
        $rating = get_comment_meta($comment->comment_ID, 'rating', true);
        if ($rating) {
            $total_ratings += $rating;
            $total_comments++;
        }
    }
    
    if ($total_comments > 0) {
        $average_rating = $total_ratings / $total_comments;
        $average_rating = round($average_rating, 1);
        $output = '<span class="average-rating">' . $average_rating . ' <i class="fas fa-star" style="color: #ffd700;"></i> (' . $total_comments . ' ' . _n('review', 'reviews', $total_comments) . ')</span>';
    } else {
        $output = '<span class="average-rating">No ratings yet</span>';
    }
    
    return $output;
}
add_shortcode('average_rating', 'average_rating_shortcode');

// Individual Reviews Shortcode
function individual_reviews_shortcode() {
    $args = array(
        'post_id' => get_the_ID(),
        'status' => 'approve',
    );
    $comments = get_comments($args);
    $output = '';
    
    foreach ($comments as $comment) {
        $rating = get_comment_meta($comment->comment_ID, 'rating', true);
        if ($rating) {
            $output .= '<div class="individual-review">';
            $output .= '<img src="' . get_avatar_url($comment->user_id) . '" alt="' . get_comment_author($comment->comment_ID) . '">';
            $output .= '<span class="review-author">' . get_comment_author($comment->comment_ID) . '</span>';
            $output .= '<span class="review-rating">';
            
            for ($i = 1; $i <= 5; $i++) {
                if ($i <= $rating) {
                    $output .= '<i class="fas fa-star" style="color: #ffd700;"></i>';
                } else {
                    $output .= '<i class="far fa-star" style="color: #ffd700;"></i>';
                }
            }
            
            $output .= '</span>';
            $output .= '<p class="review-content">' . get_comment_text($comment->comment_ID) . '</p>';
            $output .= '</div>';
        }
    }
    
    return $output;
}
add_shortcode('individual_reviews', 'individual_reviews_shortcode');

I tried modifying my Blocksy child theme’s functions.php to add the star rating above the WordPress comment form. I expected it to display properly for all users, disappear after rating while still allowing unlimited comments, and work for both guests and logged-in users.

However, the star rating does not appear for logged-in users. I also attempted using JavaScript and PHP conditions to hide the rating after submission, but it didn't work as expected.

I even tried asking AI to evaluate the code, but no luck. The issue persists, and I need help figuring out what’s wrong.

Share Improve this question asked Mar 15 at 17:25 Heart Of ChindianapolisHeart Of Chindianapolis 111 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

I think your current logic doesn't track whether the user has already rated. To fix this, use a cookie for guest users and a custom user meta field for logged-in users.

A solution can be like this:

// Check user is rated
function user_already_rated() {
    if (is_user_logged_in()) {
        return get_user_meta(get_current_user_id(), 'user_has_rated_' . get_the_ID(), true);
    } else {
        return isset($_COOKIE['rated_post_' . get_the_ID()]);
    }
}

// Hide rating if user rated
add_filter('comment_form_fields', function($fields) {
    if (user_already_rated()) {
        unset($fields['rating']);
    }
    return $fields;
});

// After submit a rating, set cookie
add_action('comment_post', function($comment_id) {
    if (!empty($_POST['rating'])) {
        if (is_user_logged_in()) {
            update_user_meta(get_current_user_id(), 'user_has_rated_' . get_the_ID(), true);
        } else {
            setcookie('rated_post_' . get_the_ID(), 'true', time() + (86400 * 365), COOKIEPATH, COOKIE_DOMAIN);
        }
    }
});

the above code displays the rating form only once per user (logged-in or guest) and hides it afterward, but allows unlimited comments.

发布评论

评论列表(0)

  1. 暂无评论