• hershkoy

    (@hershkoy)


    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 with http://localhost?city=whatever returns 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)
  • Potential Issues:

    1. Rewrite Rules Not Flushed
    2. Query Variables Handling
    3. Order of Hook Execution
    Moderator bcworkz

    (@bcworkz)

    If you still want to have the request go to the static page, you don’t want to alter the main query. By altering the main query you’re discarding the static page criteria in favor of a posts archive type of query.

    If the static page is to display results of a city query, the page template or pattern itself should be making its own query.

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Adding a custom query_vars’ is closed to new replies.