doukuang8166
2018-12-22 16:36
浏览 94
已采纳

如何将菜单项及其内容限制为Woocommerce中的已登录用户

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 none could see it without being login in?

图片转代码服务由CSDN问答提供 功能建议

在WordPress上,我正在使用Woocommerce插件设置我的在线商店。 我有一个生成定价表的PHP脚本。

但实际上每个人都可以看到它。

如何将其添加到我的WordPress菜单中,没有人可以在没有登录的情况下看到它?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongzongpeng6474 2018-12-22 16:43
    已采纳

    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.

    enter image description here

    Then once enabled, in your menu item you will be able to set a custom CSS class:

    enter image description here

    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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题