OiO.lk Blog PHP The post filtering in child-category does not work
PHP

The post filtering in child-category does not work


The post filtering in child-category does not work in WordPress

/category/child-category-1/filter_xxx-yyy/ – WORK

/category/child-category-1/child-category-2/filter_xxx-yyy/ – NOT work

/category/child-category-1/child-category-2/child-category-3/filter_xxx-yyy/ – NOT work

        add_action('pre_get_posts', array($this, 'filter_posts_by_custom_fields'));
        add_action('init', array($this, 'register_rewrite_rules'));
        
    public function register_rewrite_rules() {
        add_rewrite_rule('^category/([^/]+)/(.+)/?$', 'index.php?category_name=$matches[1]&custom_filter=$matches[2]', 'top');
        add_rewrite_tag('%custom_filter%', '([^&]+)');
    }

public function filter_posts_by_custom_fields($query) { 
    if (!$query->is_main_query() || !is_category() || !$query->get('custom_filter')) return;

    $custom_filter = $query->get('custom_filter');
    $filters = explode('-and-', $custom_filter);

    $meta_query = ['relation' => 'AND'];
    foreach ($filters as $filter) {
        if (strpos($filter, 'filter_') === 0) {
            list($key, $value) = explode('-', $filter, 2);

            $values = explode('-plus-', $value);

            $meta_query[] = [
                'key' => $key,
                'value' => count($values) > 1 ? $values : $value,
                'compare' => count($values) > 1 ? 'IN' : '='
            ];
        }
    }
    $query->set('meta_query', $meta_query);
}

How can I make the filter work at all levels of categories?

Sorry for My English.



You need to sign in to view this answers

Exit mobile version