我创建了具有子域名的多站点网络,并在主站点上添加了页面和帖子。我希望在子站点上显示此页面和帖子。例如, primarysite.local / test-page / 和 sub.primarysite.local / test-page / 显示来自 primarysite.local / test-page /的内容
默认情况下, sub.primarysite.local / test-page / 显示错误404页面,因为此页面不存在。
我尝试使用 parse_query 和 pre_get_posts 操作来检查主站点中的页面网址并覆盖默认行为但不成功。
也许有人知道应该使用什么样的钩子或者不能在WordPress中实现?
答案 0 :(得分:2)
结果,我决定使用钩子 template_redirect 。
帖子和页面的插件代码:
<?php
/*
Plugin Name: Global posts
*/
add_action( 'template_redirect', 'global_posts_redirect' );
function global_posts_redirect() {
global $wp_query;
if ( $wp_query->is_404() && !is_main_site() ) {
//switch to primary site for checking post/page
switch_to_blog( 1 );
$slug = $wp_query->query_vars[ 'name' ];
$args = array(
'name' => $slug,
'post_type' => 'any',
'post_status' => 'publish'
);
$my_posts = get_posts( $args );
if ( $my_posts ) {
//if post/page exists - change header code to 200
status_header( 200 );
$post = $my_posts[ 0 ];
$post_type = get_post_type( $post );
//emulate wp_query
$wp_query->queried_object_id = $post->post_id;
if ( $post_type == 'page' ) {
$wp_query->query[ 'pagename' ] = $post->name;
unset( $wp_query->query[ 'name' ] );
$wp_query->query_vars[ 'pagename' ] = $post->name;
}
$wp_query->query_vars[ 'name' ] = $post->name;
$wp_query->queried_object = $post;
$wp_query->post_count = 1;
$wp_query->current_post = -1;
$wp_query->posts = array( $post );
$wp_query->post = $post;
$wp_query->found_posts = 1;
if ( $post_type == 'page' ) {
$wp_query->is_page = 1;
} else if ( $post_type == 'post' ) {
$wp_query->is_single = 1;
}
$wp_query->is_404 = false;
$wp_query->is_singular = 1;
restore_current_blog();
}
}
}