• I am querying data from a separate database table ( outside WordPress ). I’ve created a page /cars/ and I would like to create dynamic permalinks based on what I’m querying. If I query /cars/?model=camaro I want to rewrite my permalinks to /cars/camaro/ then use a custom template to display some information.

    I’ve been playing around with endpoints but I haven’t quite got it working yet…

    /**
     * Add endpoint to handle models
     */
    function theme_endpoints() {
        add_rewrite_endpoint( 'model', EP_PAGES );		// Our base
    }
    add_action( 'init', 'theme_endpoints' );
    
    /**
     * Filter request variables
     * @param array $vars
     * @return array $vars
     */
    function theme_perma_requests( $vars ) {
    
    	if( isset( $vars['model'] ) ) {
    		$vars['model_template'] = true;
    	}
    
        return $vars;
    }
    add_filter( 'request', 'theme_perma_requests' );
    
    /**
     * Run template redirect on model requests
     * @param string $template
     * @return string $template
     */
    function end_point_templates( $template ) {
    	$model_template = get_query_var( 'model_template' );
    
    	if( true === $model_template ) {
    		$template = TEMPLATEPATH . '/page-templates/template-modelinfo.php';
    	}
    
    	return $template;
    }
    add_action( 'template_include', 'end_point_templates' );
    
    function cyb_add_query_vars( $vars) {
        $vars[] = "model";
        return $vars;
    }
    add_filter( 'query_vars', 'cyb_add_query_vars' );
    
    /**
     * Theme rewrite rules
     */
    function theme_rewrite_rules() {
        add_rewrite_rule( '^cars/([^/]+)/?$', 'index.php?page_id=8&model=$matches[1]', 'top' );
    }
    add_action( 'init', 'theme_rewrite_rules' );

    This uses my template just fine by using both /cars/?model=camaro and for /cars/camaro/ but it doesn’t pass the model to the page template in $_GET, $_POST, $_REQUEST – and I have a feeling I’m going about it wrong.

    How can I rewrite my query string to create virtual subpages?

The topic ‘Virtual Subpages’ is closed to new replies.