Change page template programmatically ?

I have two page templates and Qtranslate installed.

I want to choose one or another depending the language selected.

Read More

Can I do something like this ?

if($q_config['lang'] == 'en'){
// load page-template_en.php
}else{
// load page-template_de.php
}

Any idea ?

Thanks!

Related posts

Leave a Reply

5 comments

  1. It is possible using the template_redirect hook.

    Looks something like this :

     function language_redirect()
     {
          global $q_config;
    
          if( $q_config['lang'] == 'en' )
          {
               include( get_template_directory() . '/page-template_en.php' );
               exit;
          }
          else
          {
               include( get_template_directory() . '/page-template_de.php' );
               exit;
          }
     }
     add_action( 'template_redirect', 'language_redirect' );
    

    Code is untested, but should look like that.

    See my similar answer HERE for more help.

  2. Finally found it!
    If I understand your question right, the template is basically saved as metadata that needs to be updated.

    update_post_meta( $post_id, '_wp_page_template', 'your_custom_template' );
    // or
    update_metadata('post_type',  $post_id, '_wp_page_template', 'your_custom_template' );
    

    Source and further info

  3. Should be possible using the template_include hook. Code is untested:

     add_action( 'template_include', 'language_redirect' );
    
     function language_redirect( $template ) {
          global $q_config;
          $lang = ( 'en' === $q_config['lang'] ) ? 'en' : 'de';
    
          $template = str_replace( '.php', '_'.$lang.'.php', $template );
          return $template;
     }
    
  4. Thank you everyone for these suggestions !
    I wanted to set “Elementor canvas” template by default on post only and I did like that :

    function default_post_template_elementor_canvas($post_type, $post) 
    {
        $wishedTemplate = 'elementor_canvas'; // to see available template var_dump(get_page_templates($post))
        if ($post_type === 'post'
                && in_array($wishedTemplate, get_page_templates($post)) // Only if elementor_canvas is available
                && $post->ID != get_option('page_for_posts') // Not the page for listing posts
                && metadata_exists('post', $post->ID, '_wp_page_template') === false) {  // Only when meta _wp_page_template is not set
          add_post_meta($post->ID, '_wp_page_template', $wishedTemplate);
        }
    }
    add_action('add_meta_boxes', 'default_post_template_elementor_canvas', 10, 2);