kylephillips / favorites

Simple and flexible favorite buttons for any WordPress post type.
https://favoriteposts.com
223 stars 86 forks source link

Pulling Favorites list from multiple sites on Multisite #103

Open pkarjala opened 5 years ago

pkarjala commented 5 years ago

I am wanting to aggregate the Favorites that users have created across multiple sites on a Multisite install.

Currently I am doing something along these lines:

$args = array('fields'=>'ids');
$sites = get_sites($args);
foreach ($sites as $site) {
  the_user_favorites_list(
    $user_id = null,
    $site_id = $site,
    $include_links = true,
    $filters = null,
    $include_button = false,
    $include_thumbnails = false,
    $thumbnail_size = 'thumbnail',
    $include_excerpt = false
  );
}

The issue is that it will loop through each of the sites in multisite, but print out "No Favorites" for all of them except the last site's Favorites that it comes across. This may have to do with globals or other issues with the way that the_user_favorites_list() works.

Calling each site individually like this DOES work:

the_user_favorites_list(
  $user_id = null,
  $site_id = 2,
  $include_links = true,
  $filters = null,
  $include_button = false,
  $include_thumbnails = false,
  $thumbnail_size = 'thumbnail',
  $include_excerpt = false
);
the_user_favorites_list(
  $user_id = null,
  $site_id = 3,
  $include_links = true,
  $filters = null,
  $include_button = false,
  $include_thumbnails = false,
  $thumbnail_size = 'thumbnail',
  $include_excerpt = false
);

Is there a cleaner way that I can do this? I anticipate having a number of sub-sites, and would like users to be able to track Favorites across them, but can't render the links to them all without being able to produce the list of Favorites dynamically. I suppose I could query each site in turn by getting a count of the number of sites, but this is still awkward to do.

gfargo commented 5 years ago

Hey @pkarjala, and anyone else who may come here looking for a solution to individually grab Favorites from each multisite install, I think I see the issue with the code above.

The function get_sites() returns an array of site objects, not IDs. Because of this, you need to first extract the site ID from the returned object. This is outlined in a comment from mkormendy.

$sites = get_sites( [
    'fields'=>'ids'
] );

foreach ($sites as $site) {

  // Skip current item if its not an instance of WP Site
  if ( empty( ! $site instanceof WP_Site ) {
    continue;
  }

  the_user_favorites_list(
    $user_id = null,
    $site_id = $site->blog_id,  // Pass `blog_id` instead of entire WP_Site object.
    $include_links = true,
    $filters = null,
    $include_button = false,
    $include_thumbnails = false,
    $thumbnail_size = 'thumbnail',
    $include_excerpt = false
  );
}