Inclure le fichier PHP dans le contenu en utilisant [shortcode]
-
-
Y a-t-il une raisonparticulièrepour laquelle vous utilisez lamiseen mémoiretampon de sortie?Is there any particular reason that you're using output buffering?
- 0
- 2012-04-20
- Chip Bennett
-
Chip - Aucune raisonpour laquelleil était dans l'extrait quej'aitrouvé,j'ai donc supposé que c'étaitnécessaire.Chip- No reason it was in the snippet I found so I assumed it was required.
- 0
- 2012-04-20
- Eric Downs
-
5 réponses
- votes
-
- 2012-04-20
J'aimodifié du code d'un ancien article deblogpour cefaire,et autorise également les chaînes de requête à êtrejointes aufichier.
Le crédit d'origine va à amberpanther.com ,et il s'avère qu'ils ont créé un plug-in également.
//create the shortcode [include] that accepts a filepath and query string //this function was modified from a post on www.amberpanther.com you can find it at the link below: //http://www.amberpanther.com/knowledge-base/using-the-wordpress-shortcode-api-to-include-an-external-file-in-the-post-content/ //BEGIN amberpanther.com code function include_file($atts) { //if filepath was specified extract( shortcode_atts( array( 'filepath' => 'NULL' ), $atts ) ); //BEGIN modified portion of code to accept query strings //check for query string of variables after file path if(strpos($filepath,"?")) { $query_string_pos = strpos($filepath,"?"); //create global variable for query string so we can access it in our included files if we need it //also parse it out from the clean file name which we will store in a new variable for including global $query_string; $query_string = substr($filepath,$query_string_pos + 1); $clean_file_path = substr($filepath,0,$query_string_pos); //if there isn't a query string } else { $clean_file_path = $filepath; } //END modified portion of code //check if the filepath was specified and if the file exists if ($filepath != 'NULL' && file_exists(get_stylesheet_directory_uri() . "/" . $clean_file_path)){ //turn on output buffering to capture script output ob_start(); //include the specified file include(TEMPLATEPATH.$clean_file_path); //assign the file output to $content variable and clean buffer $content = ob_get_clean(); //return the $content //return is important for the output to appear at the correct position //in the content return $content; } } //register the Shortcode handler add_shortcode('include', 'include_file'); //END amberpanther.com code //shortcode with sample query string: //[include filepath="/get-posts.php?format=grid&taxonomy=testing&term=stuff&posttype=work"]
J'ai configuré lemien pour qu'iltire de l'URI de lafeuille de style (celafonctionnera donc avec lesthèmesenfantset autres),mais vouspouvezfacilement ajuster ce codepour letirer den'importe où (y compris les répertoires deplug-ins),ou le supprimer complètementet simplement utiliser le chemin complet lors de l'inclusion dufichier. Vouspouvezmême ajouter un conditionnel avec un caractère déclencheur au début qui luiindique d'utiliser un chemin spécifiquebasé sur lepremier caractère dunom defichier,comme utiliser un "#"pour le répertoire dumodèle,etc.
Je l'utilisepourextraire unfichier appeléget-posts.php qui setrouve dansmon répertoire demodèleset formate la sortie de divers articlesen fonction d'une série deparamètresfournis dans la chaîne de requête. Celam'évite d'avoirbesoin demodèles spéciaux carje peuxinclure lefichier,luienvoyer unformatet afficher lesmessages avec lebalisage quej'ai spécifié dans lefichierget-posts.php.
Ilpermet également aux clients d'extraire destypes d'articlespersonnalisés dans des articles deblog réels dans desformats spécifiqueset esttrèspratique.
Faites-moi savoir si vous avezbesoin d'éclaircissements sur quoi que ce soit.
I modified some code from an old blog post to do this, and allow for query-strings to be attached to the file as well.
Original credit goes to amberpanther.com, and it turns out they made a plug-in out of this, too.
//create the shortcode [include] that accepts a filepath and query string //this function was modified from a post on www.amberpanther.com you can find it at the link below: //http://www.amberpanther.com/knowledge-base/using-the-wordpress-shortcode-api-to-include-an-external-file-in-the-post-content/ //BEGIN amberpanther.com code function include_file($atts) { //if filepath was specified extract( shortcode_atts( array( 'filepath' => 'NULL' ), $atts ) ); //BEGIN modified portion of code to accept query strings //check for query string of variables after file path if(strpos($filepath,"?")) { $query_string_pos = strpos($filepath,"?"); //create global variable for query string so we can access it in our included files if we need it //also parse it out from the clean file name which we will store in a new variable for including global $query_string; $query_string = substr($filepath,$query_string_pos + 1); $clean_file_path = substr($filepath,0,$query_string_pos); //if there isn't a query string } else { $clean_file_path = $filepath; } //END modified portion of code //check if the filepath was specified and if the file exists if ($filepath != 'NULL' && file_exists(get_stylesheet_directory_uri() . "/" . $clean_file_path)){ //turn on output buffering to capture script output ob_start(); //include the specified file include(TEMPLATEPATH.$clean_file_path); //assign the file output to $content variable and clean buffer $content = ob_get_clean(); //return the $content //return is important for the output to appear at the correct position //in the content return $content; } } //register the Shortcode handler add_shortcode('include', 'include_file'); //END amberpanther.com code //shortcode with sample query string: //[include filepath="/get-posts.php?format=grid&taxonomy=testing&term=stuff&posttype=work"]
I set mine to pull from the stylesheet uri (so it will work with child themes and such), but you could adjust that code easily to pull from anywhere (including plug-in directories), or remove it altogether and just use the full path when including the file. You could even add a conditional with a trigger character at the beginning that tells it to use a specific path based on what the first character of the file name is, like using a "#" for the template directory, etc.
I use it to pull in a file called get-posts.php that lives in my template directory and formats the output of various posts based on a series of parameters provided in the query string. It saves me from needing special templates because I can include the file, send it a format and it will output the posts with the markup I've specified in the get-posts.php file.
It also allows clients to pull custom post types into actual blog-posts in specific formats and is quite handy.
Let me know if you need clarification on anything.
-
Vousne devezpas utiliser `TEMPLATEPATH` ou` STYLESHEETPATH`.Utilisezplutôt `get_template/stylesheet_dir ()` ou l'équivalent `* _url ()`pourpathes/URisYou shouldn't use `TEMPLATEPATH` or `STYLESHEETPATH`. Use `get_template/stylesheet_dir()` instead or the `*_url()` equivalent for pathes/URis
- 3
- 2012-04-21
- kaiser
-
ericissocial Mercibeaucoup!Je vaistoutbrancheret essayer,je vous dirai comment ça sepasse.ericissocial Thanks so much! I'm going to plug it all in and give it a try, I'll let you know how it goes.
- 0
- 2012-04-21
- Eric Downs
-
Pas deproblème,vous devriez suivre la recommandation de kaiseret utiliser lafonctionnalité GET_template au lieu du TEMPLATEPATH quej'avais dans le code.Kaiser,mercipour lamiseen garde,je modifierai le code dansma réponse lorsqueje ne le vispas surmontéléphone.No problem, you should follow kaiser's recommendation and use the GET_template functionality instead of the TEMPLATEPATH that I had in the code, as well. Kaiser, thanks for the heads up, I'll edit the code in my answer when I'm not viewing this on my phone.
- 0
- 2012-04-21
- Eric Allen
-
J'aimis àjour le TEMPLATEPATHpourget_stylesheet_directory_uri ()I updated the TEMPLATEPATH to get_stylesheet_directory_uri()
- 0
- 2012-04-22
- Eric Allen
-
- 2016-01-20
Voici une autrefaçon de lefaire,en utilisant
get_template_part
de wordpressfunction include_file($atts) { $a = shortcode_atts( array( 'slug' => 'NULL', ), $atts ); if($slug != 'NULL'){ ob_start(); get_template_part($a['slug']); return ob_get_clean(); } } add_shortcode('include', 'include_file');
exemples:
[include slug="form"]
[include slug="sub-folder/filename_without_extension"]
Here's another way to do it, utilizing
get_template_part
of wordpressfunction include_file($atts) { $a = shortcode_atts( array( 'slug' => 'NULL', ), $atts ); if($slug != 'NULL'){ ob_start(); get_template_part($a['slug']); return ob_get_clean(); } } add_shortcode('include', 'include_file');
examples:
[include slug="form"]
[include slug="sub-folder/filename_without_extension"]
-
N'utilisezjamais `extract ()`,c'est unetrèsmauvaisefonction à utiliser.Il a ététotalement supprimé dunoyau de Wordpress.Never ever use `extract()`, it is a really bad function to use. It was totally removed from Wordpress core.
- 1
- 2016-01-21
- Pieter Goosen
-
- 2019-05-29
Il y a uneerreur dans la solutionfourniepar @adedoy,car $ slugn'estjamais défini.Cela afonctionnépourmoi:
function include_file($atts) { $atts = shortcode_atts( array( 'path' => 'NULL', ), $atts, 'include' ); ob_start(); get_template_part($atts['path']); return ob_get_clean(); } add_shortcode('include', 'include_file');
Utilisation: [includepath="path/from/root"]
There is an error in the solution provided by @adedoy, since $slug is never defined. This worked for me:
function include_file($atts) { $atts = shortcode_atts( array( 'path' => 'NULL', ), $atts, 'include' ); ob_start(); get_template_part($atts['path']); return ob_get_clean(); } add_shortcode('include', 'include_file');
Usage: [include path="path/from/root"]
-
- 2014-11-07
J'aitrouvé que le code d'inclusion écrit à l'originepar lesgens d'AmberPantherne fonctionnaitpastrèsbien pourmoi,alorsj'aitrouvé un autreplugin wordpress quifait àpeuprès lamême chose. Il s'appelle Include Me,de Stefano Lissa. L'utilisationest àpeuprès que vous écrivez votre chemin vers lefichier,en commençantpar le répertoire racine de votre site.
Ainsi,parexemple,dans votrepage WordPress,vous écrirez:
[includeme file="wp-content/themes/your-theme/code/example-code.php"]
et dans votrefichierfunctions.php,vousincluez:
<?php if (is_admin()) { include dirname(__FILE__) . '/admin.php'; } else { function includeme_call($attrs, $content = null) { if (isset($attrs['file'])) { $file = strip_tags($attrs['file']); if ($file[0] != '/') $file = ABSPATH . $file; ob_start(); include($file); $buffer = ob_get_clean(); $options = get_option('includeme', array()); if (isset($options['shortcode'])) { $buffer = do_shortcode($buffer); } } else { $tmp = ''; foreach ($attrs as $key => $value) { if ($key == 'src') { $value = strip_tags($value); } $value = str_replace('&', '&', $value); if ($key == 'src') { $value = strip_tags($value); } $tmp .= ' ' . $key . '="' . $value . '"'; } $buffer = '<iframe' . $tmp . '></iframe>'; } return $buffer; } // Here because the funciton MUST be define before the "add_shortcode" since // "add_shortcode" check the function name with "is_callable". add_shortcode('includeme', 'includeme_call'); }
Bien sûr,je vous recommande également d'installer simplement leplugin afin que vouspuissiezprofiter desmises àjour. https://wordpress.org/plugins/include-me/
I found that the include code originally written by the AmberPanther folks didn't work so well for me, so I found another wordpress plugin that does pretty much the same thing. It's called Include Me, by Stefano Lissa. The usage is pretty much that you write your path to the file, starting from the root directory of your site.
So for example, within your WordPress page you'd write:
[includeme file="wp-content/themes/your-theme/code/example-code.php"]
and within your functions.php file you'd include:
<?php if (is_admin()) { include dirname(__FILE__) . '/admin.php'; } else { function includeme_call($attrs, $content = null) { if (isset($attrs['file'])) { $file = strip_tags($attrs['file']); if ($file[0] != '/') $file = ABSPATH . $file; ob_start(); include($file); $buffer = ob_get_clean(); $options = get_option('includeme', array()); if (isset($options['shortcode'])) { $buffer = do_shortcode($buffer); } } else { $tmp = ''; foreach ($attrs as $key => $value) { if ($key == 'src') { $value = strip_tags($value); } $value = str_replace('&', '&', $value); if ($key == 'src') { $value = strip_tags($value); } $tmp .= ' ' . $key . '="' . $value . '"'; } $buffer = '<iframe' . $tmp . '></iframe>'; } return $buffer; } // Here because the funciton MUST be define before the "add_shortcode" since // "add_shortcode" check the function name with "is_callable". add_shortcode('includeme', 'includeme_call'); }
of course, I'd also recommend just installing the plugin so you can take advantage of updates. https://wordpress.org/plugins/include-me/
-
- 2016-01-20
D'accord,j'abandonnerais d'abord lamiseen mémoiretampon de sortie.
Deuxième changement:
include(TEMPLATEPATH.'/wp-content/themes/grainandmortar/inc_static/test.php');
À
include( get_stylesheet_directory() . '/inc_static/test.php');
Enfin,
Lire la documentationici: https://codex.wordpress.org/Shortcode_API
Vous devez retourner quelque chose,si votretest.phpne produitpas quelque chose demanière retournable,vous allezpasser unmauvaismoment.
Assurez-vous donc que test.php fait quelque chose dugenre:
$output = "STUFF"; // a variable you could return after include. // or function test() { // do stuff return $stuff; // a function that returns a value that you can call after include. }
Ensuite,après avoirinclus votrefichier test.php -il vous suffit de renvoyer
$output
ou defaire quelque chose commereturn test();
.Ok, first I'd ditch the output buffering.
Second change:
include(TEMPLATEPATH.'/wp-content/themes/grainandmortar/inc_static/test.php');
To
include( get_stylesheet_directory() . '/inc_static/test.php');
Finally,
Reading the documentation here: https://codex.wordpress.org/Shortcode_API
You need to return something, if your test.php doesn't output something in a returnable fashion, you're going to have a bad time.
So make sure that test.php does something along the lines of:
$output = "STUFF"; // a variable you could return after include. // or function test() { // do stuff return $stuff; // a function that returns a value that you can call after include. }
Then after you include your test.php file -- you just return
$output
or do something likereturn test();
.-
Curieux de connaître votre raisonnement -pourquoine pas utiliser lamiseen mémoiretampon de sortiepour les codes courts?Just curious about your reasoning - why not use output buffering for shortcodes?
- 0
- 2019-01-08
- mattLummus
-
Hé @mattLummus - c'est une question deperspective à lafin de lajournée.Jepense que vousn'en avezpas BESOINpour atteindre l'objectifet que vousne gagnezpasgrand-chose à lefaire - deplus,je vaisfaire écho à ce qui a été ditici: https://stackoverflow.com/questions/5454345/output-buffer-vulnéraabilities-php - "Lamiseen mémoiretampon de sortieest considérée commemoche sielleest utiliséepour contourner votre ancienne peutpasenvoyer lesen-têtes,la sortie a déjà commencé à ... avertissement. Lamiseen mémoiretampon de sortieest alors utiliséepour compenser unemauvaise conception ..."Hey @mattLummus -- it's a perspective thing at the end of the day. I think that you don't NEED it to accomplish the goal and you don't gain much by doing it -- additionally, I'll echo what was said here: https://stackoverflow.com/questions/5454345/output-buffer-vulnerabilities-php -- "Output buffering is considered ugly if it is used to circumvent ye' olde Cannot send headers, output already started at... warning. Output buffering is then used to make up for poor design..."
- 1
- 2019-01-21
- Sterling Hamilton
-
Ouais,cela semble être une solution hacky dans ce casparticulier.Généralement,lorsquenous utilisons destampons de sortie,cen'estpaspour contourner un autreproblème,mais simplementparce quenous sommes dans un cas oùnous écrivonsplus debalisage que PHPet préférons la syntaxe OB (être capable d'échapper à PHPet d'écrire du HTML simplepar rapport à untas d'instructions d'échoet HTML écriten chaînes). Mercipour la réponseen tout cas!Yeah that does seem like a hacky solution in that particular case. Generally when we use Output Buffers its not for working around another issue but simply because we are in a case where we are writing more markup than PHP and prefer the OB syntax (being able to escape PHP and write plain HTML vs a bunch of echo statements and HTML written in strings). Thanks for the response in any case!
- 0
- 2019-01-23
- mattLummus
Voici ce quej'ai
Jen'ai aucune chance detrouver comment simplementinclure unfichier dans l'éditeur de contenuen utilisant un shortcode.
Parexemple,sije voulaisinclureform.php dansmapage de contact,comment y arriverais-jeen utilisant un shortcode?
Ci-dessous,j'aiessayé detravailler avecen vain.
Toute aide serait appréciée!