Skip to content

Instantly share code, notes, and snippets.

@ka215
Last active June 25, 2016 07:36
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 ka215/e3b97bae49056e5e827efb6358b35e68 to your computer and use it in GitHub Desktop.
Save ka215/e3b97bae49056e5e827efb6358b35e68 to your computer and use it in GitHub Desktop.
This example of filter hook is for rendering dynamically the shortcode by using that search value after searching at the frontend.
<?php
/**
* The markup content of frontend (as post content):
* ---
* <form method="get">
* <input type="search" name="search_keyword" value="">
* <button type="submit">Search</button>
* </form>
* [cdbt-view table="your_table_name" narrow_keyword="ID:0"]
* ---
*/
function filter_after_user_search( $sql, $table_name, $sql_clauses ){
$target_tables = [ 'your_table_name' ];
$search_target_columns = [ 'zipcode', 'prefecture', 'address' ]; // The columns that you want to search
if ( in_array( $table_name, $target_tables ) && isset( $_GET['search_keyword'] ) && ! empty( $_GET['search_keyword'] ) ) {
$_where_conditions = [];
foreach ( $search_target_columns as $_col ) {
$pdo = new PDO( 'mysql:host='. DB_HOST .';dbname='. DB_NAME, DB_USER, DB_PASSWORD ); // This security code must be!
$_where_conditions[] = sprintf( "`%s`=%s", $_col, $pdo->quote( trim( $_GET['search_keyword'] ) ) );
}
$where_clause = 'WHERE ' . implode( ' OR ', $_where_conditions );
$_new_sql = <<< SQL
SELECT %s
FROM %s
%s
%s %s
SQL;
$sql = sprintf( $_new_sql, $sql_clauses[0], $table_name, $where_clause, $sql_clauses[2], $sql_clauses[3] );
}
return $sql;
}
add_filter( 'cdbt_crud_get_data_sql', 'filter_after_user_search', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment