PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 5, 2022

[FIXED] PHP: Check if current URL is part of defined URL

 February 05, 2022     php, wordpress     No comments   

Issue

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!



Answered By - bdean531
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing