Skip to content

Instantly share code, notes, and snippets.

@jmarreros
Last active November 16, 2021 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmarreros/dd8f765d84976b83714a6c1cabd273a9 to your computer and use it in GitHub Desktop.
Save jmarreros/dd8f765d84976b83714a6c1cabd273a9 to your computer and use it in GitHub Desktop.
Muestra los datos de una tabla personalizada en una página de WordPress incluye paginación y búsqueda
<?php //don't copy this line
// Show custom table data in a WordPress specific page
// includes pagination and search
add_filter( 'the_content', 'dcms_list_data' );
function dcms_list_data( $content ) {
$slug_page = 'empleados'; //slug page where show data
$table_name = 'employee'; // custom table name
$items_per_page = 10; // quantity per page
if ( is_page($slug_page) ){
global $wpdb;
$search_condition = '';
$search = $_REQUEST['search']??'';
if ( $search ) $search_condition = "WHERE `first_name` like '%$search%'";
$start_number = $_REQUEST['start']??0;
if ( $start_number < 0 || ! is_numeric( $start_number ) ) $start_number = 0;
// Count items
$sql = "SELECT COUNT(*) FROM `$table_name` $search_condition";
$count = $wpdb->get_var($sql);
// Items
$sql = "SELECT * FROM `$table_name` $search_condition LIMIT $start_number, $items_per_page";
$items = $wpdb->get_results($sql);
$content .= dcms_print_search($search);
$content .= dcms_print_table($items);
$content .= dcms_print_pagination($start_number, $items_per_page, $count, $search);
}
return $content;
}
function dcms_print_search($search){
return '<form method="get">
<input type="search" minlength="2" placeholder="Ingresa el empleado" name="search" value="'.$search.'">
<input type="submit" value="Buscar">
</form>';
}
function dcms_print_table($items){
$result = '';
// field names
foreach ($items as $item) {
$result .= '<tr>
<td>'.$item->id.'</td>
<td>'.$item->first_name.'</td>
<td>'.$item->last_name.'</td>
<td>'.$item->email.'</td>
<td>'.$item->birthdate.'</td>
</tr>';
}
$template = '<table class="table-data">
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Correo</th>
<th>Cumpleaños</th>
</tr>
{data}
</table>';
return str_replace('{data}', $result, $template);
}
function dcms_print_pagination($start_number, $items_per_page, $count, $search){
$navbar = '';
if ( $count > $items_per_page ){
$nav_count = 0;
$page_count = 1;
$str_search = '';
$current_page = $start_number/$items_per_page + 1;
if ( $search ) $str_search = "&search=$search";
while ( $nav_count < $count ) {
if ( $page_count === $current_page ){
$navbar .= "<span>{$page_count}</span> ";
} else {
$navbar .= "<a href='?start={$nav_count}{$str_search}'>{$page_count}</a> ";
}
$nav_count += $items_per_page;
$page_count++;
}
$navbar = "<section>$navbar</section>";
}
return $navbar;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment