How to Block Unwanted Query Strings URLs in WordPress
If you are getting page indexing issue i.e., Duplicate without user-selected canonical on Google Search Console, then you are going to get an answer in this article.
I’m writing a code snippet for WordPress users that will help them permanently fix this ‘Duplicate without user-selected canonical’ page indexing issue.
Page indexing > Duplicate without user-selected canonical
I was checking out page indexing issues on Google search console then I found that, query string URLs that contains a question mark (?) and equal (=) sign inside URLs. I tried to run a link and it was loading my homepage but the link was wrong hence the canonical tag issue was raising and sending signal to search console.
Here is the example:
To prevent this error in Google search console, I have created the following snippets which you have to install on your WordPress website.
Block Unwanted Query Strings URLs in WordPress
function block_unwanted_query_strings() {
// Check if the request is for the admin area or if the user is logged in
if (is_admin() || is_user_logged_in()) {
return;
}
// Allow the WordPress search query and block all other query strings
if (!empty($_GET) && !(isset($_GET['s']) && count($_GET) == 1)) {
wp_die('Forbidden');
}
}
add_action('init', 'block_unwanted_query_strings');
See the error in the image below which the bots will get after you activate the above snippet.
You won’t have to face any duplicate without user-selected canonical errors with unwanted query strings URLs in Google search console.
Note: You need to login to your WordPress Dashboard using this url example.com/wp-login.php
(because wp-admin won’t work)