2

I'm trying to get the primary blog URL of a user. What I have works to grab the details, but if there is more than one blog it just returns them all :(

$user_id = get_current_user_id();
$user_blogs = get_blogs_of_user( $user_id );
foreach ($user_blogs AS $user_blog) {
 echo $user_blog->siteurl;
}

How can I modify this to output the primary blog URL of the current user?

I'm not sure how to pull it from wp_usermeta primary_blog table, but that may do the trick.


What I would like is the URL from the user primary blog so when they login from the network main site and visit the account area, it shows links to various areas without directing them to the you attempted to access message first...

2
  • How do you define “primary” blog for an user? How do you recognize which one is primary? Commented Apr 15, 2019 at 5:54
  • core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/… /** 27 * Get one of a user's active blogs 28 * 29 * Returns the user's primary blog, if they have one and 30 * it is active. If it's inactive, function returns another 31 * active blog of the user. If none are found, the user 32 * is added as a Subscriber to the Dashboard Blog and that blog 33 * is returned. 34 * 35 * since MU (3.0.0) 36 * 37 * param int $user_id The unique ID of the user 38 * return WP_Site|void The blog object 39 */ Commented Apr 15, 2019 at 6:05

1 Answer 1

1

There's actually a function for that: get_active_blog_for_user() https://developer.wordpress.org/reference/functions/get_active_blog_for_user/

$user_id = get_current_user_id();
$user_blog = get_active_blog_for_user( $user_id );
echo $user_blog->siteurl;

1
  • BEWARE that get_active_blog_for_user() apparently has side effects: "...If none are found, the user is added as a Subscriber to the Dashboard Blog and that blog is returned". So it's not an "information only" function! A safer option would be get_user_meta( $user_id, 'primary_blog', true ).
    – Martin_W
    Commented May 14, 2023 at 5:07

Your Answer

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

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