0

I am attempting to loop through all sites on my multisite network blog. However, when I attempt to use get_pages it ignores the fact that the blog has switched via 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();
}

Output:

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

The script above will var_dump the same $pages through out the entire loop, regardless of which blog it switches to. What exactly am I doing wrong, and is there a way to accomplish what I'm attempting to do?

0

Try using get_posts instead of get_pages

$pages = get_posts( array(
        'order' => 'ASC',
        'orderby' => 'ID',
        'post_type' => 'page',
        'post_status' => 'publish',
    ) );
  • 2
    Hi there, could you elaborate further? – Tim Malone Jul 28 '16 at 8:05
  • Try with the code I added... – user1049961 Jul 29 '16 at 11:24
0

Question is old, but for anyone with similar issue, this should work for you:

<?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_get_sites was deprecated in 4.6 in favor of get_sites

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.