PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 8, 2022

[FIXED] Changing the relation in product (or page/post) searches from AND to OR

 February 08, 2022     woocommerce, wordpress     No comments   

Issue

Without using a plugin, I need to change the standard product searches from Woocommerce to be OR and not AND. So when using the search template for products, it must return any products that contain any one of the words typed in. Currently it uses AND, so will not return a products unless it contains all the works in the search string.

add_action('woocommerce_product_query',array($this,'do_stuff')); does not seem to get called at all, but add_action('pre_get_posts',array($this,'do_stuff')); does get called, so I am presuming that's where it will need to be.

My challenge is finding out how to change the 'relation' field on the search terms? Dumping the $query (in pre_get_posts) is not very helpful.

It seems to me this should be a simple task, so I am presuming I am missing something obvious, or not looking for the right thing on google. PS This is for the search functionality on the front end.

Any ideas?


Solution

Hmm, this works, but really seems like a major 'hack' to me =>

<?php
class schsSearch
{
    public function __construct()
    {
        add_filter('posts_search',array($this,'customsearch'), 500, 2);
    }
    function customsearch( $search, $wp_query)
    {
        if (!is_admin()&& isset($_GET['s'])&&strlen($search)>0)
        {
            $a=explode('AND',$search);
            $search="AND".$a[1];
            for ($i=2;$i<count($a);$i++)
            {
                $search.="OR".$a[$i];
            }
        }
        return $search;
    }
}
new schsSearch();
?>

Basically I am just using str_replace to change all instances of "AND' top 'OR' after the first AND in the search string. The FOR loop accommodates the number of words in the search string.

Looking at the source code of wp-includes/class-wp-query.php I do not suspect there would be another way, as the AND seems to be rather hard coded.



Answered By - Gavin Simpson
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing