URL String Check in WP

User
wordpress template_redirect get if url has some string
Assistant
To check if a URL contains a specific string during the `template_redirect` action in WordPress, you can use the following code snippet in your theme's `functions.php` file:

function custom_template_redirect() {
    // Get the current URL
    $current_url = home_url(add_query_arg(array(), $wp->request));

    // Check if the URL contains the specific string
    if (strpos($current_url, 'your-string') !== false) {
        // Perform your action here
        // For example, you can redirect to another page
        wp_redirect('https://example.com/another-page');
        exit;
    }
}
add_action('template_redirect', 'custom_template_redirect');

### Explanation:
1. **Get the Current URL:** The `$current_url` variable constructs the current URL using `home_url()` and the current request.
2. **Check for String:** The `strpos()` function checks if the specified string (`'your-string'`) exists in the current URL.
3. **Redirect:** If the string is found, you can perform an action (like a redirect) using `wp_redirect()` and `exit` to stop the script.

### Note:
– Replace `'your-string'` with the actual string you want to check for in the URL.
– Adjust the redirect URL as needed.

Leave a Comment

Your email address will not be published. Required fields are marked *