0

I have a subdir multisite setup of 10 sites where I have maintained similar Url structure in all of them for a custom post like partoftheurl-in-country (except mainsite) and for the mainsite it's partoftheurl only. So far so good, everything works fine.

Now I need to create a custom function that returns an array of all matching urls for the current url across the network. I have done this but returns any one of the site only! can anyone put a flash where I'm going wrong.

 function rel_alternate_network(){
    global $post;
    $slugX = is_main_site() ? $post->post_name : rtrim($post->post_name, '-in-'.strtolower(do_shortcode('[country]')));
    $urls = array();
    foreach(get_sites() as $site){
        if( $site->blog_id == get_current_blog_id()) {continue;}
            switch_to_blog($site->blog_id);
            $slugY = get_post_by_slug($slugX);
            $urls['site'] = $site->path;
            $urls['slug'] = $slugY->post_name;
            restore_current_blog();
    }
    return $urls;
}

Note: get_post_by_slug() is custom function I created that works perfectly alright; there is also a shortcode [country] created that returns the country name in the url.

1
  • Is it only returning the site you're currently on? Jan 4, 2022 at 16:58

1 Answer 1

1

Each pass through the foreach() loop, you're wiping out the values that are already in your $urls array.

Try something like this:

 function rel_alternate_network(){
    global $post;
    $slugX = is_main_site() ? $post->post_name : rtrim($post->post_name, '-in-'.strtolower(do_shortcode('[country]')));
    $urls = array();
    foreach(get_sites() as $site){
        if( $site->blog_id == get_current_blog_id()) {continue;}
            switch_to_blog($site->blog_id);
            $slugY = get_post_by_slug($slugX);
            $new_url['site'] = $site->path;
            $new_url['slug'] = $slugY->post_name;
            $urls[] = $new_url; // Adds the new URL to the URLs array.
            restore_current_blog();
    }
    return $urls;
}
1
  • 1
    Thanks @Pat. I realized the same thing just after posting it here :-)
    – TechieBoy
    Mar 4, 2022 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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