The get_blogaddress_by_id() WordPress PHP function retrieves a full blog URL, given a blog ID.
Usage
get_blogaddress_by_id( $blog_id );
Example:
$blog_id = 2; $blog_url = get_blogaddress_by_id( $blog_id ); echo $blog_url; // Outputs "https://example.com/blog-2"
Parameters
$blog_id(int) – Required. The ID of the blog for which you want to retrieve the URL.
More information
See WordPress Developer Resources: get_blogaddress_by_id()
Examples
Display blog URL in a list
This code retrieves the URLs of all blogs in a multisite WordPress installation and displays them in an unordered list.
// Fetch all the blogs in a multisite installation
$blogs = get_sites();
echo '<ul>';
foreach ( $blogs as $blog ) {
$blog_url = get_blogaddress_by_id( $blog->blog_id );
echo '<li><a href="' . esc_url( $blog_url ) . '">' . esc_html( $blog_url ) . '</a></li>';
}
echo '</ul>';
Redirect users to their primary blog
This code redirects logged-in users to their primary blog.
// Check if user is logged in
if ( is_user_logged_in() ) {
// Get the current user ID
$user_id = get_current_user_id();
// Get the primary blog ID of the current user
$primary_blog_id = get_user_meta( $user_id, 'primary_blog', true );
// Get the blog URL by blog ID
$blog_url = get_blogaddress_by_id( $primary_blog_id );
// Redirect the user to their primary blog
wp_redirect( $blog_url );
exit;
}
Display the blog URL in the admin area
This code adds a column to the Network Admin > Sites page, displaying the blog URL for each site.
// Add a custom column to the sites list table
add_filter( 'wpmu_blogs_columns', 'custom_blog_url_column' );
function custom_blog_url_column( $columns ) {
$columns['blog_url'] = 'Blog URL';
return $columns;
}
// Display the blog URL in the custom column
add_action( 'manage_sites_custom_column', 'display_custom_blog_url_column', 10, 2 );
function display_custom_blog_url_column( $column_name, $blog_id ) {
if ( 'blog_url' === $column_name ) {
$blog_url = get_blogaddress_by_id( $blog_id );
echo esc_html( $blog_url );
}
}
Fetch and display blog URLs in a dropdown menu
This code fetches the URLs of all blogs in a multisite installation and displays them in a dropdown menu.
// Fetch all the blogs in a multisite installation
$blogs = get_sites();
echo '<select name="blogs">';
foreach ( $blogs as $blog ) {
$blog_url = get_blogaddress_by_id( $blog->blog_id );
echo '<option value="' . esc_url( $blog_url ) . '">' . esc_html( $blog_url ) . '</option>';
}
echo '</select>';