Я пытаюсь загрузить новый шаблон страницы, когда в конце URL-адреса моей страницы добавляется запрос var:
Исходный URL: example.com/testpage/
с добавленной в конец переменной: example.com/testpage/amp
Затем он загрузит пользовательский шаблон php.
Это похоже на прямую операцию, но я не могу заставить ее работать.
URL-адрес загружается с переменной / amp в конце, но шаблон не загружается. Если я уберу условие «get_query_var (‘amp’)», то это без проблем загрузит шаблон. Что мне не хватает? Спасибо 🙂
Вот мой рабочий код:
add_filter( 'query_vars', 'register_query_var' );
function register_query_var( $vars ) {
$vars[] = 'amp';
return $vars;
}
add_rewrite_endpoint( 'amp', EP_PAGES );
add_filter( 'template_include', 'use_amp_template', 99 );
function use_amp_template( $template ) {
global $wp_query;
if ( get_query_var( 'amp' ) && is_page() ) {
$new_template = locate_template( array( 'amptemplate.php' ) );
if ( '' != $new_template ) {
return $new_template;
}
}
return $template;
}
Нашел хорошее решение самостоятельно. Вот код, если он кому-нибудь поможет.
Добавление «amp» после страницы или публикации приведет к загрузке различных шаблонов для amp-версий страницы.
example.com/samplepage/amp
или же
example.com/samplepost/amp
add_filter( 'query_vars', 'register_query_var' );
function register_query_var( $vars ) {
$vars[] = 'amp';
return $vars;
}
add_rewrite_endpoint( 'amp', EP_PAGES | EP_PERMALINK );add_filter( 'template_include', 'use_amp_template', 99 );
function use_amp_template( $template ) {
global $wp_query;
if(isset( $wp_query->query['amp'] ) && is_page()){
$new_template = locate_template( array( 'amppagetemplate.php' ) );
if ( '' != $new_template ) {
return $new_template;
}
}
if(isset( $wp_query->query['amp'] ) && is_single()){
$new_template = locate_template( array( 'ampposttemplate.php' ) );
if ( '' != $new_template ) {
return $new_template;
}
}
return $template;
}
Других решений пока нет …