Я не уверен, что я делаю неправильно, исследую последние несколько дней, но безнадежно.
Настройки WordPress: Статическая страница: Главная
ЦЕЛЬ: чтобы заменить запрос, так что требуется ВСЕ данные на первой странице в том числе следующее:
и для отображения содержимого, заголовка, метаданных в естественный путь позвонив в шаблоне страницы темы
// Takes front page title
<?php wp_title(); ?>
// Takes front page config
<?php wp_head(); ?>
// takes front page post and display content
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php echo the_content(); ?>
<?php endwhile; endif; ?>
Целевой URL: homepage.com/amp (не существующая страница)
но определяется как показано ниже
// defines AMP variable
define( 'AMP_QUERY_VAR', apply_filters( 'amp_query_var', 'amp' ) );
// enable URL endpoint rewrite for /amp
add_rewrite_endpoint( AMP_QUERY_VAR, EP_ALL );
ОСНОВНАЯ ПРОБЛЕМА в текущем коде ниже
function front_page_post_AMP( $query ) {
// Get's the Current Browser URL
global $wp;
$current_url = home_url(add_query_arg(array(),$wp->request));
// Homepage AMP URL
$front_page_amp_url = get_site_url() . "/amp";
// check if the current browser URL is homepage.com/amp
if ( strcasecmp( $current_url, $front_page_amp_url ) == 0 && $query->is_main_query() )
{
// gets front page id
$front_page_id = get_option( 'page_on_front' );
// replace query id
$query->set( 'page_id', $front_page_id );
return $query;
}
}
add_action( 'pre_get_posts', 'front_page_post_AMP' );
Текущие результаты:
Конечно, он вернет 404 не найден, потому что страница усилителя или сообщение усилителя не существует.
Моя идея заключается в том, что есть альтернативный способ возврата к действительному URL-адресу путем добавления настраиваемой конечной точки для вашего сайта.
ссылка : https://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint
добавьте следующий код в функцию вашей темы
add_rewrite_endpoint( 'amp', EP_ALL );
затем сохраните постоянную ссылку, затем попробуйте получить доступ к любому URL-адресу вашего сайта, а затем / amp
пример: homepage.com/amp, homepage.com/single-post/amp
Надеюсь, поможет
провел дни, изучая, как работают WP_Query и pre_get_posts и, наконец, получил ответ
/*
* if user is accessing the not existing page homepage.com/amp/
* set the query to get the frontpage post
*/
function front_page_post_AMP( $query ) {
// Only noop the main query
if ( ! $query->is_main_query() ) {
return;
}
/*
* check if endpoint is AMP
* check if the array count is 1 (means no parameters, and most likely will result in 404)
*/
if ( is_amp_endpoint() &&
count( $query->query ) == 1 &&
! isset( $query->query['page'] ) )
{
// Get's the Current Browser URL
global $wp;
$current_url = home_url(add_query_arg(array(),$wp->request));
// Homepage AMP URL
$front_page_amp_url = get_site_url() . "/amp";
/*
* If current URL is homepage.com/amp
* set the empty query to get the front page post
*/
if ( strcasecmp( $current_url, $front_page_amp_url ) == 0 ) {
$front_page_id = get_option( 'page_on_front' );
$query->set( 'page_id', $front_page_id );
$query->set( 'post_type', "page" );
}
}
return;
}
add_action( 'pre_get_posts', 'front_page_post_AMP' );
С этим решением вы можете использовать естественный способ вызова заголовка и содержимого шаблона вашей страницы, как показано ниже.
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php echo the_content(); ?>
<?php endwhile; endif; ?>