On WordPress, I’m setting up my online shop with WooCommerce plugin. I have a PHP script that generate a pricing table.
But actually everyone can see it.
How can I add it to my WordPress menu and no one could see it without being login in?
Advertisement
Answer
In your script you will add is_user_logged_in()
in an IF
statement like:
function my_php_script_table(){ if( is_user_logged_in() ) { // The function code } else { return; // Exit } }
Now in your WordPress menu, you can add additional CSS classes enabling “css Classes” in the “Screen options” tab located up right of the “Menus” settings page.
Then once enabled, in your menu item you will be able to set a custom CSS class:
Then you will be able to hide from unlogged users this menu item using (here the additional class is hide_if_non_logged
):
add_action( 'wp_head', 'hide_if_non_logged_custom_inline_css', 500 ); function hide_if_non_logged_custom_inline_css() { if( ! is_user_logged_in() ) { ?><style>li.hide_if_non_logged { display: none !important;}</style><?php } }
Code goes in function.php file of your active child theme (or active theme). Tested and works.
You can even add redirection when user is not logged in for the page where the content that you want to hide from non logged users (You will need to set the correct page slug or ID in the code):
add_action( 'template_redirect', 'custom_unlogged_user_redirection' ); function custom_unlogged_user_redirection() { // Below set your correct page slug if ( ! is_user_logged_in() && is_page( 'pricing-table' ) ){ // Redirect to logout URL wp_safe_redirect( get_home_url() ); exit(); // Always exit } }
Code goes in function.php file of your active child theme (or active theme). Tested and works.