我意识到这个问题相当“古老”,然而,我想出了一个解决办法。
可以从多站点网络中的其他博客检索帖子,而无需使用switch_to_blog();
或restore_current_blog();
.
/**
* This is an example of retrieving posts from multiple blogs in Multisite.
*
* @author Michael Ecklund
* @author_url https://www.michaelbrentecklund.com
*
* @param array $user_args
*
* @return array|bool|null|object
*/
function mbe_get_network_posts( Array $user_args = Array() ) {
if ( ! is_multisite() ) {
return false;
}
$default_args = array(
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'limit\' => absint( get_option( \'posts_per_page\' ) ),
\'orderby\' => \'post_date\',
\'order\' => \'DESC\'
);
$args = wp_parse_args( $user_args, $default_args );
$args[\'orderby\'] = strtolower( $args[\'orderby\'] );
$args[\'order\'] = strtoupper( $args[\'order\'] );
if ( ! in_array( $args[\'orderby\'], array(
\'id\',
\'post_title\',
\'post_name\',
\'post_date\',
\'post_modified\',
\'post_author\',
\'blog_id\'
) ) ) {
return false;
}
if ( ! in_array( $args[\'order\'], array(
\'ASC\',
\'DESC\'
) ) ) {
return false;
}
global $wpdb;
if ( ! $blog_ids = $wpdb->get_col( "SELECT DISTINCT blog_id FROM {$wpdb->blogs}" ) ) {
return false;
}
$queries = array();
$where = array(
\'post_type\' => $wpdb->prepare( "AND post_type = %s", $args[\'post_type\'] ),
\'post_status\' => $wpdb->prepare( "AND post_status = %s", $args[\'post_status\'] ),
);
foreach ( $blog_ids as $blog_id ) {
if ( $blog_id == 1 ) {
$prefix = substr( $wpdb->base_prefix, 0, - 1 );
} else {
$prefix = $wpdb->base_prefix . $blog_id;
}
$queries[] = $wpdb->prepare(
"
(
SELECT *, {$blog_id} AS blog_id
FROM {$prefix}_posts
WHERE 1=1 " . join( " ", $where ) . "
ORDER BY {$args[\'orderby\']}
{$args[\'order\']}
LIMIT %d
)
",
absint( $args[\'limit\'] )
);
}
$query = join( "UNION", $queries ) . "ORDER BY {$args[\'orderby\']} {$args[\'order\']}";
return $wpdb->get_results( $query );
}
我把它写得简短而中肯。然而,您可以对此进行扩展,允许多种帖子类型或帖子状态等。
目前,通过上述功能,您可以控制帖子类型、帖子状态和排序方式:
Sortable Options: