pre_get_posts not working properly on pages

338 Views Asked by At

i am trying to add a filter to wordpress loops using pre_get_posts action which works fine on archives but all pages are returning 404 error. this is the code in functions.php:

function add_city_condition_to_main_query($query)
{
    if (!is_admin() && $query->is_main_query()) {
        if ($query->is_archive || $query->is_page) {
            if (get_current_city_id() && get_post_status(get_current_city_id())) {

                $meta_query = [[
                    'key' => 'city',
                    'value' => get_current_city_id(),
                    'compare' => '='
                ]];
                $query->set('meta_query', $meta_query);
            }
        }
    }
}

add_action('pre_get_posts', 'add_city_condition_to_main_query');
function get_current_city_id() { 
    if (isset($_COOKIE['city'])) { 
        $city = $_COOKIE['city']; 
            if ($city == 'all') return 0; 
            if (get_post_status($city) && get_post_type($city) == 'city') { 
                 $translations = pll_get_post_translations($city); 
                 if ($translations[pll_current_language()]) return $translations[pll_current_language()]; 
                 return $city; 
             } else return false; 
     } else return false; 
 }

what is the problem?

0

There are 0 best solutions below