尝试应用这些更改,将此条件添加到// first check if data exists with select query
:
// Do nothing else if the search term is empty.
if ( empty( $search_term ) ) {
return $where;
}
更新:您可能还想检查它是否是主查询,如果不是,请退出函数:
if ( empty( $search_term ) || // missing search term
! $wp_query->is_main_query() ) { // or not the main query
return $where;
}
我不想这样做
SELECT *
(全选)记录使用
$wpdb->get_results()
只是检查数据库中是否存在搜索项的现有条目。其次,你应该使用
$wpdb->prepare()
而不是
TERM = \'".$search_term."\'
. 所以我要替换这个:
$datum = $wpdb->get_results("SELECT * FROM search_product WHERE TERM = \'".$search_term."\'");
if($wpdb->num_rows > 0) {
使用此选项:
$sql = $wpdb->prepare( "SELECT TERM FROM search_product WHERE TERM = %s LIMIT 1", $search_term );
if ( $wpdb->get_var( $sql ) ) {
在这段代码中,您应该没有使用
TERM = \'".$search_term."\'
. 所以我要替换这个:
$sql = $wpdb->prepare(
"UPDATE search_product SET COUNTER = COUNTER + 1 WHERE TERM = \'".$search_term."\'");
使用此选项:
$sql = $wpdb->prepare( "UPDATE search_product SET COUNTER = COUNTER + 1 WHERE TERM = %s", $search_term );
以及
// if not exist in the database then insert it
可以重写为:
else {
$wpdb->insert( \'search_product\', [
\'TERM\' => $search_term,
\'DATE\' => current_time( \'mysql\' ),
// \'COUNTER\' => 1, // <- uncomment if the default value of the column is not 1
] );
}