Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
An example of how to escape LIKE statements in Wordpress SQL (inside AJAX for context)
add_action( 'wp_ajax_product_search', 'product_search' );
function sku_search() {
global $wpdb;
$searchText = filter_var(trim($_POST['searchText']), FILTER_SANITIZE_STRING);
$sql = "SELECT * FROM wp_posts
WHERE post_title LIKE %s
AND post_type = 'product'";
$resp = $wpdb->get_results(
$wpdb->prepare($sql, '%'.$wpdb->esc_like($searchText).'%')
echo json_encode($resp);
wp_die(); // this is required to terminate immediately and return a proper response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.