0

我创建了带有子域的多站点网络,并在主站点上添加了页面和帖子。我想在子网站上显示此页面和帖子。例如, primarysite.local/test -page/sub.primarysite.local/test-page/显示来自primarysite.local/test-page /的内容。

默认情况下,sub.primarysite.local/test-page/显示错误 404 页面,因为该页面不存在。

我尝试使用parse_querypre_get_posts操作来检查主站点中的页面 url 并覆盖默认行为,但没有成功。

也许有人知道应该使用哪种钩子,或者无法在 WordPress 中实现?

4

1 回答 1

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();
        }
    }
}
于 2015-05-10T17:01:45.847 回答