WooCommerce maintaince mode by using php

The question:

I would like to open up certain parts of my website where the remaining pages should only be accessible as an administrator on the website.

I have made a maintaince plugin and it all works as it should. However, I have trouble filtering users by which page they are visiting.

I would like to open up a specific product category, as well as all products that belong to this category.

If I am not logged in as an administrator, I can not access the product category and products belonging to it.

My code is below – anyone can see what I’m doing wrong?

Thanks.

<?php

@return void

function ng_maintenance_mode() {
    global $pagenow;

    if ( ! current_user_can('administrator') ) {

        if ( $pagenow !== 'wp-login.php' && ! is_product_category( 232 ) && ! has_term( 232, 'product_cat' ) {

                    header( $_SERVER["SERVER_PROTOCOL"] . ' 503 Service Temporarily Unavailable', true, 503 );
                    header( 'Content-Type: text/html; charset=utf-8' );
                    if ( file_exists( plugin_dir_path( __FILE__ ) . 'views/maintenance.php' ) ) {
                        require_once( plugin_dir_path( __FILE__ ) . 'views/maintenance.php' );
                    }
                    die();

                }

        }

}

add_action( 'wp_loaded', 'ng_maintenance_mode' );

?>

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

You need to replace the following:

if ( ! current_user_can('administrator') ) {

with

if ( ! current_user_can('manage_options') ) {

This is because there’s no such capability as administrator. There are a couple of administrator-only capabilities, and manage_options is a reliable one to use.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment