WordPress.org

Make WordPress Core

Opened 3 months ago

Last modified 3 months ago

#53541 new enhancement

Arguments passed to load_template() should be extracted

Reported by: caseymilne Owned by:
Milestone: Awaiting Review Priority: normal
Severity: minor Version: 5.8
Component: General Keywords: dev-feedback 2nd-opinion
Focuses: Cc:

Description

As was originally voiced in this thread when ability to pass arguments to templates was added in v5.5, these arguments should be extracted. As a plugin developer today, the new $args passing does provide as good an experience in terms of simplicity and documentation as the older method of passing query vars. This is because query vars are extracted. So if I'm building a plugin that has a product template and I want to render out $product variables, or pass an object in $product, then which would I prefer to offer to theme developers:

Use $args['product'] to access the $product object.

OR

Use $product to access the product object.

Clearly having the vars extracted makes them easier to access. Perhaps the objection to this is that aside from the exception made for query vars we normally try to avoiding using extract(). However in this case I think an exception is warranted. Otherwise the effort put into making argument passing available is somewhat wasted because plugin developers will likely prefer to use query vars simply because they are extracted automatically.

Another potential way to enable this would be through an option argument passed to load_template (which would have to first go through locate_template() as well, and that would be $extract_args = false, or $extract_args = true. I'd opt for the later to set the default to extract, but just having that option would let developers control the naming of variables they make available in templates.

Reference to the announcement, argument passing in 5.5 https://make.wordpress.org/core/2020/07/17/passing-arguments-to-template-files-in-wordpress-5-5/

load_template() on trak: https://core.trac.wordpress.org/browser/tags/5.7.1/src/wp-includes/template.php#L709

Change History (1)

#1 @joyously
3 months ago

If the author of the template expects the argument to be passed, they can certainly extract it themselves. Since the argument is optional, it makes sense for backward compatibility for core to not touch it, because the template file doesn't control where it is invoked.
It would be more flexible if the template calls functions to get the data needed, and those functions are filtered.
(Yes, I was opposed to adding the argument, because it makes it more difficult to write a backward compatible template.)

Note: See TracTickets for help on using tickets.