Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

php - WP add_filter within class constructor does not work

I'm using a basic PHP class to add callbacks to existing WC filters, outside the class the callbacks work as they should, but it seems the filters in the constructor do not call the functions, I tried many variations, but none of them work. This is the class:

class Filters implements FiltersInterface{
    public function __construct()
    {
        add_filter("woocommerce_rest_product_object_query", array($this,'FilterByMeta'),           10,2);
        add_filter("woocommerce_rest_query_var-tax_query",  array($this,'FilterByTaxonomies'),     10,1);
    }

    public function FilterByMeta($args,$request){
        $key = $request->get_param('meta-key');
        if($key!='' && $key!=null)
         {
           $args['meta_key'] = $key;
         }  
         $value = $request->get_param('meta-value');
         if($value!='' && $value!=null)
          {
            $args['meta_value'] = $value;
          }  
       return $args;
    }

    public function FilterByTaxonomies($args){
        var_dump('--');

        $attr_term = $_GET['attribute-term'];
        $attr_name = $_GET['attribute-name'];
    
        if($attr_term!='' && $attr_term!=null && $attr_name!='' && $attr_name!=null)
         {
           $args = array(
             array(
               'taxonomy' => $attr_name,
               'field'    => 'slug',
               'terms'    => $attr_term
             )
           );
           return $args;
          }  
          $cat= $_GET['category'];
          if($cat!='' && $cat!=null)
           {
             $args =  array(
              'relation'            => 'OR',
              array( 
                'taxonomy'          => 'product_cat',
                'field'             => 'slug',
                'terms'             => $cat
              )
            );  
             return $args;     
            }   
         return $args;
    }
 }

And this is in the index.php file i have in my custom 2-file plugin

   include('cfilters.php');

   $filters = new Filters;

I tried using the class name and 'CLASS 'in the add_filter, but it didnt work either

question from:https://stackoverflow.com/questions/65898386/wp-add-filter-within-class-constructor-does-not-work

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem was with the first filter not adding the key for the second one, after initializng the tax query in the first filter, it was working


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...