我有一个自定义的Select查询,它连接两个表并显示比当前日期早的事件。在我尝试分页之前,一切都很好。
<?php
global $wpdb;
$date = date("Y-m-d");
$querystr = "
SELECT *
FROM wp_posts
JOIN wp_ftcalendar_events ON wp_posts.ID = wp_ftcalendar_events.post_parent
WHERE wp_posts.post_status = \'publish\'
AND wp_posts.post_type = \'post\'
AND wp_ftcalendar_events.start_datetime < \'$date\'
ORDER BY wp_ftcalendar_events.start_datetime DESC
";
$total_record = count($wpdb->get_results($querystr, OBJECT_K));
$paged = get_query_var(\'paged\') ? get_query_var(\'paged\') : 1;
$post_per_page = 3;
$offset = ($paged - 1)*$post_per_page;
$max_num_pages = ceil($total_record/ $post_per_page);
$wp_query->found_posts = $total_record;
$wp_query->max_num_pages = $max_num_pages;
$limit_query = " LIMIT ".$post_per_page." OFFSET ".$offset;
$pageposts = $wpdb->get_results($querystr.$limit_query, OBJECT_K); ?>
<?php if ($pageposts): ?>
<?php global $post; ?>
<?php foreach ($pageposts as $post): ?>
<?php setup_postdata($post); ?>
<!-- do stuff -->
<?php endforeach; ?>
<?php endif; ?>
<?php if(function_exists(\'wp_paginate\')) { wp_paginate(); } ?>
总共有8个帖子。我将$post\\u per\\u page设置为3,但Wordpress在第一页显示2篇文章,在第二页显示2篇文章。第二页上的一篇帖子与第一页上的帖子相同。
例如,当我将post\\u per\\u page设置为6时,第一页上有2篇文章,第二页上有4篇文章。我不知道为什么会这样。
SO网友:th3rion
我找到了解决办法。按ID对重复的帖子进行分组。只需添加此代码即可选择查询:
GROUP BY wp_posts.ID
完整的代码(可能会对某人有所帮助-在internet上使用select query进行分页的示例不多:):
<?php
global $wpdb;
$date = date("Y-m-d");
$querystr = "
SELECT *
FROM wp_posts
JOIN wp_ftcalendar_events ON wp_posts.ID = wp_ftcalendar_events.post_parent
WHERE wp_posts.post_status = \'publish\'
AND wp_posts.post_type = \'post\'
AND wp_ftcalendar_events.start_datetime < \'$date\'
GROUP BY wp_posts.ID
ORDER BY wp_ftcalendar_events.start_datetime DESC
";
$total_record = count($wpdb->get_results($querystr, OBJECT_K));
$paged = get_query_var(\'paged\') ? get_query_var(\'paged\') : 1;
$post_per_page = 3;
$offset = ($paged - 1)*$post_per_page;
$max_num_pages = ceil($total_record/ $post_per_page);
$wp_query->found_posts = $total_record;
$wp_query->max_num_pages = $max_num_pages;
$limit_query = " LIMIT ".$post_per_page." OFFSET ".$offset;
$pageposts = $wpdb->get_results($querystr.$limit_query, OBJECT_K); ?>
<?php if ($pageposts): ?>
<?php global $post; ?>
<?php foreach ($pageposts as $post): ?>
<?php setup_postdata($post); ?>
<!-- do stuff -->
<?php endforeach; ?>
<?php endif; ?>
<?php if(function_exists(\'wp_paginate\')) { wp_paginate(); } ?>