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:

  1. Retrieving Page Number: The code first retrieves the current page number using get_query_var('cpage'), defaulting to 1 if it's not available.
  2. Setting Comments per Page: It sets the number of comments to display per page to 10.
  3. Calculating Offset: The offset is calculated based on the current page number and comments per page, ensuring the correct set of comments is fetched.
  4. Conditional Query Arguments: The $args array 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.
  5. Executing the Query: The WP_Comment_Query object is initialized and the $args are passed to its query() 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.

WP_Comment_Query: Paginating Comments with Offset

原文地址: https://www.cveoy.top/t/topic/owku 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录