如何在切换到博客后获取特定博客的所有页面?

时间:2016-07-27 作者:Josh Foskett

我正在尝试在我的multisite network 博客然而,当我尝试使用get_pages 它忽略了博客已通过switch_to_blog.

$sites = wp_get_sites( array( \'limit\' => 1000 ) );
foreach ( $sites as $site ) {
    $blog_id = intval( $site[\'blog_id\'] );
    if ( $blog_id < 2 ) {
        continue;
    }
    switch_to_blog( $blog_id );
    $pages = get_pages( array(
        \'sort_order\' => \'asc\',
        \'sort_column\' => \'ID\',
        \'post_type\' => \'page\',
        \'post_status\' => \'publish\',
    ) );
    echo \'Blog ID: \' . get_current_blog_id() . \' | Total Pages: \' . count ( $pages ) . \'<br>\';
    // foreach( $pages as $page ) {
    //  echo \'Blog ID: \' . $blog_id . \' | Post ID: \' . $page->ID . \'<br>\';
    // }
    restore_current_blog();
}
输出:

Blog ID: 2  | Total Pages: 71
Blog ID: 3  | Total Pages: 71
Blog ID: 4  | Total Pages: 71
Blog ID: 5  | Total Pages: 71
Blog ID: 6  | Total Pages: 71
Blog ID: 7  | Total Pages: 71
Blog ID: 8  | Total Pages: 71
Blog ID: 9  | Total Pages: 71
Blog ID: 10 | Total Pages: 71
Blog ID: 11 | Total Pages: 71
Blog ID: 12 | Total Pages: 71
Blog ID: 13 | Total Pages: 71
Blog ID: 14 | Total Pages: 71
Blog ID: 15 | Total Pages: 71
Blog ID: 16 | Total Pages: 71
Blog ID: 17 | Total Pages: 71
Blog ID: 18 | Total Pages: 71
Blog ID: 19 | Total Pages: 71
Blog ID: 20 | Total Pages: 71
上面的脚本将var\\u转储相同的$pages 通过整个循环,无论它切换到哪个博客。我到底做错了什么?有没有办法完成我想做的事情?

2 个回复
SO网友:user1049961

尝试使用get_posts 而不是get_pages

$pages = get_posts( array(
        \'order\' => \'ASC\',
        \'orderby\' => \'ID\',
        \'post_type\' => \'page\',
        \'post_status\' => \'publish\',
    ) );

SO网友:Curtis

这个问题由来已久,但对于任何有类似问题的人来说,这应该适合您:

<?php

$sites = get_sites([
    \'number\' => 9999,
]);

foreach ($sites as $site) {
    switch_to_blog($site->blog_id);

    $pages = get_pages();
    echo count($pages);

    restore_current_blog();
}
wp\\u get\\u站点在4.6中被弃用,取而代之的是get_sites