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

如何将菜单项及其内容限制为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?

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路