Search code examples
phpwordpresswoocommercestorefront

woocommerce/sensei dynamic/changeable button in secondary menu


I would like to add a button to my secondary menu which points to a 'my account' page and the text on the button should display 'my account' if the user is logged in.

If the user is logged out, they would see a button that says 'register' and points to a login page.

Anyone know if this is possible?

I think i am close but i am unsure if it's possible:

This is in my child theme's functions.php:

    function storefront_secondary_navigation() {
        if ( has_nav_menu( 'secondary' ) ) {
            ?>
            <nav class="secondary-navigation" role="navigation" aria-label="<?php esc_html_e( 'Secondary Navigation', 'storefront' ); ?>">
                <p>wat is deze</p>
                <?php


                        if( ! is_user_logged_in()) {
                        wp_nav_menu(
                                array(
                                    'theme_location'    => 'secondary',
                                    'fallback_cb'       => '',

                                )

                            );

                        }
                        else{
                        wp_nav_menu(
                                array(
                                    'theme_location'    => 'secondary',
                                    'fallback_cb'       => '',

                                )

                            );

                        }
echo "menu locations";
$hoi = get_nav_menu_locations();
var_dump($hoi);
//outputs an array with 3 objects: 'primary', 'secondary', and 'handheld'.
                ?>
            </nav><!-- #site-navigation -->
            <?php
        }
    }

Solution

  • A pure CSS solution:

    In Wordpress, the <body> element has the class logged-in if a user is logged in. So you can use this to hide the right button:

    Add this to your style.css:

    #menu-item-8071 {
        display: none;
    }
    
    body.logged-in #menu-item-8071 {
        display: block;
    }
    
    body.logged-in #menu-item-8011 {
        display: none;
    }
    

    Instead of using menu-items ids as css selector, you can add your own css classes to your buttons. First you have to enable "CSS Classes" in the Screen Options (at top of the menu editor page). Now you can enter additional css classes for each menu item.

    e.g.:

    • show-if-logged-in for the first button
    • hide-if-logged-in for the second button

    So you can use this css code:

    .show-if-logged-in {
        display: none;
    }
    
    body.logged-in show-if-logged-in {
        display: block;
    }
    
    body.logged-in .hide-if-logged-in {
        display: none;
    }