Skip to content

Instantly share code, notes, and snippets.

@jmarreros
Last active February 1, 2022 15:47
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/23b2dd205cb478c2e9186f6be718c201 to your computer and use it in GitHub Desktop.
Save jmarreros/23b2dd205cb478c2e9186f6be718c201 to your computer and use it in GitHub Desktop.
Búsqueda en una tabla personalizada de WordPress usando un Shortcode
<?php // No copiar esta línea
// ShortCode
add_action( 'init', 'dcms_frm_shortcode' );
function dcms_frm_shortcode(){
add_shortcode('search-form', 'dcms_search_form');
}
function dcms_search_form( $atts , $content ){
global $wpdb;
$search = $_GET['search']??'';
$table_name = 'customers';
$field_search1 = 'customerNumber';
$field_search2 = 'customerName';
if ( $search ){
$sql = "SELECT * FROM {$table_name}
WHERE {$field_search1} = '{$search}' OR $field_search2 LIKE '%{$search}%'";
$items = $wpdb->get_results($sql);
}
?>
<form>
<input type="search" name="search" id="name" placeholder="Buscar..." value="<?= $search ?>" required>
<input type="submit" value="Buscar">
</form>
<?php if ( $items ): ?>
<table class="custom-table">
<tr>
<th>Número</th>
<th>Nombre</th>
<th>Tel</th>
<th>Dirección</th>
<th>País</th>
<th>Crédito</th>
</tr>
<?php foreach($items as $item): ?>
<tr>
<td><?= $item->customerNumber ?></td>
<td><?= $item->customerName ?></td>
<td><?= $item->phone ?></td>
<td><?= $item->addressLine1 ?></td>
<td><?= $item->city ?></td>
<td><?= $item->creditLimit ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php elseif ( $search ): ?>
<div><strong>No se encontraron resultados</strong></div>
<?php endif;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment