【发布时间】:2018-10-04 07:00:50
【问题描述】:
我正在为 WordPress 开发我的简单插件。这个插件应该计算所有用户的帖子并将它们打印在表格中。但我有一个问题。我使用 for 循环从 MySQL 获取数据,然后将其放入 $result 数组。然后我使用 foreach 循环在 HTML 表中打印它们。它不能正常工作,因为only 1 (last) record 打印在表中(应该是6 条记录)。你有什么想法?提前致谢。
global $wpdb;
$result = count_users();
$total_users = $result['total_users'];
for($id = 1;$id<=$total_users;$id++){ //there is 6 users i database
$result = $wpdb->get_results("SELECT wp_users.ID, wp_users.display_name, COUNT(wp_posts.post_author) AS 'Number_of_posts' FROM wp_users INNER JOIN wp_posts ON wp_users.ID = wp_posts.post_author WHERE wp_posts.post_type = 'post' AND wp_users.ID = $id AND wp_posts.post_status = 'publish'" , ARRAY_A);
};
echo '<table>';
foreach ($result as $x){
echo'<tr>';
// only one is printed
echo'<td>'.'ID: '. $x['ID']."</td>";
echo'<td>'.'User : '. $x['display_name'].'</td>';
echo'<td>'.'Number of posts :'. $x['Number_of_posts'].'</td>';
echo'</tr>';
}
echo '</table>';
echo '<br>';
【问题讨论】:
-
$result 应该排列并在赋值时将其用作 $result[]
-
我只会使用
get_users()和query_posts( 'author=' . $theauthorid ); -
另外,您的 id 仅从 (int)1 变为 (int)6 - 如果用户已被删除等 - 它会扭曲您的 MySQL
标签: php mysql wordpress plugins