WP_Comment_Query: Paginating Comments with Offset
This code snippet demonstrates how to paginate comments using the WP_Comment_Query in WordPress, retrieving 10 comments per page. It utilizes the 'number' and 'offset' parameters in the query to achieve this pagination.
$page_number = get_query_var( 'cpage' ) ? get_query_var( 'cpage' ) : 1;
$comments_per_page = 10;
$offset = ( $page_number - 1 ) * $comments_per_page;
if ( current_user_can( 'manage_options' ) ) {
$args = array(
'post_type' => 'qqproduct',
'post_id' => $pid,
'status' => 'approve',
'number' => $comments_per_page,
'offset' => $offset,
);
} else {
$args = array(
'post_type' => 'qqproduct',
'status' => array( 'approve', 'hold' ),
'number' => $comments_per_page,
'offset' => $offset,
);
}
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
Explanation:
- Retrieving Page Number: The code first retrieves the current page number using
get_query_var('cpage'), defaulting to 1 if it's not available. - Setting Comments per Page: It sets the number of comments to display per page to 10.
- Calculating Offset: The offset is calculated based on the current page number and comments per page, ensuring the correct set of comments is fetched.
- Conditional Query Arguments: The
$argsarray is constructed based on user permissions:- If the user has 'manage_options' capability, it fetches comments with 'approve' status and the given
$pid. - Otherwise, it retrieves comments with 'approve' or 'hold' status.
- If the user has 'manage_options' capability, it fetches comments with 'approve' status and the given
- Executing the Query: The
WP_Comment_Queryobject is initialized and the$argsare passed to itsquery()method to retrieve the comments.
Important Note:
To implement pagination links, use the paginate_comments_links() function in your template. This function will automatically generate the pagination links based on the retrieved comment count.
Example Usage:
// ... (code from above)
// Display the comments
foreach ($comments as $comment) {
// Display comment content
}
// Display pagination links
paginate_comments_links();
This code will ensure that your comments are displayed in a paginated fashion, improving user experience and site performance.
原文地址: https://www.cveoy.top/t/topic/owku 著作权归作者所有。请勿转载和采集!