I'm a developer who is relatively new to developing in PHP for WordPress, and I am working on a WordPress site that has a considerable amount of custom code in the site's theme. I have been enjoying using the WordPress Coding Standards tool, since it often makes me aware of PHP's gotchas and footguns.
One of the coding standards that seems to come up a lot is related to variable naming, which typically validate against three criteria:
- Use
$snake_case
- Don't override WordPress global variables like
$post
and$id
. - Prefix all global variables with
$theme_name_
to have the effect of namespacing these variables to avoid conflicts with globals from WP or other packages.
In other languages I am more experienced with like JavaScript, I tend to code in a functional style, and avoid polluting global scope by using IIFEs.
What I've seen so far with template files and template parts in WordPress themes seems to suggest it is impossible not to pollute global scope, so I'm very curious to know if I'm unaware of a better practice, or otherwise missing something.
For example, again comparing with JavaScript, if I wanted to write a template file, I could do something like this:
export function template_html (args) {
const title = args['title'];
const subtitle = args['subtitle'];
return `
<h1>${title}</h1>
<h2>${subtitle}</h2>
<p>Hello world</p>
`;
}
Whereas in WordPress, I have something like the following:
<?php
/**
* This is a template file
*
* @package my-theme
*/
$my_theme_title = $args['title'];
$my_theme_subtitle = $args['subtitle'];
?>
<h1><?php echo esc_html( $my_theme_title ); ?></h1>
<h2><?php echo esc_html( $my_theme_subtitle ); ?></h2>
<p>Hello world</p>
Is this really as good as it gets? I am still learning PHP require
semantics and it seems worrying that if you can't avoid populating the global variable scope, even if the tooling helps you avoid clobbering WP variables, you have no guarantees that you haven't reused your own namespaced global variable names across multiple files and could end up with initial values that you don't expect since they were populated in a different file, earlier in the require chain.
get_template_part
][developer.wordpress.org/reference/functions/get_template_part/]?.php
file you use to implement your template part has exactly the same properties with regard to global variable scope? I don't see how that would address my concerns.require
while you are already building the template. If you want to go around this, you'll have to skip WP's template system and build something yourself with functions that generate the templates