I’m working on a WordPress site and need to figure out how to send different numeric values to my template parts. Right now I have something like this:
I have two files called homepage-header.php and homepage-content.php that get loaded by these calls. The problem is I need each template file to receive a different number value so they can display different content. Is there any method to send these variables when calling the template parts? I’ve been searching but can’t find a clean solution for this.
Here’s another approach that works great - use locate_template with include instead of get_template_part. Set your variables right before the include and they’ll be available in the template scope. Like $header_number = 15; include(locate_template('partials/homepage-header.php')); - you get direct variable access without messing with globals or WordPress version issues. I’ve done this on several client sites when I needed better control over data flow between templates. Rock solid every time.
you can also use get_template_part’s third param to pass data. since WP 5.5, just do get_template_part(‘partials/homepage’, ‘header’, array(‘number’ => 10)) and grab it with $args[‘number’] in your template. way cleaner than globals and doesn’t mess with the global scope.
WordPress doesn’t let you pass variables directly through get_template_part, but here’s a simple fix I use all the time. Just set your variables as globals before calling the template part, then grab them inside your template files. Like this: $GLOBALS[‘my_number’] = 5; before your get_template_part call, then $my_number = $GLOBALS[‘my_number’]; inside homepage-header.php. Works great across different WordPress versions and keeps things clean without needing plugins or messy workarounds.