【问题标题】:WordPress Multisite - show "parent" pages and posts on "child" sitesWordPress Multisite - 在“子”站点上显示“父”页面和帖子
【发布时间】:2015-05-10 13:32:45
【问题描述】:

我创建了带有子域的多站点网络,并在主站点上添加了页面和帖子。我想在子网站上显示此页面和帖子。例如,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 中实现?

【问题讨论】:

    标签: wordpress multisite


    【解决方案1】:

    因此,我决定使用钩子 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();
            }
        }
    }
    

    【讨论】:

    • 您将如何更改此代码以检测然后转到自定义帖子类型的单页?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 2016-04-10
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    相关资源
    最近更新 更多