📅  最后修改于: 2023-12-03 14:48:32.847000             🧑  作者: Mango
WordPress是一个广泛应用的内容管理系统(CMS)和博客平台,它使用PHP语言编写,提供了很多插件以扩展其功能。本文主要讲解如何使用PHP来查询WordPress中热门的帖子。
要查询WordPress中的热门帖子,需要先在WordPress中启用“热门帖子”插件。然后,需要知道WordPress网站的数据库信息,包括数据库名称、用户名、密码、数据库主机等等。
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($db->connect_error) {
die("无法连接到数据库: " . $db->connect_error);
}
SELECT wp_posts.ID, wp_posts.post_title, wp_posts.post_content, wp_posts.post_type, COUNT(*)
FROM wp_posts
INNER JOIN wp_postmeta ON wp_postmeta.post_id = wp_posts.ID
INNER JOIN wp_comments ON wp_comments.comment_post_ID = wp_posts.ID
WHERE wp_posts.post_type = 'post'
AND wp_comments.comment_approved = 1
AND wp_postmeta.meta_key = 'views'
GROUP BY wp_posts.ID
ORDER BY COUNT(*) DESC
LIMIT 10
上面的查询语句会返回前10篇热门的文章,在代码中,可以将它封装在一个函数中:
function get_popular_posts($db, $limit = 10) {
$sql = "SELECT wp_posts.ID, wp_posts.post_title, wp_posts.post_content, wp_posts.post_type, COUNT(*)
FROM wp_posts
INNER JOIN wp_postmeta ON wp_postmeta.post_id = wp_posts.ID
INNER JOIN wp_comments ON wp_comments.comment_post_ID = wp_posts.ID
WHERE wp_posts.post_type = 'post'
AND wp_comments.comment_approved = 1
AND wp_postmeta.meta_key = 'views'
GROUP BY wp_posts.ID
ORDER BY COUNT(*) DESC
LIMIT $limit";
$result = $db->query($sql);
return $result->fetch_all(MYSQLI_ASSOC);
}
$popular_posts = get_popular_posts($db);
foreach ($popular_posts as $post) {
$title = $post['post_title'];
$content = apply_filters('the_content', $post['post_content']);
$views = get_post_meta($post['ID'], 'views', true);
echo "<h2>$title</h2>";
echo "<p>$content</p>";
echo "<p>阅读量:$views</p>";
}