Need assistance with custom loop to query CPT on Multisite

I'm looking for a solution to query network custom post types, as I do it with wp_query.

Here's the code I have so far:

$subsites = get_sites(); // on cherche la liste des sites sur le réseau
foreach($subsites as $subsite) { // pour chaque site

switch_to_blog($subsite->blog_id); // on switch de site avec l'ID

$events = new WP_Query( array( // on fait la requête sur les events avec les filtres
'post_type'	=> 'events',
'post_status'	=> 'publish',
'meta_key'	=> 'date_debut',
'orderby' => 'meta_value',
'order' => $order, // pas forcément utile car order côté client après
'posts_per_page'	=> $posts_per_page,
'meta_query' => array(
array( // on compare avec la date du jour
'key'	=> 'date_debut',
'value' => date('Ymd'),
'compare' => $compare == '<' ? '<' : $compare, // le symbole est stocké encodé
'type'	=> 'DATE',

set_query_var( 'blogid', $subsite->blog_id ); // on récupère l'ID du site pour le passer au template

if ( $events->have_posts() ) {
while ( $events->have_posts() ) : $events->the_post();
get_template_part('components/modules/event'); // on appelle le template
$output .= ob_get_clean();

restore_current_blog(); // on revient au site 1

I'd like to use this query and output using a shortcode.

Any assistance would be appreciated.

  • Ivan
    • Developer

    Hi Valentin GUENICHON !

    You can include your code into a function and add this function like handler for the custom shortcode and insert this code in a MU plugin. For example, you can create {wordpress_folder}/wp-content/mu-plugins/wpmu_custom_events.php with the following code

    function custom_events( $attrs ) {
        //your code
        return $output;
    add_shortcode( 'custom_events', 'custom_events' );

    Note: in your code you should set value for $order, $posts_per_page, $compare variables and it seems you forgot } symbol at the end of your code for closing foreach construction.

    Best regards,

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.