comment_form() generates the wrong action url

By default WordPress organizes the comment pages from oldest to newest. This does not change, even if the Settings-Discussion options have been modified. This is the sticking point, one might suspect changing these settings to reorganize the comment pages, it doesn’t. These settings, basically, define comment order in the default comment loop, and what page is displayed when $cpage is empty.

To be clear, when $cpage is empty that means you’re on the Post URL and not a comment page within that post.

This means, the problem isn’t in getting the links, since that code is not dynamic. The problem is in how comments are displayed. There are two options 'default_comments_page' and 'comment_order' each has two settings, which makes for four configurations. Each needs a unique offset calculation. In this code below you can see the offset calculations necessary to display the correct comments on the correct pages.

function grab_comments( $remainder, $page_total){
    global $cpage;
    $per_page = get_option('comments_per_page');
    $order_asc = get_option('comment_order') == 'asc';
    $order = $order_asc ? 'ASC' : 'DESC'; //Affects the offset

    if( get_option('default_comments_page') == 'newest' )
    {
        if ($cpage == '') $cpage = $page_total;

        if (get_option('comment_order') == 'desc')
        {
            // ; 8,7,6; 5,4,3; 2,1,0
            $offset = ( $page_total - $cpage ) * $per_page;
        }
        else
        {
            // ; 6,7,8; 3,4,5; 0,1,2
            $offset = ( ( $cpage - 1 ) * $per_page ) - ( $per_page - $remainder );
            if($offset < 0){
                $offset = 0;
                $per_page = $remainder != 0 ? $remainder : $per_page;
            }
        }
    }
    else // default page: 'oldest'
    {
        if ($cpage == '') $cpage = 1;

        if (get_option('comment_order') == 'asc')
        {
            // 0,1,2; 3,4,5; 6,7,8;
            $offset = ( $cpage - 1 ) * $per_page;
        }
        else
        {
            // 2,1,0; 5,4,3; 8,7,6;
            $offset = ( ( $page_total - $cpage ) * $per_page ) - ($per_page - $remainder);
            if($offset < 0){
                $offset = 0;
                $per_page = $remainder != 0 ? $remainder : $per_page;
            }
        }
    }
    $args = array(
        'post_id' => get_the_id()
        , 'number' => $per_page
        , 'offset' => $offset
        , 'order' => $order);
    return get_comments($args);
}

Leave a Comment