admin管理员组

文章数量:1134569

I'm running a WordPress multi-site, where i have created a custom post type which have 5 different categories on main site. now i want to display data (posts) of those 5 categories on multi-sites 5 sub sites.. is this possible?

some answers says

switch_to_blog()

can help, but i don't know how this will work in my case, can anyone help?

I'm running a WordPress multi-site, where i have created a custom post type which have 5 different categories on main site. now i want to display data (posts) of those 5 categories on multi-sites 5 sub sites.. is this possible?

some answers says

switch_to_blog()

can help, but i don't know how this will work in my case, can anyone help?

Share Improve this question asked Aug 17, 2023 at 14:17 Chandresh TiwariChandresh Tiwari 132 bronze badges 2
  • do you want to display a list of these posts with links to them on the first site? Or do you want those posts to actually be on the other sites? switch_to_blog won't make those posts or their categories show up in the WP Admin area. What's the problem you're trying to solve that needs this? What is your CPT? – Tom J Nowell Commented Aug 17, 2023 at 14:38
  • i wanna display a list of these posts from main site to other sites. like if 'category one' is dedicated to 'site one' then i can display all the post under 'category one' on 'site one', and the same goes for category two, three...etc – Chandresh Tiwari Commented Aug 17, 2023 at 15:19
Add a comment  | 

1 Answer 1

Reset to default 2

You can put something like this in a theme template:

<?php

switch ( get_current_blog_id() ) {
    case 9:
        $category = 'alignment';
        break;

    case 13:
        $category = 'lists';
        break;

    case 14:
        $category = 'comments';
        break;

    default:
        $category = '';
        break;
}

switch_to_blog( BLOG_ID_CURRENT_SITE ); // root site.

$category_posts = get_posts(
    array(
        'category_name' => $category,
    )
);

if ( $category_posts ) {
    ?>

    <ul>
        <?php foreach ( $category_posts as $category_post ) : ?>
            <li>
                <a href="<?php echo esc_url( get_permalink( $category_post->ID ) ); ?>">
                    <?php echo esc_html( get_the_title( $category_post->ID ) ); ?>
                </a>
            </li>
        <?php endforeach; ?>
    </ul>

    <?php
}

restore_current_blog();

?>

That switches to the main site, grabs the posts that correspond to the sub-site's category, displays them, then restores the sub-site.

Update the case statements to match your blog IDs and category slugs. If you need it in a widget, etc, it should be pretty straightforward to adapt to other contexts.

本文标签: categoriesCan Multisite and Custom Post Types work this way