Created
May 30, 2017 19:55
-
-
Save hearvox/5208b747dbf220def1e1e3cc31245fb4 to your computer and use it in GitHub Desktop.
WordPress shortcode to access external database and output data in HTML table.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Shortcode accesses external database and returns data in HTML table. | |
* | |
* Shortcode is: [my-db-data]. | |
* Uses WP class: | |
* @link https://developer.wordpress.org/reference/classes/wpdb/ | |
* Sets transient with db data and 24 hour expiration. | |
* | |
* @return string $data_html HTML table with database data | |
*/ | |
function my_db_data_table() { | |
$db_html = ''; | |
// Get any existing copy of our transient data | |
if ( false === ( $data = get_transient( 'my_data_transient' ) ) ) { | |
/* No transient, so access database and make new transient (uses wpdb class) */ | |
$db_data = new wpdb( | |
'my_db_username', | |
'my_db_password', | |
'my_db_name', | |
'my_db_host' | |
); | |
$data = $data_db->get_results( 'SELECT * FROM `my_db_table_name`.`my_db_column_name`', ARRAY_A ); | |
set_transient( 'my_data_transient', $data, DAY_IN_SECONDS ); | |
} | |
/* Build HTML table */ | |
$data_html .= "<table class=\"table table-bordered table-hover info\"><thead>\n"; | |
$data_html .= "<colgroup>\n<col /><col /><col /><col /><col />\n</colgroup/>\n"; // For 5 cols. | |
$data_html .= "<thead>\n<tr>\n"; | |
/* Build HTML table head (column names) from database keys */ | |
foreach ( $data[0] as $key => $value ) { | |
$data_html .= "<th scope=\"col\">{$key}</th>\n"; | |
} | |
/* Build HTML table cells from database values */ | |
foreach ( $data as $row ) { | |
$data_html .= "<tr>\n"; | |
foreach ( $row as $key => $value ) { | |
$data_html .= "<td>{$value}</td>\n"; | |
} | |
$data_html .= "</tr>\n"; | |
} | |
$data_html .= "</tbody>\n</table>\n"; | |
return $data_html; | |
} | |
add_shortcode('my-db-data', 'my_db_data_table'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment