WordPress.org

Make WordPress Core

Opened 3 months ago

Last modified 3 months ago

#53108 new enhancement

`get_theme_file_uri()` fails with query params

Reported by: zulaica Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 5.7.1
Component: Themes Keywords:
Focuses: Cc:

Description

get_theme_file_uri() fails to locate a file if it is supplied with any query params and incorrectly falls back to returning the parent theme's path to the file, including the supplied query params. This prevents the ability to use a bundler's versioning without adding complexity to registering scripts and styles.

<?php
get_theme_file_uri( '/js/script.js?id=41142aba6c0214da8ec1' );

// Expected output:
// 'https://domain.com/wp-content/themes/ChildTheme/js/script.js?id=41142aba6c0214da8ec1'

// Actual output:
// 'https://domain.com/wp-content/themes/ParentTheme/js/script.js?id=41142aba6c0214da8ec1'

file_exists() does not understand the query param when attempting to locate the file. One solution could be to use parse_url() to determine the file path used in the condition:

<?php // https://core.trac.wordpress.org/browser/tags/5.7.1/src/wp-includes/link-template.php#L4374
...
    } elseif ( file_exists( get_stylesheet_directory() . '/' . parse_url($file)['path'] ) ) {
...

Change History (3)

#1 @dd32
3 months ago

  • Component changed from General to Themes
  • Type changed from defect (bug) to enhancement

The functionality currently isn't designed to handle query arguments, it's intentionally to find a URI for a file.

I would say the expected use-case currently is something like this:

// preferably:
$uri = add_query_arg( 'id', '41142aba6c0214da8ec1', get_theme_file_uri( 'js/script.js' ) );

// will probably work most of the time, unless a plugin has filtered the URI to include query args:
$uri = get_theme_file_uri( 'js/script.js' ) . '?id=41142aba6c0214da8ec1';

Marking this as an enhancement instead as a result, the fact that this works for parent themes is kind of an unexpected side effect of simply not checking to see if the file exists (ie. get_theme_file_url( '404.js' ) returns a URI even though the file doesn't exist).

#2 @zulaica
3 months ago

I see! Okay, that all makes sense. I wasn't aware of add_query_arg(), but that fits the bill perfectly. Thanks!

I agree that the unintended side effect should be fixed to better follow the intent of the function, but I'm concerned that some existing themes may wind up breaking as a result of relying on this side effect.

#3 @zulaica
3 months ago

I can also see the argument against fixing the unintended side effect, that get_theme_file_uri () should handle query params given that a query is part of a URI's syntax. I have no strong opinion either way, just trying to consider potential complications.

Note: See TracTickets for help on using tickets.