Passer une variable à get_template_part
-
-
J'aieu [àpeuprès lamême questionet je l'aifaitfonctionner] (https://wordpress.stackexchange.com/questions/270166/pass-a-variable-to-get-template-part) avec `set_query_var`et`get_query_var`,cependant c'étaitpour utiliser les valeurs d'untableau `$ args` quiestpassé à un` WP_Query`.Celapourrait être utilepour d'autrespersonnes qui commencent à apprendre cela.Had [about the same question and got it to work](https://wordpress.stackexchange.com/questions/270166/pass-a-variable-to-get-template-part) with `set_query_var` and `get_query_var`, however this was for using the values of an `$args` array that is passed to a `WP_Query`. Might be helpful for other people starting to learn this.
- 0
- 2017-06-14
- lowtechsun
-
@Florian s'il vousplaît voir https://wordpress.stackexchange.com/a/373230/54986et marquez comme une réponse le cas échéant - c'estmaintenant une chosepriseen charge depremière classe@Florian please see https://wordpress.stackexchange.com/a/373230/54986 and mark as an answer if appropriate - it's now a first-class supported thing
- 0
- 2020-08-18
- Selrond
-
13 réponses
- votes
-
- 2015-02-02
Aufuret àmesure que lesmessages sont configurés via
the_post()
(respectivement viasetup_postdata()
)et sont donc accessibles via l'API (get_the_ID()
parexemple),supposons quenousbouclons sur unensemble d'utilisateurs (commesetup_userdata()
remplit les variablesglobales de l'utilisateur actuellement connecté et n'estpas utilepour cettetâche)et essaie d'afficher lesmétadonnéespar utilisateur:<?php get_header(); // etc. // In the main template file $users = new \WP_User_Query( [ ... ] ); foreach ( $users as $user ) { set_query_var( 'user_id', absint( $user->ID ) ); get_template_part( 'template-parts/user', 'contact_methods' ); }
Ensuite,dansnotrefichier
wpse-theme/template-parts/user-contact_methods.php
,nous devons accéder à l'ID utilisateur:<?php /** @var int $user_id */ $some_meta = get_the_author_meta( 'some_meta', $user_id ); var_dump( $some_meta );
C'esttout.
L'explicationesten faitexactement au-dessus de lapartie que vous avez citée dans votre question:
Cependant,
load_template()
,quiest appeléindirectementparget_template_part()
extraittoutes les variables de requêteWP_Query
,dans laportée de lemodèle chargé.Lafonctionnative PHP
extract()
"extrait" les variables (lapropriétéglobal $wp_query->query_vars
)et place chaquepartie dans sapropre variable qui aexactement lemêmenom que la clé. En d'autrestermes:set_query_var( 'foo', 'bar' ); $GLOBALS['wp_query'] (object) -> query_vars (array) foo => bar (string 3) extract( $wp_query->query_vars ); var_dump( $foo ); // Result: (string 3) 'bar'
As posts get their data set up via
the_post()
(respectively viasetup_postdata()
) and are therefore accessible through the API (get_the_ID()
for e.g.), let's assume that we are looping through a set of users (assetup_userdata()
fills the global variables of the currently logged in user and isn't useful for this task) and try to display meta data per user:<?php get_header(); // etc. // In the main template file $users = new \WP_User_Query( [ ... ] ); foreach ( $users as $user ) { set_query_var( 'user_id', absint( $user->ID ) ); get_template_part( 'template-parts/user', 'contact_methods' ); }
Then, in our
wpse-theme/template-parts/user-contact_methods.php
file, we need to access the users ID:<?php /** @var int $user_id */ $some_meta = get_the_author_meta( 'some_meta', $user_id ); var_dump( $some_meta );
That's it.
The explanation is actually exactly above the part you quoted in your question:
However,
load_template()
, which is called indirectly byget_template_part()
extracts all of theWP_Query
query variables, into the scope of the loaded template.The native PHP
extract()
function "extracts" the variables (theglobal $wp_query->query_vars
property) and puts every part into its own variable which has exactly the same name as the key. In other words:set_query_var( 'foo', 'bar' ); $GLOBALS['wp_query'] (object) -> query_vars (array) foo => bar (string 3) extract( $wp_query->query_vars ); var_dump( $foo ); // Result: (string 3) 'bar'
-
fonctionnetoujourstrèsbienstill working great
- 1
- 2019-06-11
- middlelady
-
- 2015-02-04
Lafonction
hm_get_template_part
de humanmade estextrêmementbon dans ce domaineet je l'utilisetout letemps.Vous appelez
hm_get_template_part( 'template_path', [ 'option' => 'value' ] );
puis à l'intérieur de votremodèle,vous utilisez
$template_args['option'];
pour renvoyer la valeur. Ilfait de lamiseen cacheet tout,mais vouspouvez le supprimer si vous le souhaitez.
Vouspouvezmême renvoyer lemodèle rendu sousforme de chaîneen passant
'return' => true
dans letableau clé/valeur./** * Like get_template_part() put lets you pass args to the template file * Args are available in the tempalte as $template_args array * @param string filepart * @param mixed wp_args style argument list */ function hm_get_template_part( $file, $template_args = array(), $cache_args = array() ) { $template_args = wp_parse_args( $template_args ); $cache_args = wp_parse_args( $cache_args ); if ( $cache_args ) { foreach ( $template_args as $key => $value ) { if ( is_scalar( $value ) || is_array( $value ) ) { $cache_args[$key] = $value; } else if ( is_object( $value ) && method_exists( $value, 'get_id' ) ) { $cache_args[$key] = call_user_method( 'get_id', $value ); } } if ( ( $cache = wp_cache_get( $file, serialize( $cache_args ) ) ) !== false ) { if ( ! empty( $template_args['return'] ) ) return $cache; echo $cache; return; } } $file_handle = $file; do_action( 'start_operation', 'hm_template_part::' . $file_handle ); if ( file_exists( get_stylesheet_directory() . '/' . $file . '.php' ) ) $file = get_stylesheet_directory() . '/' . $file . '.php'; elseif ( file_exists( get_template_directory() . '/' . $file . '.php' ) ) $file = get_template_directory() . '/' . $file . '.php'; ob_start(); $return = require( $file ); $data = ob_get_clean(); do_action( 'end_operation', 'hm_template_part::' . $file_handle ); if ( $cache_args ) { wp_cache_set( $file, $data, serialize( $cache_args ), 3600 ); } if ( ! empty( $template_args['return'] ) ) if ( $return === false ) return false; else return $data; echo $data; }
The
hm_get_template_part
function by humanmade is extremely good at this and I use it all the time.You call
hm_get_template_part( 'template_path', [ 'option' => 'value' ] );
and then inside your template, you use
$template_args['option'];
to return the value. It does caching and everything, though you can take that out if you like.
You can even return the rendered template as a string by passing
'return' => true
into the key/value array./** * Like get_template_part() put lets you pass args to the template file * Args are available in the tempalte as $template_args array * @param string filepart * @param mixed wp_args style argument list */ function hm_get_template_part( $file, $template_args = array(), $cache_args = array() ) { $template_args = wp_parse_args( $template_args ); $cache_args = wp_parse_args( $cache_args ); if ( $cache_args ) { foreach ( $template_args as $key => $value ) { if ( is_scalar( $value ) || is_array( $value ) ) { $cache_args[$key] = $value; } else if ( is_object( $value ) && method_exists( $value, 'get_id' ) ) { $cache_args[$key] = call_user_method( 'get_id', $value ); } } if ( ( $cache = wp_cache_get( $file, serialize( $cache_args ) ) ) !== false ) { if ( ! empty( $template_args['return'] ) ) return $cache; echo $cache; return; } } $file_handle = $file; do_action( 'start_operation', 'hm_template_part::' . $file_handle ); if ( file_exists( get_stylesheet_directory() . '/' . $file . '.php' ) ) $file = get_stylesheet_directory() . '/' . $file . '.php'; elseif ( file_exists( get_template_directory() . '/' . $file . '.php' ) ) $file = get_template_directory() . '/' . $file . '.php'; ob_start(); $return = require( $file ); $data = ob_get_clean(); do_action( 'end_operation', 'hm_template_part::' . $file_handle ); if ( $cache_args ) { wp_cache_set( $file, $data, serialize( $cache_args ), 3600 ); } if ( ! empty( $template_args['return'] ) ) if ( $return === false ) return false; else return $data; echo $data; }
-
Inclure 1300 lignes de code (degithub HM) auprojetpourpasser unparamètre à unmodèle?Impossible defaire cela dansmonprojet :(Include 1300 lines of code(from github HM) to the project to pass one parameter to a template? Can not do this in my project :(
- 1
- 2019-09-04
- Gediminas
-
Vouspouvez simplementinclure le code qu'il a collé ci-dessus dans votrefunctions.php ...You can just include the code he pasted above to your functions.php...
- 3
- 2019-11-15
- DokiCRO
-
- 2016-06-04
Je regardais autour demoiet j'aitrouvé une variété de réponses.Cela semble à unniveaunatif,Wordpresspermet d'accéder aux variables dans lesparties dumodèle.J'aitrouvé que l'utilisation de l'inclusion associée à Locate_templatepermettait à laportée des variables d'être accessible dans lefichier.
include(locate_template('your-template-name.php'));
I was looking around and have found a variety of answers. Its seems at a native level, Wordpress does allow for variables to be accessed in Template parts. I did find that using the include coupled with locate_template did allow for variables scope to be accessible in the file.
include(locate_template('your-template-name.php'));
-
Utiliser `include`ne passerapas [themecheck] (https://github.com/anhskohbo/wp-cli-themecheck).Using `include` won't pass [themecheck](https://github.com/anhskohbo/wp-cli-themecheck).
- 0
- 2017-06-14
- lowtechsun
-
Avons-nous vraimentbesoin de quelque chose qui ressemble au vérificateur W3Cpour lesthèmes WP?Do we really need something that is like the W3C checker for WP Themes?
- 1
- 2019-08-15
- Fredy31
-
- 2017-08-05
// you can use any value including objects. set_query_var( 'var_name_to_be_used_later', 'Value to be retrieved later' ); //Basically set_query_var uses PHP extract() function to do the magic. then later in the template. var_dump($var_name_to_be_used_later); //will print "Value to be retrieved later"
Je recommande de lire sur lafonction PHP Extract ().
// you can use any value including objects. set_query_var( 'var_name_to_be_used_later', 'Value to be retrieved later' ); //Basically set_query_var uses PHP extract() function to do the magic. then later in the template. var_dump($var_name_to_be_used_later); //will print "Value to be retrieved later"
I recommend to read about PHP Extract() function.
-
- 2016-09-11
J'ai rencontré lemêmeproblème sur unprojet sur lequelje travaille actuellement.J'ai décidé de créermonproprepetit plugin qui vouspermet depasserplusexplicitement des variables àget_template_parten utilisant unenouvellefonction.
Au cas où cela vous serait utile,voici lapage correspondante sur GitHub: https://github.com/JolekPress/Get-Template-Part-With-Variables
Et voici unexemple de sonfonctionnement:
$variables = [ 'name' => 'John', 'class' => 'featuredAuthor', ]; jpr_get_template_part_with_vars('author', 'info', $variables); // In author-info.php: echo " <div class='$class'> <span>$name</span> </div> "; // Would output: <div class='featuredAuthor'> <span>John</span> </div>
I ran into this same issue on a project I'm currently working on. I decided to create my own small plugin that allows you to more explicitly pass variables to get_template_part by using a new function.
In case you might find it useful, here's the page for it on GitHub: https://github.com/JolekPress/Get-Template-Part-With-Variables
And here's an example of how it would work:
$variables = [ 'name' => 'John', 'class' => 'featuredAuthor', ]; jpr_get_template_part_with_vars('author', 'info', $variables); // In author-info.php: echo " <div class='$class'> <span>$name</span> </div> "; // Would output: <div class='featuredAuthor'> <span>John</span> </div>
-
- 2020-08-03
Àpartir de 5.5 ,il serapossible detransmettre des données auxmodèles viales différentesfonctions debase de chargement demodèles.
Toutes lesfonctions de chargement demodèles WordPressprendronten charge unparamètre supplémentaire de
$args
,quipermet aux auteurs dethèmes detransmettre untableau associatif de données aumodèle chargé.Lesfonctions quiprennenten charge cenouveauparamètre sont:get_header() get_footer() get_sidebar() get_template_part() locate_template() load_template()
Tous les hooks associés auxfonctionstransmettent également les données.
Pourplus d'informations: https://make.wordpress.org/core/2020/07/17/passing-arguments-to-template-files-in-wordpress-5-5/
Starting in 5.5, it will be possible to pass data to templates via the various core template-loading functions.
All of the WordPress template-loading functions will support an additional parameter of
$args
, which allows theme authors to pass along an associative array of data to the loaded template. The functions that support this new parameter are:get_header() get_footer() get_sidebar() get_template_part() locate_template() load_template()
Any hooks associated with the functions also pass along the data.
For more information: https://make.wordpress.org/core/2020/07/17/passing-arguments-to-template-files-in-wordpress-5-5/
-
Malheureusement,leparamètre `$ args`n'estpasexécuté via`extract () `donc vous devrezfaire`echo $ args ['foo'] `dans lemodèle.J'aurais aimé qu'il y ait une optionpourextraire les arguments aussi.Unfortunately the `$args` parameter isn't run through `extract()` so you'll need to do `echo $args['foo']` in the template. I wish there was an option to extract the args too.
- 0
- 2020-08-17
- powerbuoy
-
- 2016-08-20
J'aime leplugin Pods et leur fonctionpods_view . Celafonctionne demanière similaire à lafonction
hm_get_template_part
mentionnée dans la réponse de djb. J'utilise unefonction supplémentaire (findTemplate
dans le code ci-dessous)pour rechercher d'abord unfichier demodèle dans lethème actuel,et s'iln'estpastrouvé,il renvoie lemodèle avec lemêmenom dans le/templates
. Voici uneidée approximative de lafaçon dontj'utilisepods_view
dansmonplugin:/** * Helper function to find a template */ function findTemplate($filename) { // Look first in the theme folder $template = locate_template($filename); if (!$template) { // Otherwise, use the file in our plugin's /templates folder $template = dirname(__FILE__) . '/templates/' . $filename; } return $template; } // Output the template 'template-name.php' from either the theme // folder *or* our plugin's '/template' folder, passing two local // variables to be available in the template file pods_view( findTemplate('template-name.php'), array( 'passed_variable' => $variable_to_pass, 'another_variable' => $another_variable, ) );
pods_view
prend égalementen charge lamiseen cache,maisje n'en avaispasbesoinpourmesbesoins. Voustrouverezplus d'informations sur les arguments de lafonction dans lespages de documentation despods. Consultez lespages relatives aux pods_view et aux Miseen cachepartielle depageet parties demodèlesintelligents avec despods .I like the Pods plugin and their pods_view function. It works similar to the
hm_get_template_part
function mentioned in djb's answer. I use an additional function (findTemplate
in the code below) to search for a template file in the current theme first, and if not found it returns the template with the same name in my plugin's/templates
folder. This is a rough idea of how I'm usingpods_view
in my plugin:/** * Helper function to find a template */ function findTemplate($filename) { // Look first in the theme folder $template = locate_template($filename); if (!$template) { // Otherwise, use the file in our plugin's /templates folder $template = dirname(__FILE__) . '/templates/' . $filename; } return $template; } // Output the template 'template-name.php' from either the theme // folder *or* our plugin's '/template' folder, passing two local // variables to be available in the template file pods_view( findTemplate('template-name.php'), array( 'passed_variable' => $variable_to_pass, 'another_variable' => $another_variable, ) );
pods_view
also supports caching, but I didn't need that for my purposes. More information about the function arguments can be found in the Pods documentation pages. See the pages for pods_view and Partial Page Caching and Smart Template Parts with Pods. -
- 2018-12-18
Basé sur la réponse de @djben utilisant le code de l'homme.
Il s'agit d'une version allégée deget_template_part quipeut accepter des arguments. De cettefaçon,les variables sont étendues localement à cemodèle. Pasbesoin d'avoir
global
,get_query_var
,set_query_var
./** * Like get_template_part() but lets you pass args to the template file * Args are available in the template as $args array. * Args can be passed in as url parameters, e.g 'key1=value1&key2=value2'. * Args can be passed in as an array, e.g. ['key1' => 'value1', 'key2' => 'value2'] * Filepath is available in the template as $file string. * @param string $slug The slug name for the generic template. * @param string|null $name The name of the specialized template. * @param array $args The arguments passed to the template */ function _get_template_part( $slug, $name = null, $args = array() ) { if ( isset( $name ) && $name !== 'none' ) $slug = "{$slug}-{$name}.php"; else $slug = "{$slug}.php"; $dir = get_template_directory(); $file = "{$dir}/{$slug}"; ob_start(); $args = wp_parse_args( $args ); $slug = $dir = $name = null; require( $file ); echo ob_get_clean(); }
Parexemple dans
cart.php
:<? php _get_template_part( 'components/items/apple', null, ['color' => 'red']); ?>
Dans
apple.php
:<p>The apple color is: <?php echo $args['color']; ?></p>
Based on the answer from @djb using code from humanmade.
This is a lightweight version of get_template_part that can accept args. This way variables are scoped locally to that template. No need to have
global
,get_query_var
,set_query_var
./** * Like get_template_part() but lets you pass args to the template file * Args are available in the template as $args array. * Args can be passed in as url parameters, e.g 'key1=value1&key2=value2'. * Args can be passed in as an array, e.g. ['key1' => 'value1', 'key2' => 'value2'] * Filepath is available in the template as $file string. * @param string $slug The slug name for the generic template. * @param string|null $name The name of the specialized template. * @param array $args The arguments passed to the template */ function _get_template_part( $slug, $name = null, $args = array() ) { if ( isset( $name ) && $name !== 'none' ) $slug = "{$slug}-{$name}.php"; else $slug = "{$slug}.php"; $dir = get_template_directory(); $file = "{$dir}/{$slug}"; ob_start(); $args = wp_parse_args( $args ); $slug = $dir = $name = null; require( $file ); echo ob_get_clean(); }
For example in
cart.php
:<? php _get_template_part( 'components/items/apple', null, ['color' => 'red']); ?>
In
apple.php
:<p>The apple color is: <?php echo $args['color']; ?></p>
-
- 2020-08-18
Leparamètre
$args
pour lesfonctions de chargement demodèle vient de débarquer dans WordPress 5.5 «Eckstine» :Transmission de données auxfichiersmodèles
Lesfonctions de chargement demodèle (get_header (),get_template_part (),etc.) ont unnouvel argument $ args.Vouspouvez désormaistransmettre la valeur d’untableauentier de données à cesmodèles.
The
$args
parameter for template loading functions has just landed in WordPress 5.5 “Eckstine”:Passing data to template files
The template loading functions (get_header(), get_template_part(), etc.) have a new $args argument. So now you can pass an entire array’s worth of data to those templates.
-
- 2018-06-22
Et ça?
render( 'template-parts/header/header', 'desktop', array( 'user_id' => 555, 'struct' => array( 'test' => array( 1,2 ) ) ) ); function render ( $slug, $name, $arguments ) { if ( $arguments ) { foreach ( $arguments as $key => $value ) { ${$key} = $value; } } $name = (string) $name; if ( '' !== $name ) { $templates = "{$slug}-{$name}.php"; } else { $templates = "{$slug}.php"; } $path = get_template_directory() . '/' . $templates; if ( file_exists( $path ) ) { ob_start(); require( $path); ob_get_clean(); } }
En utilisant
${$key}
,vouspouvez ajouter les variables dans laportée de lafonction actuelle. Fonctionnepourmoi,rapideet facileet nefuitpas oun'estpas stocké dans laportéemondiale.How about this?
render( 'template-parts/header/header', 'desktop', array( 'user_id' => 555, 'struct' => array( 'test' => array( 1,2 ) ) ) ); function render ( $slug, $name, $arguments ) { if ( $arguments ) { foreach ( $arguments as $key => $value ) { ${$key} = $value; } } $name = (string) $name; if ( '' !== $name ) { $templates = "{$slug}-{$name}.php"; } else { $templates = "{$slug}.php"; } $path = get_template_directory() . '/' . $templates; if ( file_exists( $path ) ) { ob_start(); require( $path); ob_get_clean(); } }
By using
${$key}
you can add the variables into the current function scope. Works for me, quick and easy and its not leaking or stored into the global scope. -
- 2019-09-04
Pour ceux qui semblent être unmoyentrès simple depasser des variables,vouspouvezmodifier lafonctionpourinclure:
include (Locate_template ('YourTemplate.php',false,false));
Et vouspourrezensuite utilisertoutes les variables qui sont définies avant d'inclure lemodèle sans PASSERen plus chacunepour lemodèle.
Les crédits vont à: https://mekshq.com/passing-variables-via-get_template_part-wordpress/
For ones who looks very easy way to pass variables, you can change function to include:
include( locate_template( 'YourTemplate.php', false, false ) );
And then you will be able to use all variables which are defined before you are including template without PASSING additionally each one for the template.
Credits goes to: https://mekshq.com/passing-variables-via-get_template_part-wordpress/
-
- 2020-09-02
Mise àjour
Comme selrond correctement répondu àpartir de Wordpress 5.5 get_template_part () ( voir changelog ) accepte désormais un troisièmeparamètre
array $args = array()
,qui sera disponible dans votrefichier demodèle sous lenom$args
.Voir cetexemple:
$bar = 'bar'; // get helper-my-template.php get_template_part( 'template-parts/helper', 'my-template', array( 'foo' => $bar, // passing this array possible since WP 5.5 ) );
Dans votrefichiermodèle
parexemple helper-my-template.php vouspouvezmaintenant accéder à votre variable comme ceci:
<?php /** * @var array $args */ $foo = $args['foo']; ?> <h1><?php echo $foo; ?></h1> <?php // will print 'bar' ?>
Update
As selrond correctly answered as of Wordpress 5.5 get_template_part() (see changelog) now accepts a third parameter
array $args = array()
, which will be available in your template file as$args
.See this example:
$bar = 'bar'; // get helper-my-template.php get_template_part( 'template-parts/helper', 'my-template', array( 'foo' => $bar, // passing this array possible since WP 5.5 ) );
In your template file
e.g. helper-my-template.php you can now access your variable like this:
<?php /** * @var array $args */ $foo = $args['foo']; ?> <h1><?php echo $foo; ?></h1> <?php // will print 'bar' ?>
-
- 2018-01-16
C'est la solutionexacteet cela abien fonctionné. https://developer.wordpress.org/reference/functions/set_query_var/
This is exact solution and it worked well. https://developer.wordpress.org/reference/functions/set_query_var/
Le WP Codex dit defaire ceci:
Mais commentpuis-je
echo $my_var
dans lapartie dumodèle?get_query_var($my_var)
ne fonctionnepaspourmoi.J'ai vu destonnes de recommandationspour utiliser à laplace
locate_template
.Est-ce lameilleurefaçon deprocéder?