Custom request in posts_search

How can I use this query as a custom search query?

add_filter('posts_search', 'my_search_is_perfect', 20, 2); function my_search_is_perfect($search, $wp_query) { $sWord = 'Zukunft haus'; return " SELECT *, MATCH(post_title) AGAINST('$sWord' IN BOOLEAN MODE) AS Score FROM `wp_posts` INNER JOIN wp_term_relationships ON wp_term_relationships.object_id = ID AND wp_term_relationships.term_taxonomy_id = 1 WHERE MATCH( post_title) AGAINST ('$sWord' IN BOOLEAN MODE) AND `post_status` = 'publish' AND `post_type` = 'post' ORDER BY score DESC "; } 

The request is correct (I checked this in phpMyAdmin), but in WordPress I get a message, no results.

+7
php mysql wordpress
source share
3 answers

In function.php file:

 add_filter('posts_search', 'my_search_is_perfect', 20, 2); function my_search_is_perfect() { global $post; global $wpdb; $sWord = 'Zukunft haus'; $sel_query = "SELECT *, MATCH(post_title) AGAINST('$sWord' IN BOOLEAN MODE) AS Score FROM ".$wpdb->prefix."posts INNER JOIN ".$wpdb->prefix."term_relationships ON ".$wpdb->prefix."term_relationships.object_id = ID AND ".$wpdb->prefix."term_relationships.term_taxonomy_id = 1 WHERE MATCH( post_title) AGAINST ('$sWord' IN BOOLEAN MODE) AND post_status = 'publish' AND post_type = 'post' ORDER BY score DESC"; $totaldata = $wpdb->get_results($sel_query); return $totaldata; } 
+5
source share

As suggested by @Gustavo Straube, it would be better to use $ wpdb, in which case you should implement it like this:

 add_filter('posts_search', 'my_search_is_perfect', 20, 2); function my_search_is_perfect() { global $wpdb; $sWord = 'Zukunft haus'; $query = "SELECT *, MATCH(post_title) AGAINST('$sWord' IN BOOLEAN MODE) AS Score FROM `".$wpdb->prefix."_posts` INNER JOIN ".$wpdb->prefix."_term_relationships ON ".$wpdb->prefix."_term_relationships.object_id = ID AND ".$wpdb->prefix."_term_relationships.term_taxonomy_id = 1 WHERE MATCH( post_title) AGAINST ('$sWord' IN BOOLEAN MODE) AND `post_status` = 'publish' AND `post_type` = 'post' ORDER BY score DESC"; $myrows = $wpdb->get_results( $query ); return $myrows; } 

Further information can be found at https://codex.wordpress.org/Class_Reference/wpdb

0
source share

User requests in wordpress are done through $ wpdb. If you are simply using mysql query filters in Wordpress, you may not run the queries to avoid SQL injection. Therefore, to create custom queries, use $ wpdb.

0
source share

All Articles