Modèles de type de message personnalisés à partir du dossier Plugin
7 réponses
- votes
-
- 2011-05-16
Vouspouvez utiliser le crochet defiltre
single_template
./* Filter the single_template with our custom function*/ add_filter('single_template', 'my_custom_template'); function my_custom_template($single) { global $post; /* Checks for single template by post type */ if ( $post->post_type == 'POST TYPE NAME' ) { if ( file_exists( PLUGIN_PATH . '/Custom_File.php' ) ) { return PLUGIN_PATH . '/Custom_File.php'; } } return $single; }
You can use
single_template
filter hook./* Filter the single_template with our custom function*/ add_filter('single_template', 'my_custom_template'); function my_custom_template($single) { global $post; /* Checks for single template by post type */ if ( $post->post_type == 'POST TYPE NAME' ) { if ( file_exists( PLUGIN_PATH . '/Custom_File.php' ) ) { return PLUGIN_PATH . '/Custom_File.php'; } } return $single; }
-
C'est une réponsegéniale.Veuillezpartager oùpuis-je obtenirtous lesmodèles de hooks disponiblestels que single_template.It's awesome answer. Please share were can I get all the template available hooks like single_template.
- 0
- 2013-05-02
- Gowri
-
@gowri Lefiltreest appelépar lafonction [`get_query_template ()`] (http://queryposts.com/function/get_query_template/).C'est un hook variable,donc lapremièrepartie `{$type} _template` changeen fonction duparamètrepassé à cettefonction.Voir [wp-includes/template.php] (http://svn.automattic.com/wordpress/tags/3.5/wp-includes/template.php)pour quelquesexemples courants@gowri The filter is called by the [`get_query_template()`](http://queryposts.com/function/get_query_template/) function. It's a variable hook, so the first part `{$type}_template` changes depending on what parameter is passed to that function. See [wp-includes/template.php](http://svn.automattic.com/wordpress/tags/3.5/wp-includes/template.php) for some common ones
- 6
- 2013-05-07
- shea
-
[Cetutoriel] (https://wpshout.com/hacking-the-wordpress-template-hierarchy/) couvre le hook single_template avec unebonneexplication.Unefois que vous avez compris les hooks,le commentaire de @ shea suggère une approcheplus simple que la réponse de @ Bainternet,en utilisant `add_filter ('single-movies_template','my_custom_template');` comme dans letutoriel lié.(Cette questionestfermée auxnouvelles réponses,je nepeux doncpas l'ajouter seule.)[This tutorial](https://wpshout.com/hacking-the-wordpress-template-hierarchy/) covers the single_template hook with good explanation. Once you understand the hooks, @shea's comment suggests a simpler approach than @Bainternet's answer, using `add_filter( 'single-movies_template', 'my_custom_template' );` as in the linked tutorial. (This question is closed to new answers, so I can't add it on its own.)
- 0
- 2017-09-26
- Greg Perham
-
Vouspouvez remplacer `PLUGIN_PATH`par [`plugin_dir_path (__FILE__) `] (https://developer.wordpress.org/reference/functions/plugin_dir_path/),puis supprimer lapremièrebarre oblique de votrenom defichier.Le chemin complet ressemblerait à ceci: `returnplugin_dir_path (__FILE__).'Custom_File.php'; `You could replace `PLUGIN_PATH` with [`plugin_dir_path( __FILE__ )`](https://developer.wordpress.org/reference/functions/plugin_dir_path/) and then remove the first slash from your file name. The full path would look something like this: `return plugin_dir_path( __FILE__ ) . 'Custom_File.php';`
- 2
- 2018-02-13
- Frits
-
Il sepeut que PLUGIN_PATH s'appelle WP_PLUGIN_DIR cesjours-ci.It could be PLUGIN_PATH is called WP_PLUGIN_DIR these days.
- 0
- 2019-03-26
- Hans Dash
-
PLUGIN_PATH agénéré uneerreur,voici unexcellent article quimontre commentfaire celaet cela afonctionnépourmoi hors de laboîte: https://wpsites.net/free-tutorials/load-single-template-from-plugin-for-different-post-types/PLUGIN_PATH threw an error, here's a great post that shows how to do this and it worked for me out of the box: https://wpsites.net/free-tutorials/load-single-template-from-plugin-for-different-post-types/
- 1
- 2019-05-02
- Nathan
-
existe-t-il unfiltrepour untype depublicationpersonnalisé?is there a filter for just a custom post type?
- 0
- 2019-09-06
- v3nt
-
- 2016-01-15
Réponsemise àjour
Versionpluspropreet plus courte.
function load_movie_template( $template ) { global $post; if ( 'movie' === $post->post_type && locate_template( array( 'single-movie.php' ) ) !== $template ) { /* * This is a 'movie' post * AND a 'single movie template' is not found on * theme or child theme directories, so load it * from our plugin directory. */ return plugin_dir_path( __FILE__ ) . 'single-movie.php'; } return $template; } add_filter( 'single_template', 'load_movie_template' );
Ancienne réponse
Ajout d'une vérificationpour unmodèle spécifique autype d'articlepersonnalisé dans le dossier duthème à la réponse @Brainternet.
function load_cpt_template($template) { global $post; // Is this a "my-custom-post-type" post? if ($post->post_type == "my-custom-post-type"){ //Your plugin path $plugin_path = plugin_dir_path( __FILE__ ); // The name of custom post type single template $template_name = 'single-my-custom-post-type.php'; // A specific single template for my custom post type exists in theme folder? Or it also doesn't exist in my plugin? if($template === get_stylesheet_directory() . '/' . $template_name || !file_exists($plugin_path . $template_name)) { //Then return "single.php" or "single-my-custom-post-type.php" from theme directory. return $template; } // If not, return my plugin custom post type template. return $plugin_path . $template_name; } //This is not my custom post type, do nothing with $template return $template; } add_filter('single_template', 'load_cpt_template');
Vouspouvez désormais laisser les utilisateurs duplugin copier lemodèle de votreplugin vers leurthèmepour le remplacer.
Dans cetexemple,lesmodèles doivent setrouver dans le répertoire racine dupluginet duthème.
Updated answer
Cleaner and shorter version.
function load_movie_template( $template ) { global $post; if ( 'movie' === $post->post_type && locate_template( array( 'single-movie.php' ) ) !== $template ) { /* * This is a 'movie' post * AND a 'single movie template' is not found on * theme or child theme directories, so load it * from our plugin directory. */ return plugin_dir_path( __FILE__ ) . 'single-movie.php'; } return $template; } add_filter( 'single_template', 'load_movie_template' );
Old answer
Added a check for a custom post type specific template in theme folder to @Brainternet answer.
function load_cpt_template($template) { global $post; // Is this a "my-custom-post-type" post? if ($post->post_type == "my-custom-post-type"){ //Your plugin path $plugin_path = plugin_dir_path( __FILE__ ); // The name of custom post type single template $template_name = 'single-my-custom-post-type.php'; // A specific single template for my custom post type exists in theme folder? Or it also doesn't exist in my plugin? if($template === get_stylesheet_directory() . '/' . $template_name || !file_exists($plugin_path . $template_name)) { //Then return "single.php" or "single-my-custom-post-type.php" from theme directory. return $template; } // If not, return my plugin custom post type template. return $plugin_path . $template_name; } //This is not my custom post type, do nothing with $template return $template; } add_filter('single_template', 'load_cpt_template');
Now you can let the plugin users to copy the template from your plugin to their theme to override it.
With this example, templates must be in the root directory of both plugin and theme.
-
Utiliser `Locate_template` au lieu de`get_stylesheet_directory`me semble être l'optionpluspropre (trouvéeici: http://code.tutsplus.com/tutorials/a-guide-to-wordpress-custom-post-types-creation-display-et-méta-boîtes - wp-27645).Using `locate_template` instead of `get_stylesheet_directory` sounds like the cleaner option to me (found here: http://code.tutsplus.com/tutorials/a-guide-to-wordpress-custom-post-types-creation-display-and-meta-boxes--wp-27645).
- 1
- 2016-06-14
- Felix
-
La réponsemise àjourn'apasfonctionné,la réponse acceptée (ou votre ancienne réponse)fonctionne.The updated answer didn't work, the accepted answer (or your old answer) works.
- 1
- 2018-03-29
- Edward
-
Vous avez raison,@Edward,c'était unemise àjour horrible.Je l'aimis àjour ànouveau avec la suggestion de Felix.Cettefois aussi,j'aitesté le code avant de leposter :)You are right, @Edward, that was an horrendous update. I updated it again with Felix suggestion. Also this time I tested the code before posting it :)
- 2
- 2018-04-03
- campsjos
-
- 2016-12-14
Je voudrais souligner que lorsque vous utilisez laméthode defiltragepour cela,ilestextrêmementimportant de donner lapriorité aufiltre comme ceci:
add_filter('single_template', 'my_custom_template', 99);
Si vousne lefaitespas,WPtenteraparfois de revérifier après cefiltre.Jeme suis arraché les cheveux à cause de celapendantenviron 2 heures.
I would like to point out that when you are using the filter method for this, it is extremely important to prioritize the filter like so:
add_filter('single_template', 'my_custom_template', 99);
If you don't do this, sometimes WP will attempt to recheck after this filter. Was pulling my hair out because of this for like 2 hours.
-
- 2019-08-01
Ilexiste unebien meilleurefaçon de lefaire quej'utilisepourmesplugins.
Comme @campsjos mentionnez ici ,au lieu de vérifier l'existence dufichier,vouspouvez cocher
locate_template
qui sera archivé dans lefichier demodèle de remplacement dethème.Ce quiest assez évident.function my_plugin_templates() { if (is_singular('movie')) { if (file_exists($this->template_dir . 'single-movie.php')) { return $this->template_dir . 'single-movie.php'; } } }
Utilisez le crochet defiltre
template_include
pour charger le code ci-dessus.add_filter('template_include' , 'my_plugin_templates');
There is a much better way to do it that I am using for my plugins.
As @campsjos mention here, instead of file existence check, you may check
locate_template
that will check into the theme overrode template file. Which is quite obvious.function my_plugin_templates() { if (is_singular('movie')) { if (file_exists($this->template_dir . 'single-movie.php')) { return $this->template_dir . 'single-movie.php'; } } }
Use
template_include
filter hook to load above code.add_filter('template_include' , 'my_plugin_templates');
-
- 2019-10-19
grâce à cettepage,j'aipu résoudre lamême questionpourmoi.
Pour référence,voici ce quej'ai obtenu:
function pluginName_myposttype_single_template($single_template) { $myposttype_template = PLUGIN_DIR . 'templates/single-myposttype.php'; return get_post_type() === 'myposttype' && file_exists($myposttype_template) ? $myposttype_template : $single_template; } add_filter('single_template', 'pluginName_myposttype_single_template');
le crochet defiltre {$type} _templatene fonctionnaitpaspourmoi
function pluginName_myposttype_single_template($single_template) { $myposttype_template = PLUGIN_DIR . 'templates/single-myposttype.php'; if ( file_exists($myposttype_template) ) { $single_template = $myposttype_template; } return $single_template; } add_filter('single-myposttype_template', 'pluginName_myposttype_single_template');
thanks to this page i was able to solve the same question for me.
For reference, this is what i ended up with:
function pluginName_myposttype_single_template($single_template) { $myposttype_template = PLUGIN_DIR . 'templates/single-myposttype.php'; return get_post_type() === 'myposttype' && file_exists($myposttype_template) ? $myposttype_template : $single_template; } add_filter('single_template', 'pluginName_myposttype_single_template');
the {$type}_template filter hook did not work for me
function pluginName_myposttype_single_template($single_template) { $myposttype_template = PLUGIN_DIR . 'templates/single-myposttype.php'; if ( file_exists($myposttype_template) ) { $single_template = $myposttype_template; } return $single_template; } add_filter('single-myposttype_template', 'pluginName_myposttype_single_template');
-
- 2020-07-10
Cetravailpourmoi,merci de l'essayer,merci
Lesmodèles sont chargés dans lefichier cpt,qui setrouve sur
custom_plugin - >app - >cpt - >cpt_article.php
Lemodèle setrouve
custom_plugin - >app - >modèlesadd_filter( 'single_template', 'load_my_custom_template', 99, 1 ); function load_custom_templates($single_template) { global $post; if ($post->post_type == 'article' ) { $single_template = trailingslashit( plugin_dir_path( __FILE__ ) .'app/templates' ).'single_article.php'; } return $single_template; }
This work for me, kindly try it, Thanks
Templates is loaded into cpt file, which was located at
custom_plugin -> app -> cpt -> cpt_article.php
Template is located
custom_plugin -> app -> templatesadd_filter( 'single_template', 'load_my_custom_template', 99, 1 ); function load_custom_templates($single_template) { global $post; if ($post->post_type == 'article' ) { $single_template = trailingslashit( plugin_dir_path( __FILE__ ) .'app/templates' ).'single_article.php'; } return $single_template; }
-
- 2015-10-19
La réponse ci-dessusestexcellente,mais la vérification de la variable $ singlepermet aumodèle de remplacer unmodèle s'ilestfournipar lethème/thèmeenfant.
/* Filter the single_template with our custom function*/ add_filter('single_template', 'your_cpt_custom_template'); function your_cpt_custom_template( $single ) { global $wp_query, $post; /* Checks for single template by post type */ if ( !$single && $post->post_type == 'cpt' ) { if( file_exists( plugin_dir_path( __FILE__ ) . 'single-cpt.php' ) ) return plugin_dir_path( __FILE__ ) . 'single-cpt.php'; } return $single; }
Above is a great answer, but checking for the $single var allows the template to override a template if one is provided by the theme/child theme.
/* Filter the single_template with our custom function*/ add_filter('single_template', 'your_cpt_custom_template'); function your_cpt_custom_template( $single ) { global $wp_query, $post; /* Checks for single template by post type */ if ( !$single && $post->post_type == 'cpt' ) { if( file_exists( plugin_dir_path( __FILE__ ) . 'single-cpt.php' ) ) return plugin_dir_path( __FILE__ ) . 'single-cpt.php'; } return $single; }
-
Celane vérifiepas si single-cpt.phpestprésent dans unenfant ou lethème.Ilne vérifie que lefichier single.php qui seratoujoursprésent danstous lesthèmes.This does not check if single-cpt.php is present in a child or the theme. It only checks against single.php which will always be present in any themes.
- 1
- 2015-10-28
- newpxsn
-
C'est vrai,quandj'ai écrit ceci,j'utilisais unthème vraimentnu,il doit y avoir unmeilleurmoyen!That's right, when I wrote this I was using a really bare theme, there has to be a better way!
- 0
- 2015-11-20
- DigitalDesignDj
Je voudraisproposermontype demessagepersonnalisé sousforme deplugin,afin que lesgenspuissent l'utiliser sanstoucher leur dossier dethème.Mais lesmodèles detype depublicationpersonnalisés -tels que single-movies.php - résident dans le dossier dethème.Existe-t-il unmoyen de demander à WP de rechercher un single-movies.php dans le dossier duplugin?Accrocher unefonction à la Filer Hierarchy ?Ouget_template_directory ();?