- This topic has 5 replies, 2 voices, and was last updated 3 years, 3 months ago by
David.
-
AuthorPosts
-
January 25, 2023 at 7:11 am #2508578
Brian
Hello!
Goal: add dynamic WooCommerce menu bar item in navigation with hook in custom plugin.
I’ve added the following code to a hook element using
generate_menu_bar_itemswith the execute PHP option checked:<?php function add_loginout_link() { if ( !is_user_logged_in() ) { $item = '<a class="my-account-link" href="' . get_permalink( wc_get_page_id( 'myaccount' ) ) . '"> ➤ Log in </a>'; } elseif ( is_user_logged_in() ) { $item = '<a class="my-account-link" href="' . get_permalink( wc_get_page_id( 'myaccount' ) ) . '"> My Account </a>'; } echo $item; } add_loginout_link(); ?>It works pretty much exactly how I’d like, however this site defines
DISALLOW_FILE_EDITas true for security purposes which does not allow me to execute PHP in a hook element (I temporarily changed the config setting to test on a staging site which is how I know the code works for my needs).I have all site mods in a custom plugin.
How can I write this same function to still apply to
generate_menu_bar_itemsbut in my custom plugin instead of a hook element in GP?January 25, 2023 at 7:37 am #2508605David
StaffCustomer SupportHi there,
you could use the
add_actionfunction to hook in your callback.So instad of:
add_loginout_link();you can do:
add_action( 'generate_menu_bar_items', 'add_loginout_link' );January 25, 2023 at 9:01 am #2508823Brian
Bingo!
That worked perfect, thank you so much!
This might be for a separate thread, but in the off chance I wanted the “logged in state” only to have a dropdown submenu (to show direct links to the Dashboard, Orders, Downloads, etc), is that a relatively easy add in? Could that dropdown menu pull from a menu that was setup in Appearance > Menus?
Thanks again!
January 26, 2023 at 3:15 am #2509559David
StaffCustomer SupportOK, if it has to be a button in the menu bar items.
Then an alternative solution would be to use the GP Block element:https://docs.generatepress.com/article/block-element-hook/
You can add a core Navigation Block.
And add it themenu_bar_itemshook.Set the Display Rules > Location to
Entire Site
And the User > Logged In.That menu can contain the sub menu items
Then repeat that for the User > logged Out.
Is that an option ?
January 27, 2023 at 8:00 am #2511218Brian
Oh I very much like that as an option—you’re good!
I’ll play around a bit but I’ll likely just start with no dropdown and the first option we spoke about but will definitely keep the Block Element idea in the back of my mind as well.
Thanks so much!
January 28, 2023 at 2:20 am #2511790David
StaffCustomer SupportYou’re welcome!
-
AuthorPosts
- You must be logged in to reply to this topic.