0
votes

Here is the code in my functions.php that redirects users (to their new "Sample Page") when they log in:

function admin_default_page() {  
  return '/wp-admin/post.php?post=2&action=edit';
}

add_filter('login_redirect', 'admin_default_page');

The problem is that the url to which we redirect is missing the users site url. For example, if a user creates a site "Bobs Trucks", it redirects them to

example.com/wp-admin/post.php?post=2&action=edit (does not work)

instead of

example.com/bobstrucks/wp-admin/post.php?post=2&action=edit

I've tried all the WordPress functions to get the full url needed (example.com/bobstrucs/url-to-redirect-to) but have not succeeded.

I'm trying a rather hackish solution where I get the user ID form the logged in user, and get all the blogs the user has (= just one, "Bobs Trucks"):

function admin_default_page() {
    global $current_user;
    get_currentuserinfo();
    $blogs = get_blogs_of_user( $current_user->ID);
    foreach($blogs as $blog) { $userblog = $blog->siteurl; }
    return $userblog .'/wp-admin/post.php?post=2&action=edit';
}

add_filter('login_redirect', 'admin_default_page');

But this one has the problem of not working the first time user logs in.

Thank you very much!

1
Its an array with an object inside it. Quick question, whats the user id in that example? - Darren
echo $current_user->ID; ends up as "37". Was this what you meant? How can I access the ["siteurl"] (key..?) of this object inside the array? - Jonathan
You could use a foreach($blogs as $blog) { $userblog = $blog->siteurl; } then check if $userblog is correct. - Darren
im sure theres a better alternative than looping but that should work for now provided the user only ever has one blog. Will find something when i can get to the computer :-) - Darren
Ok. Although the loop-solution was correct here seems to be a problem not knowing the necessary information early enough. Since the function gets triggered when user clicks "log in" apparently we don't know the $userblog etc. When user is logged in, the function works but not on the firts time when users loggs in. - Jonathan

1 Answers

0
votes

Try something like this:

function admin_default_page() {
    if ( is_user_logged_in() && is_admin() ) {
        $blog_id = get_current_blog_id();
        $blog = get_blog_details( array( 'blog_id' => $blog_id ) );
        $location = '/' . $blog->blogname . '/wp-admin/post.php?post=2&action=edit';
        wp_redirect( $location );
        exit;
    }
}
add_filter( 'login_redirect', 'admin_default_page' );

Refs: