Skip to content

Instantly share code, notes, and snippets.

@SteveJonesDev
Created October 11, 2023 17:52
Show Gist options
  • Save SteveJonesDev/a0a6e50ac0599b15ae410dafdb2458a6 to your computer and use it in GitHub Desktop.
Save SteveJonesDev/a0a6e50ac0599b15ae410dafdb2458a6 to your computer and use it in GitHub Desktop.
On a WordPress multisite subsite track if the user is logged in on the main site and add log In or Log Out link to the primary menu
<?php
/**
* Check if the user is logged in to the main site.
*
* @return bool True if the user is logged in to the main site, false otherwise.
*/
function sjd_is_user_logged_in_main_site() {
switch_to_blog( 1 ); // 1 usually represents the main site in a multisite setup.
$logged_in = is_user_logged_in();
restore_current_blog(); // Switches back to the original blog.
return $logged_in;
}
/**
* Add a custom login link to the primary menu.
*
* @param string $items The HTML list content for the menu items.
* @param object $args An object containing wp_nav_menu() arguments.
* @return string The modified HTML list content for the menu items.
*/
function sjd_add_custom_login_link_to_nav( $items, $args ) {
if ( 'primary' === $args->theme_location ) { // Change 'primary' to your desired menu location if different.
if ( sjd_is_user_logged_in_main_site() ) {
// If the user is logged in, show a logout link.
$logout_url = wp_logout_url( get_site_url( 1 ) ); // Redirect to the main site after logout.
$link_content = '<li><a href="' . esc_url( $logout_url ) . '">Log Out</a></li>';
} else {
// If the user is not logged in, show a login link.
$main_site_login_url = get_site_url( 1, 'log-in', 'login' );
$link_content = '<li><a href="' . esc_url( $main_site_login_url ) . '">Log In</a></li>';
}
// Prepend the custom link to the beginning of the menu.
$items = $link_content . $items;
}
return $items;
}
add_filter( 'wp_nav_menu_items', 'sjd_add_custom_login_link_to_nav', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment