Skip to content

Instantly share code, notes, and snippets.

@kasparsd
Created April 14, 2025 12:53
Show Gist options
  • Save kasparsd/29b8d2da93d8c3b7aab396badef351ef to your computer and use it in GitHub Desktop.
Save kasparsd/29b8d2da93d8c3b7aab396badef351ef to your computer and use it in GitHub Desktop.
Render template of a login-logout block for WordPress
<?php
/**
* Render the login/logout block.
*
* @param array $attributes Block attributes.
* @param string $content Block content.
* @param array $block Block instance.
*/
$link = [
'url' => null,
'label' => null,
];
// Remove a fake argument to resolve the current request path.
$redirect_url = home_url( remove_query_arg( 'redirect_url' ) );
$loginPostId = $attributes['loginPostId'] ?? null;
if ( ! is_user_logged_in() && ! empty( $attributes['loginLinkEnabled'] ) ) {
if ( ! empty( $loginPostId ) ) {
$link['url'] = add_query_arg( 'redirect_url', $redirect_url, get_permalink( $attributes['loginPostId'] ) );
} else {
$link['url']= wp_login_url( $redirect_url );
}
if ( ! empty( $attributes['loginLabel'] ) ) {
$link['label'] = $attributes['loginLabel'];
} else {
$link['label'] = __( 'Login', 'commerce-pilot' );
}
} elseif ( is_user_logged_in() && ! empty( $attributes['logoutLinkEnabled'] ) ) {
$link['url']= wp_logout_url( $redirect_url );
if ( ! empty( $attributes['logoutLabel'] ) ) {
$link['label'] = $attributes['logoutLabel'];
} else {
$link['label'] = __( 'Logout', 'commerce-pilot' );
}
}
// Skip, if no link should be displayed.
if ( empty( $link['url'] ) || empty( $link['label'] ) ) {
return;
}
// Inherit block styles from the navigation link.
$css_classes = [
'wp-block-navigation-item',
'wp-block-navigation-link',
];
// Mark the menu item as active.
if ( $loginPostId && is_singular() && get_queried_object_id() === (int) $loginPostId ) {
$css_classes[] = 'current-menu-item';
}
$extra_wrapper_attributes = [
'class' => implode( ' ' , $css_classes ),
];
?>
<li <?php echo get_block_wrapper_attributes( $extra_wrapper_attributes ); ?>>
<a
class="wp-block-navigation-item__content"
href="<?php echo esc_url( $link['url'] ); ?>">
<?php echo esc_html( $link['label'] ); ?>
</a>
</li>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment