questions

PHP: Check if current URL is part of defined URL

Rate this post

I want to check of the current URL is part of a pre-defined URL.

For example: I want to check if the domain example.com/shop/ is part of the viewed URL.

I’m using the following function to get the current URL and a pre-defined ($shop_page_url) URL:

function shop_page_url_condition(){
    global $wp;
    $shop_page_id = get_option( 'woocommerce_shop_page_id' );
    $shop_page_url = get_permalink($shop_page_id );
    $current_url = home_url(add_query_arg(array(), $wp->request).'/');
    if( $shop_page_url == $current_url) {
        return true;
    } else {
        return false;
    }
}

In this case it only works if the $shop_page_url is the same as the $current_url.

But I want to check if pre-defined URL ($shop_page_url) is part of the current URL (example.com/shop/page/7).

 

✔️Solution:

Is strpos what you’re looking for?

If I’m understanding correctly, you would just want to see if it returns false:

if ( strpos( $current_url, $shop_page_url ) !== false ) {
    return true;
} else {
    return false;
}

You could also simplify the above if you wanted to save a few lines of code:

return strpos( $current_url, $shop_page_url ) !== false;

strpos() >= 0 won’t work. If the substring is not found at all, doing that will end up returning true, which is not what you’d want here!

Leave a Reply

Your email address will not be published.

Back to top button