Created
June 15, 2016 03:46
-
-
Save ka215/4d82f74a74f0c3b169ecd68f7b7ed5f8 to your computer and use it in GitHub Desktop.
This example of filter hook is in which to narrow down the data by a plurality of conditions to the values stored in one column. This code should be inserted to as like "functions.php" in your theme.
This file contains 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 | |
// In the variables of "$target_tables", "$narrow_column", "$narrow_keywords", you should be optimized by your environment and project. | |
function custom_filter_sql( $sql, $table_name, $sql_clauses ) { | |
$target_tables = [ 'your_table_name' ]; | |
$narrow_column = 'specific_column_name'; | |
$narrow_keywords = [ 'keyword1', 'keyword2', 'keyword3' ]; | |
if ( in_array( $table_name, $target_tables ) ) { | |
if ( is_array( $sql_clauses[1] ) ) { | |
// Narrowing is find_data() | |
$_add_query = "AND `". $narrow_column ."` IN ('". implode( "','", $narrow_keywords ) ."')"; | |
foreach ( $sql_clauses[1] as $_i => $_union_query ) { | |
$_before_query = function_exists( 'mb_substr' ) ? mb_substr( $_union_query, 0, -1 ) : substr( $_union_query, 0, -1 ); | |
$sql_clauses[1][$_i] = $_before_query . $_add_query . ')'; | |
} | |
$sql = implode( ' ', $sql_clauses[1] ) .' '. $sql_clauses[2] .' '. $sql_clauses[3]; | |
} else { | |
// Narrowing is get_data() | |
$_new_sql = <<<SQL | |
SELECT %s | |
FROM %s | |
%s | |
%s %s | |
SQL; | |
$_add_query = "`". $narrow_column ."` IN ('". implode( "','", $narrow_keywords ) ."')"; | |
$_where_clause = empty( $sql_clauses[1] ) ? 'WHERE '. $_add_query : $sql_clauses[1] .'AND '. $_add_query; | |
$sql = sprintf( $_new_sql, $sql_clauses[0], $table_name, $_where_clause, $sql_clauses[2], $sql_clauses[3] ); | |
} | |
} | |
return $sql; | |
} | |
add_filter( 'cdbt_crud_find_data_sql', 'custom_filter_sql', 10, 3 ); | |
add_filter( 'cdbt_crud_get_data_sql', 'custom_filter_sql', 10, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment