Check request URL for pattern

I need help. I’m making a plugin in woo which add html when URL contains a specific word.

I used get_site_url, get_permalink, and others but strangely none was sending the information. Finally I decided use $_SERVER[REQUEST_URI] and works but on some pages doesn’t. Why is this happening? What can I do?

Solutions Collecting From Web of "Check request URL for pattern"

how’s the URL structure? Could you paste here?

If you’re URL follows this structure: http://example.com/?foo=bar, so you need to get the foo value with this:

if ( isset( $_GET['foo'] ) ) {
   $bar_value = $_GET['foo'];
   // Do whatever you want with $bar_value.
} else {
  // Do something else.
}

If that doesn’t work, you could test get_query_var()function, here is the link. This should work like the code below in a simple way.

Tell me if any of this worked for you.

I can’t say why $_SERVER['REQUEST_URI'] isn’t working sometimes, but here’s one way to check if the requested URL contains a phrase using the core WP class:

<?php

    global $wp;

    $magic_phrase = 'abracadabra';
    $request_path = $wp->request;

    if (preg_match('/.*'. $magic_phrase .'.*/', $request_path)) {
        // Phrase matches, do what you need here!
    }

?>

That’ll match any URL that contains “abracadabra” at any position in the URL. You can/should update the regex used to check the request path against your phrase to make sure you’re not matching paths you don’t intend to.

The core WP class does a bit of extra magic with the request to make sure it’s consistent and using it instead of server variables might help a bit.