Adding a custom query_vars
-
I am trying to add a custom_vars to my wordpress site using version 6.5.3 (Hebrew)
The template is Twenty Twenty, and I disabled all the plugins.
The problem is that after adding the query_vars, access the site withhttp://localhost?city=whateverreturns the posts page.
Accessing the site normally without the query_vars (http://localhost) returns the statis page as expected.This is the code that I added to wp-content/themes/twentytwenty/functions.php:
function myplugin_register_query_vars( $vars ) { $vars[] = 'city'; return $vars; } add_filter( 'query_vars', 'myplugin_register_query_vars' ); function myplugin_rewrite_tag_rule() { add_rewrite_tag( '%city%', '([^&]+)' ); add_rewrite_rule( '^city/([^/]*)/?', 'index.php?city=$matches[1]','top' ); } add_action('init', 'myplugin_rewrite_tag_rule', 10, 0); function myplugin_pre_get_posts( $query ) { if ( is_admin() || ! $query->is_main_query() ){ return; } $city = get_query_var( 'city' ); // add meta_query elements if( !empty( $city ) ){ $query->set( 'meta_key', 'city' ); $query->set( 'meta_value', $city ); $query->set( 'meta_compare', 'LIKE' ); } } add_action( 'pre_get_posts', 'myplugin_pre_get_posts', 1 );
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
The topic ‘Adding a custom query_vars’ is closed to new replies.