• klishb

    (@klishb)


    I’ve found some old ways of doing this for posts ( for example https://scratch99.com/wordpress/development/how-to-change-post-template-via-url-parameter/), but it doesn’t seem to work for pages. Not sure why. For example, I’d like to be able to do:

    mysite.com/mypage/?template=page_noheaderfooter

    I know my template works because if I select it in the page editor it produces the result I want. Here’s the code I’ve been playing with which I modified slightly from the example provided above:

    function template_query_vars($vars) {
    return array(‘template’) + $vars;
    }
    add_filter(‘query_vars’, ‘template_query_vars’);

    function url_template($template) {
    global $wp;
    if ($wp->query_vars[‘template’]==’full’) {
    return dirname( __FILE__ ) . ‘/page_noheaderfooter.php’;
    }
    else {
    return $template;
    }
    }

    add_filter(‘template_include’, ‘url_template’);`

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

    (@howdy_mcgee)

    If it’s literally a $_GET parameter you don’t need to use any query vars. Those were if you were wanting to use an endpoint. Personally, I would use locate_template() instead of what you’re currently using. An example could look something like this:

    /**
     * Change template based on $_GET value
     *
     * @param String $template
     *
     * @return String $template
     */
    function prefix_template_mods( $template ) {
    	
    	// Check if our GET parameter exists and holds a specific value
    	if( isset( $_GET['template'] ) && 'page_noheaderfooter' == $_GET['template'] ) {
    		
    		// Attempt to locate our template
    		$new_template = locate_template( array( 'page_noheaderfooter.php' ) );
    		
    		// If a template was found, switch it
    		if( ! empty( $new_template ) ) {
    			$template = $new_template;
    		}
    		
    	}
    	
    	return $template;
    	
    }
    add_filter( 'template_include', 'prefix_template_mods' );
    Thread Starter klishb

    (@klishb)

    That worked. Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Select page template via url parameter’ is closed to new replies.