Halloween Sale 15% off Ends in See the plans
PHP

Post Comments Without Reloading the Page

Submits the comment form in the background and shows the new comment (or the "awaiting moderation" note) right away, instead of reloading the page.

Don’t have WPIDE yet? Install it on your site

Code

add_action( 'wp_ajax_wpide_comment', 'wpide_ajax_comment' );
add_action( 'wp_ajax_nopriv_wpide_comment', 'wpide_ajax_comment' );

function wpide_ajax_comment() {
    $comment = wp_handle_comment_submission( wp_unslash( $_POST ) );

    if ( is_wp_error( $comment ) ) {
        wp_send_json_error( array( 'message' => wp_strip_all_tags( $comment->get_error_message() ) ), 400 );
    }

    $user = wp_get_current_user();
    do_action( 'set_comment_cookies', $comment, $user, ! empty( $_POST['wp-comment-cookies-consent'] ) );

    $approved = '1' === (string) $comment->comment_approved;
    $html     = sprintf(
        '<li id="comment-%1$d" class="comment"><article class="comment-body"><footer class="comment-meta"><b class="fn">%2$s</b></footer><div class="comment-content">%3$s</div>%4$s</article></li>',
        (int) $comment->comment_ID,
        esc_html( get_comment_author( $comment ) ),
        wp_kses_post( wpautop( $comment->comment_content ) ),
        $approved ? '' : '<p class="comment-awaiting-moderation"><em>Your comment is awaiting moderation.</em></p>'
    );

    wp_send_json_success( array( 'html' => $html, 'approved' => $approved ) );
}

add_action( 'wp_footer', function () {
    if ( ! is_singular() || ! comments_open() ) {
        return;
    }
    ?>
<script>
( function () {
    var form = document.getElementById( 'commentform' );
    if ( ! form || ! window.fetch || ! window.FormData ) { return; }
    form.addEventListener( 'submit', function ( event ) {
        event.preventDefault();
        var button = form.querySelector( '[type="submit"]' );
        var data = new FormData( form );
        data.append( 'action', 'wpide_comment' );
        if ( button ) { button.disabled = true; }
        var status = form.querySelector( '.wpide-comment-status' );
        if ( ! status ) { status = document.createElement( 'p' ); status.className = 'wpide-comment-status'; status.setAttribute( 'role', 'status' ); form.appendChild( status ); }
        fetch( <?php echo wp_json_encode( admin_url( 'admin-ajax.php' ) ); ?>, { method: 'POST', body: data, credentials: 'same-origin' } )
            .then( function ( r ) { return r.json(); } )
            .then( function ( res ) {
                if ( ! res.success ) { status.textContent = res.data && res.data.message ? res.data.message : 'Your comment could not be posted.'; return; }
                var list = document.querySelector( '.comment-list, .commentlist, .wp-block-comment-template' );
                if ( list ) { list.insertAdjacentHTML( 'beforeend', res.data.html ); }
                form.reset();
                status.textContent = res.data.approved ? 'Thanks, your comment has been posted.' : 'Thanks, your comment is awaiting moderation.';
            } )
            .catch( function () { form.submit(); } )
            .finally( function () { if ( button ) { button.disabled = false; } } );
    } );
} )();
</script>
    <?php
} );

Notes

Uses WordPress's own comment handling, so spam checks and moderation rules still apply; falls back to the normal form if JavaScript fails.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.