Question

I have three WordPress installations (cannot use multisite; cannot use RSS/Atom feeds) and I am trying to display a date-sorted list of the latest 10 posts from each of the two sub-sites on the main site home page. The site is organized thus:
https://www.example.com
https://www.example.com/editorials
https://www.example.com/news

These are three separate installations of WordPress, however sharing the same database (with different db prefixes, of course).

I have tried creating a loop calling the wp-load.php function, but I cannot seem to get it to reset; instead, the second iteration simply re-displays the posts from the first loop (in this case, from ./editorials/wp-load.php).

I have tried to place all the posts in separate arrays, for later combining and sorting by date, i.e., $content1 and $content2, but I haven't gotten that far since I cannot fetch posts from the second instance.

Here is code:
https://pastebin.com/9REj1RhV
Thanks in advance! -Brian

Was it helpful?

Solution

I'd use the REST API to get the latest 10 posts from each install, then combine the two arrays, sort them by the date, and then only use the latest 10 results.

$editorials = wp_remote_get( 'https://www.example.com/editorials/wp-json/wp/v2/posts/' );
$news       = wp_remote_get( 'https://www.example.com/news/wp-json/wp/v2/posts/' );

$editorials = json_decode( $editorials[ 'body' ] );
$news       = json_decode( $news[ 'body' ] );

$all = array_merge( $editorials, $news );
//* The spaceship operator requires PHP > 7.0
usort( $all, function( $a, $b ) { return $a->date <=> $b->date; } );
$all = array_slice( $all, 0, 10 );

//* Do something useful with the combined array of posts
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top