如何在WordPress中部署代码从PHP MyAdmin数据库获取数据?
解决WordPress展示数据库数据的问题
首先,直接在页面源码里加PHP代码不生效是正常的——WordPress默认禁止在页面/文章的内容区域执行PHP代码,这是出于安全考虑。
至于能不能把代码放到functions.php里?当然可以,但不推荐直接把输出代码丢进去,因为那样你没法控制它在哪个页面展示。更灵活的方式是把你的数据库查询代码封装成一个短代码(Shortcode),这样你可以在任意页面/文章里调用它。
改造你的代码为短代码
把下面的代码添加到当前主题的functions.php文件末尾(修改前记得备份文件!):
function display_database_data() { // 声明全局$wpdb变量,WordPress用来操作数据库的核心类 global $wpdb; // 替换成你实际的数据库表名,注意如果用了WordPress前缀(比如wp_)要加上 $table_name = 'your_database_table_name'; $results = $wpdb->get_results( "SELECT * FROM $table_name"); if(!empty($results)) { // 用变量拼接输出内容,而不是直接echo,短代码需要返回内容而非直接输出 $output = "<table width='100%' border='0'>"; $output .= "<tbody>"; foreach($results as $row){ $userip = $row->user_ip; $output .= "<tr>"; $output .= "<th>ID</th>" . "<td>" . $row->id . "</td>"; $output .= "</tr>"; $output .= "<td colspan='2'><hr size='1'></td>"; $output .= "<tr>"; $output .= "<th>User IP</th>" . "<td>" . $row->user_ip . "</td>"; $output .= "</tr>"; $output .= "<td colspan='2'><hr size='1'></td>"; $output .= "<tr>"; $output .= "<th>Post ID</th>" . "<td>" . $row->post_id . "</td>"; $output .= "</tr>"; $output .= "<td colspan='2'><hr size='1'></td>"; $output .= "<tr>"; $output .= "<th>Time</th>" . "<td>" . $row->time . "</td>"; $output .= "</tr>"; $output .= "<td colspan='2'><hr size='1'></td>"; } $output .= "</tbody>"; $output .= "</table>"; return $output; } else { // 没有数据时的提示 return "<p>No data found in the table.</p>"; } } // 注册短代码,你可以在页面里用[display_database_data]调用 add_shortcode('display_database_data', 'display_database_data');
怎么使用?
- 打开WordPress后台,编辑你想要展示数据的页面。
- 在编辑器里直接输入短代码:
[display_database_data] - 更新页面,前端就能看到你的数据库数据了!
几个重要提示
- 表名替换:一定要把
$table_name改成你实际的数据库表名,比如你的表是wp_user_visits,就写$table_name = 'wp_user_visits';(前缀根据你的WordPress设置来)。 - 安全问题:如果你的表包含敏感数据,记得给页面添加访问限制,比如只有管理员能看。可以在函数开头加上这行代码:
if (!current_user_can('manage_options')) { return "<p>You don't have permission to view this content.</p>"; } - 备份文件:修改
functions.php前一定要备份,万一写错代码可能导致网站无法访问。
内容的提问来源于stack exchange,提问作者Izu
相关产品推荐
相关产品推荐

