Displaying product categories on WooCommerce page for non-registered users

Currently, I am working on a WordPress WooCommerce website and I have encountered an issue. I want to implement a logic where users cannot see product categories, subcategories, or product pages without logging in, and instead be redirected to the login page.

add_action( 'template_redirect', 'wc_redirect_non_logged_to_login_access');
function wc_redirect_non_logged_to_login_access() {

    if ( !is_user_logged_in() && ( is_woocommerce() || is_shop() || is_cart() || is_checkout() ) ) {
        wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id')) );
        exit();
    }
}

However, even after logging in, when I try to access a product category page, it still redirects me to the login page. Upon debugging, I noticed that the product category page shows as not logged in. I'm puzzled as to why this happens after successfully logging in. Can someone please provide some possible solutions or insights?

Answer №1

Perhaps the issue lies with the woocommerce_myaccount_page_id setting.
Attempt to retrieve it using the slug (assuming the page slug is "my-account"):

add_action( 'template_redirect', 'wc_redirect_non_logged_to_login_access');
function wc_redirect_non_logged_to_login_access() {
    if ( !is_user_logged_in() && ( is_woocommerce() || is_shop() || is_cart() || is_checkout() ) ) {
        wp_redirect( home_url( '/my-account/' ) );
        exit();
    }
}

or by utilizing the ID of the My Account page:

add_action( 'template_redirect', 'wc_redirect_non_logged_to_login_access');
function wc_redirect_non_logged_to_login_access() {
    if ( !is_user_logged_in() && ( is_woocommerce() || is_shop() || is_cart() || is_checkout() ) ) {
        $my_account_page_id = 2;
        wp_redirect( get_page_link( $my_account_page_id )  );
        exit();
    }
}

This code has been thoroughly tested and proven effective. Implement it in your active theme's functions.php file.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Eliminate Selection from Bundle Product in Magento

I am looking to programmatically remove all options from a bundle product using only the SKU of the product. Here is my code: $bundled = Mage::getModel('catalog/product')->loadByAttribute('sku',THISISMYSKU); $selectionCollection = ...

The information transmitted from the Laravel controller is not syncing with the Vue variable as expected

I've been working on a web app with a dashboard using Laravel and Vue. While passing data from the controller to the Vue file, the data is received correctly. However, when I try to set it to a Vue variable, the value does not update in the variable. ...

How can I use AJAX to automatically populate a dropdown menu with cities in a PHP MVC application?

Within a PHP MVC setup, there is a file named city.php in the model section which defines a city class. The city class contains a method called getCitiesByProvince('ProvinceId') that retrieves all cities for a given province. When a user picks ...

Step-by-Step Guide: Unveiling a Particular Modal Post-Submission of Form with

My website has a form inside a modal, and when the form is submitted, I don't want the modal to close. However, I have encountered an issue because my SQL UPDATE statement redirects to the same page after updating the database. This disrupts the funct ...

Exploring the concept: Uploading images simultaneously on Facebook - Unraveling the

I am currently working on implementing an ajax-style submission form for File Upload. After successfully getting a progress bar updated, it seems like the whole logic is working fine. However, I recently observed Facebook and noticed that: 1) Facebook a ...

There seems to be an issue with my PHP code, as it is not successfully making

Having an issue with my code - no errors when I press update or add. Can someone provide assistance? The goal is to have data added to the database when the add button is pressed and updated in the database when the update button is pressed. <html> ...

Utilize AJAX to verify the content of a PHP variable within a Wordpress environment

After attempting multiple approaches without success, I am seeking advice from anyone who has experience with this particular issue. I have developed a custom post type that generates Public pages. However, I require certain information to only be accessi ...

Having trouble with the mysqli_query function, it's not working as expected. Can someone offer assistance?

Could use some help with my mysqli_query. It's not inserting into the database, even though it works in phpmyadmin SQL but not on the website. Here is my code: <form action="" method="POST> <input type="email" name="email" placeholder="P ...

Are AJAX submitted forms secure?

Recently, I have been using jQuery's $.ajax and $.post functions to submit form data. Now, I am contemplating using this approach for the login form on my e-commerce website. My primary concern is the security of the data transmitted through AJAX post ...

Troubleshooting an issue with jQuery remote validation in Internet Explorer, specifically related to PHP MySQL query results matching form entries

Encountering unusual behavior on Internet Explorer while working with a form and adding a remote rule in jQuery for username validation using "check_username.php". The code snippet below includes requiring a view.php script that implements jQuery scripts a ...

What is the method for accessing a JQuery mapping array in PHP?

I am attempting to transfer data from JQuery to PHP and then save it in the database. Here is my JQuery code snippet: var map = $.map(customFieldIds, function(value) { return { name: value, value: customFieldValues[value] ...

PHP integration with IBM Cloud storage

I am encountering an issue while attempting to establish a bucket and upload files on IBM cloud storage using PHP. I keep receiving an error 405 Method not allowed. Despite reviewing the documentation, which suggests utilizing S3, I have opted for the AWS ...

Configuring Laravel to operate on a specific port number?

Currently, I am utilizing nodejs, expressjs, and socket.io to trigger events on my web app via a mobile phone connected to the nodejs server. Although the app is primarily built in JavaScript, I have opted to use laravel for data storage within a database ...

What is the best way to choose which attributes from a class should be incorporated into an UPDATE dynamic query?

Example of a Model Class class Games { public $id = 0; public $date = null; public $player1_id = 0; public $player2_id = 0; public $score = null; public function save(){ if(empty($this->id)){ // perform INSE ...

How to Show PHP Errors using Serverpilot

I am in the process of updating my website from php5.6/mysql to php7.0/mysqli. Currently, I am using digitalocean with serverpilot.io as my hosting provider. However, I am facing an issue where I am unable to display PHP errors; instead, it just shows a wh ...

Executing an AJAX request to insert data into MySQL

After my extensive online search, I came across a solution that involves using ajax to set information in my database. While browsing through this page, I learned how to retrieve data from the database. My specific query is: can we also use ajax to set in ...

The Problem of Duplicate Queries in Wordpress SEO Yoast with Another Plugin

Here is a simple WordPress shortcode plugin code that I have along with the WordPress SEO Yoast enabled: function mySimpleFunction() { global $wpdb; $wpdb->query("insert into `anytable` (`column1`) values ('13')"); return '&a ...

Navigate through the items in my subnavbar by scrolling the content

HTML Code <div id="subnavigation"> <?php $verbindung = mysql_connect("host", "user" , "pw") or die("Verbindung zur Datenbank konnte nicht hergestellt werden"); mysql_select_db("db") or die ("Datenbank konnte nicht ausgewählt w ...

What could be causing this prepared statement to consistently display -1 rows affected?

I'm really struggling with this mysqli prepared statement and I just can't seem to figure out what's going wrong. I've spent a lot of time troubleshooting already, so let me start by showing you the code snippet (which is currently only ...

Following the implementation of the YITH ajax navigation filter, my jQuery scripts are no longer functioning as

I'm having trouble with using yith ajax navigation in my theme. Everything works perfectly until I click on an element to filter, at which point my jquery codes stop working. The team at yith suggests: If your product list contains JavaScript cod ...