Denis Yanchevskiy
Denis Yanchevskiy

Reputation: 21

WordPress Multisite - show "parent" pages and posts on "child" sites

I created multisite network with subdomains and added pages and posts on primary site. I want show this pages and posts on child sites. For example, primarysite.local/test-page/ and sub.primarysite.local/test-page/ show content from primarysite.local/test-page/.

By default, sub.primarysite.local/test-page/ show Error 404 page, because this page is not exists.

I tried to use parse_query and pre_get_posts actions to check page url in primary site and override default behavior but it was not successful.

Maybe someone has an idea of what kind of hook should be used or is not possible to implement in WordPress?

Upvotes: 0

Views: 1616

Answers (1)

Denis Yanchevskiy
Denis Yanchevskiy

Reputation: 21

As a result, I decided to use the hook template_redirect.

Code of plugin for posts and pages:

<?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();
        }
    }
}

Upvotes: 2

Related Questions