Как программно изменить шаблон страницы?
У меня есть два шаблона страниц и установлен Qtranslate.
Я хочу выбирать один или другой шаблон в зависимости от выбранного языка.
Могу ли я сделать что-то подобное?
if($q_config['lang'] == 'en'){
// загрузить page-template_en.php
}else{
// загрузить page-template_de.php
}
Есть какие-нибудь идеи?
Спасибо!
Наконец-то нашёл! Если я правильно понял ваш вопрос, шаблон сохраняется как метаданные, которые нужно обновить.
update_post_meta( $post_id, '_wp_page_template', 'your_custom_template' );
// или
update_metadata('post_type', $post_id, '_wp_page_template', 'your_custom_template' );

Лучший (канонический) способ — использовать фильтр-хук template_include
: http://codex.wordpress.org/Plugin_API/Filter_Reference/template_include
Пример кода:
function language_redirect( $template ) {
global $q_config;
$new_template = locate_template( array( "page-{$q_config['lang']}.php" ) );
if ( '' != $new_template ) {
return $new_template ;
}
return $template;
}
add_filter( 'template_include', 'language_redirect' );

Должно быть возможно с использованием хука template_include
. Код не тестировался:
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;
}

Спасибо всем за эти предложения! Я хотел установить шаблон "Elementor canvas" по умолчанию только для записей и сделал это так:
function default_post_template_elementor_canvas($post_type, $post)
{
$wishedTemplate = 'elementor_canvas'; // чтобы увидеть доступные шаблоны, используйте var_dump(get_page_templates($post))
if ($post_type === 'post'
&& in_array($wishedTemplate, get_page_templates($post)) // Только если elementor_canvas доступен
&& $post->ID != get_option('page_for_posts') // Не страница для списка записей
&& metadata_exists('post', $post->ID, '_wp_page_template') === false) { // Только когда мета _wp_page_template не установлена
add_post_meta($post->ID, '_wp_page_template', $wishedTemplate);
}
}
add_action('add_meta_boxes', 'default_post_template_elementor_canvas', 10, 2);

Это возможно с использованием хука template_redirect
.
Выглядит примерно так:
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' );
Код не тестировался, но должен выглядеть именно так.
Смотрите мой похожий ответ ЗДЕСЬ для получения дополнительной помощи.

Не используйте template_redirect для загрузки альтернативного файла шаблона http://markjaquith.wordpress.com/2014/02/19/template_redirect-is-not-for-loading-templates/
