How to Dynamically Modify Request URL or Parameters in WordPress Functions wp_remote_get or wp_remote_post

Do you need to try a WordPress theme? Create a temp site now!

Sharing is caring!

WordPress has lots of filters and actions which are known as actions. That way you can achieve a lot of things without having to modify the WordPress source code directly also known as hacking the core.

There is a WordPress filter for the http_request_args but there isn’t one for ‘http_request_url‘ just yet.

To modify the request parameters is pretty easy. Just hook into http_request_args filter and update whatever you need.

Using an Inline callback/closure (quick & easy but hard to unhook so not recommended)

It’s better to use a function name or call a class method because the callbacks may be hard to unhook in case you want to turn that callback/closure off completely or depending on certain values in $url or $args parameters.

add_filter( 'http_request_args', function( $args, $url ) {
    if (strpos($url, 'doing_wp_cron') !== false) { // skip cron job requests
        return $args;
    }
    
    // modify the arguments
    $args['headers']['referer'] = site_url(); // set the referrer
    //$args['timeout'] = 45;
    
    return $args;
}

Way to update the Request parameters via a callback (Recommended)


/**
 * Modify the request parameters before sending the request
 * @copyright Svetoslav Marinov | https://wpsandbox.net
 * @see https://wpsandbox.net/1293
 * @param array $args
 * @param string $url
 * @return array
 */
function wpsandbox_post1293_modify_req_params_only($args, $url) {
    if (strpos($url, 'doing_wp_cron') !== false) {
        return $args;
    }

    // Return early if the URL is not my url
    if (strpos($url, 'mydomain.com') === false) {
        return $args;
    }

    // needed for the fonts to work
    $args['headers']['referer'] = site_url();

    // ca't change url but can add this
    $args['body']['req_id'] = sha1(mt_rand(9, 9999) . microtime(true));

    return $args;
}

add_filter( 'http_request_args', 'wpsandbox_post1293_modify_req_params_only', 10, 2 );

How to update the URL and/or Any Parameters

This might be the case when a plugin calls an external API and has hardcoded some parameters right in the $url that were supposed to be passed as POST parameters.

e.g. site.com/api/?req_id=wpsandbox1293

To be able modify that url or arguments we have to hook very early and use pre_http_request filter. If the callback returns a non-false value, that value will be used as if that value was returned by the request which can help us solve what we’re after.

/**
 * How to Modify URL or Parameters in WordPress Functions wp_remote_get or wp_remote_post
 * @copyright Svetoslav Marinov | https://wpsandbox.net
 * @see https://wpsandbox.net/1293
 */
class WPSandbox_Post1293_Modify_Url_Params
{
    private $req_id = '';
    public function __construct($params = [])
    {
        add_filter('pre_http_request', [$this, 'filterHttpRequest'], 10, 3);
        $this->req_id = sha1(mt_rand(9, 9999) . microtime(true));
    }

    public function filterHttpRequest($pre, $args, $url)
    {
        if (strpos($url, 'doing_wp_cron') !== false) { // skip cron requests
            return $pre;
        }

        // Return early if the URL is not my url
        if (strpos($url, 'mydomain.com') === false) {
            return $pre;
        }

        // Temporarily unhook to avoid infinite loop
        remove_filter('pre_http_request', [$this, 'filterHttpRequest'], 10);

        // Modify the URL
        $modified_url = $this->modifyUrl($url);

        // Add referer header
        $args['headers']['referer'] = site_url();

        // Make the request with the modified URL and headers
        $response = wp_remote_get($modified_url, $args);

        // Re-hook the filter
        add_filter('pre_http_request', [$this, 'filterHttpRequest'], 10, 3);

        return $response;
    }

    /**
     * Modify the URL by adding a request ID parameter
     * @param string $url
     * @return string
     */
    private function modifyUrl($url)
    {
        $parsed_url = parse_url($url);

        if (empty($parsed_url)) { // invalid url?
            return $url;
        }

        $query_params = [];
        parse_str(!empty($parsed_url['query']) ? $parsed_url['query'] : '', $query_params);

        if (empty($query_params['req_id'])) {
            $query_params['req_id'] = $this->req_id;
        }

        $query_string = http_build_query($query_params);
        $modified_url = $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'] . '?' . $query_string;

        return $modified_url;
    }
}

Method Explanations

Filter Method: The filterHttpRequest method is responsible for modifying the request.

  • Parameters: It takes three parameters: $pre, $args, and $url.
  • Skipping Cron Requests: It checks if the URL contains wp_doing_cron and returns $pre if true to skip cron requests.
  • URL Check: It checks if the URL contains mydomain.com. If not, it returns $pre to process only specific URLs.
  • Temporary Unhooking: It temporarily removes the filter to avoid infinite loops when making the modified request.
  • Modify URL: It calls the modifyUrl method to modify the URL.
  • Add Header: It adds a referer header to the request arguments.
  • Make Request: It makes a new request with the modified URL and updated arguments.
  • Re-hooking: It re-hooks the filter after the request is made.
  • Return Response: It returns the response of the modified request.

URL Modification Method: The modifyUrl method modifies the URL by adding a request ID parameter.

  • Parse URL: It parses the URL to get its components.
  • Check Validity: It checks if the parsed URL is valid.
  • Parse Query String: It parses the query string into an associative array.
  • Add Request ID: It adds the req_id parameter if it doesn’t already exist.
  • Rebuild URL: It rebuilds the URL with the modified query string.
  • Return Modified URL: It returns the modified URL.

Use Case

This setup is particularly useful when you need to dynamically add query parameters, such as an API key, to URLs for specific services (e.g., Google Fonts) while making HTTP requests in WordPress.

By leveraging WordPress hooks creatively, we can modify URLs and their parameters even in the absence of a direct http_request_url filter. This method ensures that your HTTP requests are flexible and can include necessary parameters dynamically, enhancing the functionality and security of your WordPress site.

Sharing is caring!

Do you need to try a WordPress theme? Create a temp site now!
This code shared in this post/site is provided "AS IS" without any warranties or guarantees of any kind. The authors and distributors of this code cannot be held responsible for any damage, data loss, or other issues that may arise from its use. It is strongly recommended that you test this code in a staging environment before deploying it to a live site. Always ensure you have proper backups and understand the implications of running this code on your WordPress installation. Use at your own risk.

Leave a Comment

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