Ottieni il nome del file modello corrente
-
-
@chodorowicz - Anche semi fermerò unpassoprima di chiamare la selezione di `functions.php` come unbug,sono completamente d'accordo con latuapremessa.Apeggiorare le cose ho scansionatoil codice dibase di WordPresse hotrovato circa 5puntiin cui avrebbepotutoesserci ungancioper consentirti digestire questoproblema,manonne hotrovatonessuno.Suggerirei dipubblicare unticket su http://core.trac.wordpress.org.@chodorowicz - While I will stop one step short of calling the selection of `functions.php` as a bug, I will agree completely with your premise. To make matters worse I scanned the WordPress core code and found about 5 places where there could have been a hook to allow you to handle this issue yet I found none. I'd suggest posting a ticket on http://core.trac.wordpress.org.
- 2
- 2011-02-26
- MikeSchinkel
-
@MikeSchinkel -grazieperil commento,ma l'hook `template_include`,suggerito dat31os,non risolveilproblema?Oforseti hofrainteso.@MikeSchinkel - thanks for comment, but doesn't `template_include` hook, which t31os suggested, solve the issue? Or maybe I've misunderstood you.
- 0
- 2011-02-27
- chodorowicz
-
@chodorowicz - Orami haimolto confuso.La rispostafornita da @t31os risolve unproblemamolto diverso da quello che ho capito stavi chiedendoin base allatua domandae aituoi commenti difollow-up alle risposte degli altri.Ma se la risposta di @t31os ha risolto latuaeffettivanecessità,lamia confusione quinon èimportantepoiché latua domanda ha ricevuto risposta.@chodorowicz - You now have me very confused. The answer @t31os gave solves a problem that is very different from the one that I understood you were asking based on your question and your follow up comments to other's answers. But if @t31os' answer solved your actual need, then my confusion here is unimportant as your question has been answered.
- 0
- 2011-02-27
- MikeSchinkel
-
Sì,l'effettivanecessitàera di visualizzareilnome delfile deltema attualmente utilizzato,il codice che hopubblicato aveva un difetto (chepuòessere risolto spostando lafunzionefuori dalla cartella deltemaprincipale),ma la soluzione di @t31os èmoltopiùpulitaesoddisfa lanecessità,ma,se ho capitobene,il veroproblema (WPnon dovrebbeprovare a leggere `functions.php` comefilemodello dipagina)persiste ancora.Proverò apostarlo sutrac,non l'ho ancorafatto.Saluti!Yes, the actual need was to display the name of the currently used theme file, the code I posted had a flaw (which can be solved by moving the function out of the main theme folder), but @t31os' solution is much cleaner and fulfills the need, but, if I understand you correctly, the real problem (WP shouldn't try to read `functions.php` as page template file) still persists. I'll try to post it on trac, haven't done it yet. Greetings!
- 0
- 2011-02-27
- chodorowicz
-
@MikeSchinkel - hagià unapatch :) http://core.trac.wordpress.org/ticket/16689@MikeSchinkel - it already has a patch :) http://core.trac.wordpress.org/ticket/16689
- 1
- 2011-02-28
- chodorowicz
-
@chodorowicz - Sì,ilmio commento stava affrontandoil veroproblema,impedendo a WP diprovare a leggere `functions.php`e/opermettendoti di scrivere un hookper cambiare è stato restituito.Sono contento di vedere che haitrovato unapatchpiuttosto che duplicarla;è così difficiletrovare queibigliettiesistenti.@chodorowicz - Yes, my comment was addressing the real problem, keeping WP from trying to read `functions.php` and/or allowing you to write a hook to change was is returned. Glad to see you found a patch rather than duplicate it; it's so hard to find those existing tickets.
- 0
- 2011-02-28
- MikeSchinkel
-
^ie.haipresoil codice dallamia rispostae lo haiinseritoin unplugin.E haifattotutto questo senza dare alcun credito all'origine,néioné lo stackexchange WP ...bello ...:/^ ie. you took the code from my answer and wrapped it into a plugin. And you did all that without providing any credit to the origin, neither myself or the WP stackexchange... nice... :/
- 4
- 2014-03-30
- t31os
-
9 risposta
- voti
-
- 2011-04-09
a quantopare questo è sufficiente:
add_action('wp_head', 'show_template'); function show_template() { global $template; echo basename($template); }
o semplicemente usalo direttamenteneltemplate (tendo afareecoin footer.phpnel commento HTML)
<?php global $template; echo basename($template); ?>
apparently this is enough:
add_action('wp_head', 'show_template'); function show_template() { global $template; echo basename($template); }
or just use it directly in template (I tend to echo in footer.php in HTML comment)
<?php global $template; echo basename($template); ?>
-
Questononfunzionerà conget-template-part solo così sai,mostra solo single.php (adesempio)e nonilfilein cui sitrova.That won't work with get-template-part just so you know, it only shows single.php (for example) and not the file it is in.
- 1
- 2012-09-25
- m-torin
-
Si è vero.Per ottenereilnome delfileincluso dovrestiprobabilmente usare qualcosa di simile a `echo __FILE __;`Yes, it's true. To get the name of included file you'd probably need to use something like this `echo __FILE__;`
- 0
- 2012-10-05
- chodorowicz
-
questo vabene,adesempionei casiin cuimodifichiilmodellopredefinito senza assegnarlo a unpostnelbackoffice.Adesempio utilizzandopercorsipersonalizzatie ilfiltrotemplate_include.Grazie.this is fine, for example in cases when you modify the default template without assigning it to a post in backoffice. For example using custom routes and the template_include filter. Thank you.
- 0
- 2016-09-15
- Luca Reghellin
-
Comepotreifarlo all'interno di un ciclo?Sto cercando diinviare l'URL a unapagina di ognifilemodello.How could I do this within a loop? I'm trying to output the URL to one page of each template file.
- 0
- 2017-02-28
- JacobTheDev
-
@JacobTheDevpotrebbe usare `echo __FILE__` -poichénonfunzionerà,mostra soloilmodelloinizialeprincipale@JacobTheDev maybe using `echo __FILE__` - because this won't work, it displays only main, initial template
- 0
- 2017-03-07
- chodorowicz
-
- 2011-02-27
Èpossibileimpostare una variabileglobale duranteilfiltro
template_include
e quindi controllare successivamente quella variabileglobaleper vedere qualemodello è statoincluso.Naturalmentenon vorrestiil percorso completoinsieme alfile,quinditi consiglio ditroncareilnome delfile utilizzando lafunzione
basename
di PHP.Codice diesempio:
Duefunzioni,unaperimpostareilglobale,unaper richiamarlo.add_filter( 'template_include', 'var_template_include', 1000 ); function var_template_include( $t ){ $GLOBALS['current_theme_template'] = basename($t); return $t; } function get_current_template( $echo = false ) { if( !isset( $GLOBALS['current_theme_template'] ) ) return false; if( $echo ) echo $GLOBALS['current_theme_template']; else return $GLOBALS['current_theme_template']; }
Puoi quindiinvocare
get_current_template
ovunqueti servanei file deltema,notando che ciò deve avvenirenaturalmente dopo che l'azionetemplate_include
è stata attivata (non avraibisognopreoccuparsi di questo se la chiamata vieneeffettuata all'interno di unfilemodello).Peri modelli dipagina c'è
is_page_template()
,tenendopresente che aiuterà solonel caso deimodelli dipagina (unafunzione catturatutto moltomeno).Informazioni sullefunzioni utilizzate o citate sopra:
You could set a global variable during the
template_include
filter and then later check that global vairable to see which template has been included.You naturally wouldn't want the complete path along with the file, so i'd recommend truncating down to the filename using PHP's
basename
function.Example code:
Two functions, one to set the global, one to call upon it.add_filter( 'template_include', 'var_template_include', 1000 ); function var_template_include( $t ){ $GLOBALS['current_theme_template'] = basename($t); return $t; } function get_current_template( $echo = false ) { if( !isset( $GLOBALS['current_theme_template'] ) ) return false; if( $echo ) echo $GLOBALS['current_theme_template']; else return $GLOBALS['current_theme_template']; }
You can then call upon
get_current_template
wherever you need it in the theme files, noting this naturally needs to occur after thetemplate_include
action has fired(you won't need to worry about this if the call is made inside a template file).For page templates there is
is_page_template()
, bearing in mind that will only help in the case of page templates(a far less catch all function).Information on functions used or referenced above:
-
- 2013-03-01
Tra lefunzioninative di WP come get_template_part () e quellenative di PHP,ilmodopiù affidabileper vederei file deltema utilizzati èil recuperoelenco dituttii fileinclusie filtratutto ciò chenon appartiene altema (otemi quando viene utilizzata la combinazionegenitoree figlio):
$included_files = get_included_files(); $stylesheet_dir = str_replace( '\\', '/', get_stylesheet_directory() ); $template_dir = str_replace( '\\', '/', get_template_directory() ); foreach ( $included_files as $key => $path ) { $path = str_replace( '\\', '/', $path ); if ( false === strpos( $path, $stylesheet_dir ) && false === strpos( $path, $template_dir ) ) unset( $included_files[$key] ); } var_dump( $included_files );
Between native WP functions like get_template_part() and PHP's native includes the most reliable way to see theme's files used is to fetch list of all included files and filter out whatever doesn't belong to theme (or themes when parent and child combination is used):
$included_files = get_included_files(); $stylesheet_dir = str_replace( '\\', '/', get_stylesheet_directory() ); $template_dir = str_replace( '\\', '/', get_template_directory() ); foreach ( $included_files as $key => $path ) { $path = str_replace( '\\', '/', $path ); if ( false === strpos( $path, $stylesheet_dir ) && false === strpos( $path, $template_dir ) ) unset( $included_files[$key] ); } var_dump( $included_files );
-
- 2012-09-08
Un'aggiunta (codicepiù dolce) ad altre risposte qui.
Nomemodello
Per ottenere soloilnome del modello dipagina corrente,utilizzare la riga seguente.
is_page() AND print get_page_template_slug( get_queried_object_id() );
Nomefile
Quando vuoi solo ripetereil nome delfile delmodello corrente ,seguiil seguente
Modifica: ecco lanuova versione delplugin racchiusain una classe. Mostra siailnome delfile delmodello corrente,siailnome delfile dellagerarchia delmodellonell'hook di chiusuranellaparteinferiore dellapagina.
Cosati diceilplugin:
- Ilmodelloproviene dalpadre deltema secondario/attuale?
- Ilmodello vienepubblicato da una sottocartella? Se sì:ti diceilnome
- Ilnome delfile delmodello.
Copiail codice seguentein unfilee chiamalo
wpse10537_template_info.php
,caricalonella directory deiplugine attivalo.<?php /** Plugin Name: (#10537) »kaiser« Get Template file name */ if ( ! class_exists( 'wpse10537_template_name' ) ) { add_action( 'plugins_loaded', array( 'wpse10537_template_name', 'init' ) ); class wpse10537_template_name { protected static $instance; public $stack; public static function init() { is_null( self :: $instance ) AND self :: $instance = new self; return self :: $instance; } public function __construct() { if ( is_admin() ) return; add_action( 'wp', array( $this, 'is_parent_template' ), 0 ); add_action( 'wp', array( $this, 'get_template_file' ) ); add_action( 'template_include', array( $this, 'get_template_name' ) ); add_action( 'shutdown', array( $this, 'get_template_name' ) ); } public function get_template_name( $file ) { if ( 'template_include' === current_filter() ) { $this->to_stack( "Template file" ,basename( $file ) ); return $file; } // Return static var on echo call outside of filter if ( current_user_can( 'manage_options' ) AND defined( 'WP_DEBUG' ) AND WP_DEBUG ) return print implode( " – ", $this->stack ); } public function get_template_file() { if ( ! is_post_type_hierarchical( get_post_type() ) ) return; $slug = get_page_template_slug( get_queried_object_id() ); if ( ! strstr( $slug, "/" ) ) return $this->to_stack( "Template", $slug ); $this->to_stack( "Subdirectory" ,strstr( $slug, "/", true ) ); $this->to_stack( "Template (in subdirectory)" ,str_replace( "/", "", strstr( $slug, "/" ) ) ); } public function is_parent_template() { if ( ! is_null( wp_get_theme()->parent ) ) return $this->to_stack( 'from parent theme' ); $this->to_stack( 'from current/child theme' ); } public function to_stack( $part, $item = '' ) { $this->stack[] = "{$part}: {$item}"; } } // END Class wpse10537_template_name } // endif;
Questopluginpuòessereeseguito anche come MU-Plugin.
Puoi quindi chiamare semplicemente
wpse10537_get_template_name()
in qualsiasimomento (adesempioin unmodello ditema). Ciòevita diingombrare lo spazio deinomiglobale.An addition (more sweet code) to other answers here.
Template Name
To just get the current page template name, use the following line.
is_page() AND print get_page_template_slug( get_queried_object_id() );
File Name
When you just want to echo the current template file name, go with the following
Edit: Here's the new version of the plugin wrapped up in a class. It shows both the current template file name, as well as the template hierarchy file name in the shutdown hook at the most bottom of the page.
What the plugin tells you:
- Is the template from the parent of child/current theme?
- Is the template served from a subfolder? If yes: Tells you the name
- The template file name.
Just copy the following code into a file and name it
wpse10537_template_info.php
, upload it to your plugins directory and activate it.<?php /** Plugin Name: (#10537) »kaiser« Get Template file name */ if ( ! class_exists( 'wpse10537_template_name' ) ) { add_action( 'plugins_loaded', array( 'wpse10537_template_name', 'init' ) ); class wpse10537_template_name { protected static $instance; public $stack; public static function init() { is_null( self :: $instance ) AND self :: $instance = new self; return self :: $instance; } public function __construct() { if ( is_admin() ) return; add_action( 'wp', array( $this, 'is_parent_template' ), 0 ); add_action( 'wp', array( $this, 'get_template_file' ) ); add_action( 'template_include', array( $this, 'get_template_name' ) ); add_action( 'shutdown', array( $this, 'get_template_name' ) ); } public function get_template_name( $file ) { if ( 'template_include' === current_filter() ) { $this->to_stack( "Template file" ,basename( $file ) ); return $file; } // Return static var on echo call outside of filter if ( current_user_can( 'manage_options' ) AND defined( 'WP_DEBUG' ) AND WP_DEBUG ) return print implode( " – ", $this->stack ); } public function get_template_file() { if ( ! is_post_type_hierarchical( get_post_type() ) ) return; $slug = get_page_template_slug( get_queried_object_id() ); if ( ! strstr( $slug, "/" ) ) return $this->to_stack( "Template", $slug ); $this->to_stack( "Subdirectory" ,strstr( $slug, "/", true ) ); $this->to_stack( "Template (in subdirectory)" ,str_replace( "/", "", strstr( $slug, "/" ) ) ); } public function is_parent_template() { if ( ! is_null( wp_get_theme()->parent ) ) return $this->to_stack( 'from parent theme' ); $this->to_stack( 'from current/child theme' ); } public function to_stack( $part, $item = '' ) { $this->stack[] = "{$part}: {$item}"; } } // END Class wpse10537_template_name } // endif;
This plugin can run as MU-Plugin too.
You can then simply call
wpse10537_get_template_name()
at any point (in for example a theme template). This avoids cluttering the global namespace.-
"template_redirect"non stapassandonulla,penso chetu stia confondendo con "template_include".Inoltre controllerei se all'interno delfiltroinvece che se la variabile staticafosse riempita.Se un codice decide dieseguire l'hookpiùtempo,può rovinare le cose.`template_redirect` is not passing anything, I think you are confusing with `template_include`. Also I'd check if inside the filter instead of if static var filled. If some code decides to run hook additional time it can wreck things.
- 1
- 2012-09-15
- Rarst
-
@Rarst Done/Fixed.Grazieperil suggerimentoe indicandoilnome delfiltro.@Rarst Done/Fixed. Thanks for the hint and pointing out the filter name.
- 0
- 2012-09-15
- kaiser
-
- 2011-02-26
Ilnome delmodello èmemorizzatonellatabellapostmeta,quinditutto ciò che devifare èinserirlo da qualcheparteneltuo ciclo:
$template = get_post_meta( $post->ID, '_wp_page_template', true ); echo "Template: " . $template;
The template name is stored in the postmeta table, so all you need to do is put this somewhere in your loop:
$template = get_post_meta( $post->ID, '_wp_page_template', true ); echo "Template: " . $template;
-
Sì,lo so,mailproblema è chefunziona solo quando unapagina ha unmodelloimpostato.La cosainteressante del codice che hopostato è cheti dirà se lapagina corrente sta usando `front-page.php`,`index.php`,`single.php`,`page.php` o qualsiasi altrofile.Il codicemostrailnome delmodello soloper lepagine con unmodello dipaginapersonalizzato.Yes, I know about this, but the problem is that it works only when a page has a set template. The cool thing about the code I posted is that it will tell you if current page is using `front-page.php`, `index.php`, `single.php`, `page.php` or any other file. Your code displays template name only for pages with custom page template.
- 2
- 2011-02-26
- chodorowicz
-
ah,scusa -ilmiomalinteso sullatua domanda.ah, sorry - my misunderstanding of your question.
- 0
- 2011-02-26
- Simon Blackbourn
-
@SimonBlackbourn È di aiutoper lemie esigenze.Grazie.@SimonBlackbourn It's help for my requirement. Thanks.
- 0
- 2013-10-08
- KarSho
-
- 2013-05-01
Questonon risolvetutte le domande dell'OP,mail codice seguente è certamentepiùelegante delleespressioni regolarie dell'analisi delfilemodello stesso.
Seti trovi su unapagina che utilizza unmodello dipaginae desideri ottenereilnome delmodello dipagina (adesempio:ilnome leggibile dall'uomo che hai definitonei commentinellaparte superiore delfile PHP delmodello),puoi usare questapiccolapepita:
if ( is_page() && $current_template = get_page_template_slug( get_queried_object_id() ) ){ $templates = wp_get_theme()->get_page_templates(); $template_name = $templates[$current_template]; }
Volevo ottenereilnome delmodelloperchéero davvero stufo deinomi di classe stupidie lunghi che lafunzione
body_class
incorporata di WordPress crea quando stai usando unmodello. Fortunatamente c'è unfiltro hook allafine di quellafunzione cheti consente di aggiungere anchei nomi delletue classi. Eccoilmiofiltro. Spero che qualcuno lotrovi utile:add_filter( 'body_class', 'gs_body_classes', 10, 2 ); function gs_body_classes( $classes, $class ){ if ( is_page() && $current_template = get_page_template_slug( get_queried_object_id() ) ){ $templates = wp_get_theme()->get_page_templates(); $template_name = str_replace( " ", "-", strtolower( $templates[$current_template] ) ); $classes[] = $template_name; } return $classes; }
Questofiltroprenderà qualsiasi cosatu abbia chiamatoiltuomodello dipagina,sostituiràgli spazi contrattinie renderàtuttominuscoloin modo che assomigli atutte le altre classi di WordPress.
This doesn't address all of the OP's question, but the code below is certainly more elegant than regular expressions and parsing the template file itself.
If you're on a Page that is using a Page Template, and you want to get the page template's Name (ie: the human-readable name that you defined in the comments at the top of your template PHP file), you can use this little nugget:
if ( is_page() && $current_template = get_page_template_slug( get_queried_object_id() ) ){ $templates = wp_get_theme()->get_page_templates(); $template_name = $templates[$current_template]; }
I wanted to get the template name because I was really sick of the silly-long-ass class names that the built-in WordPress
body_class
function creates when you're using a template. Luckily there's a filter hook at the very end of that function to let you append your own class names as well. Here's my filter. Hope someone finds it useful:add_filter( 'body_class', 'gs_body_classes', 10, 2 ); function gs_body_classes( $classes, $class ){ if ( is_page() && $current_template = get_page_template_slug( get_queried_object_id() ) ){ $templates = wp_get_theme()->get_page_templates(); $template_name = str_replace( " ", "-", strtolower( $templates[$current_template] ) ); $classes[] = $template_name; } return $classes; }
This filter will take whatever you named your page template, replace spaces with dashes and make everything lower case so it looks like all the other WordPress classes.
-
- 2011-02-26
Si è verificato unproblema con la riga
preg_match_all
.Prova questoinvece:preg_match_all("/Template Name:(.*)\n/siU",$template_contents,$template_name);
Inoltre,puoi usare
if (!is_admin()) { .... }
pereseguire le cose solo sulfrontend.There's an issue with the
preg_match_all
line. Try this instead:preg_match_all("/Template Name:(.*)\n/siU",$template_contents,$template_name);
Also, you can use
if (!is_admin()) { .... }
to run things on the frontend only.-
Grazieperil suggerimento,non risolvonoilproblema,mami hannoindirizzato verso soluzioni.Si scopre che WP,mentregenera l'elenco deimodelli,sta cercando anchein `functions.php`,trova" "/Nomemodello: (. *) \ N/siU" "e quinditratta`functions.php` comefilemodello.Penso che questo sia unbug di WP,non dovrebbenemmenoguardare questofile.La soluzione: spostailfilenella sottodirectory.Thanks for suggestion, they don't solve the problem, but they kinda directed me into solutions. It turns out that WP, while generating templates list, is looking even into `functions.php` finds the `"/Template Name:(.*)\n/siU"` and thus treats the `functions.php` as template file. I think this is WP bug, it shouldn't even look at this file. The solution: move the file into subdirectory.
- 0
- 2011-02-26
- chodorowicz
-
@chodorowicz: Non è unbugin WP,è unbugnellatuafunzione.@chodorowicz: That's not a bug in WP, it's a bug in your function.
- 0
- 2011-02-26
- wyrfel
-
Quindifondamentalmente WP vieta dimettere la stringa "Template Name:" (anchenei commenti)nelfile `functions.php`.Perme,personalmente,questo è unbug (piccolo,ma comunque)ma questo èilpunto di discussione,suppongo.Penso chenon sipossa dire che lafunzione stessa sia difettosa.So basically WP forbids you to put string "Template Name:" (even in comment) in `functions.php` file. For me, personally, that's a bug, (small, but anyway) but that's the up to discussion, I suppose. I think you cannot say that the function itself is buggy.
- 0
- 2011-02-26
- chodorowicz
-
WPnonti proibisce difarenulla.Ma WPnonti promettenemmeno chepuoieseguireil loop su debug_backtrace ()per scoprire qualefilemodello stai usando.Soloperché l'haitrovato su unforum di supporto WPnon significa che sia un codice ufficialmente supportato.Comepuoi vedere,latuafunzioneesploraesplicitamentefooter.php.Puoi anche aggiungere un'altra condizione cheescludefunctions.php.BTW: latuafunzionenon cerca `Template Name` all'interno di ciascuno deifile,iltuo ciclo èterminatomoltoprima.WP doesn't forbid you to do anything. But WP also doesn't promise you that you can loop over a debug_backtrace() to find out what template file you're using. Just because you found it on a WP support forum doesn't mean it's officially supported code. As you may see, your function explicitly expludes footer.php. You may as well add another condition that excludes functions.php. BTW: your function doesn't look for `Template Name` within each of the files, your loop has ended long before that.
- 0
- 2011-02-27
- wyrfel
-
Ilproblemanonera con `debug_backtrace ()` - Posso rimuoveretuttoil codicee lasciare semplicemente `preg_match_all ("/Template Name ... `,o anche solo`//Template Name: `e WPtratta quindi`functions.php` comefilemodello,magrazieperi commenti - questo è unproblema così unico che,come dicitu,non ègiusto dire che sitratta di unbug. La soluzione dit31os èpulitae risolve l'interoproblema.The problem wasn't with `debug_backtrace()` - I can remove all the code and just leave `preg_match_all("/Template Name...`, or even just `// Template Name:` and WP treats then `functions.php` as template file, but thanks for comments - this is such a unique problem that, as you say, it's not fair to say it's a bug. t31os solution is clean and solves the whole issue. Greets.
- 0
- 2011-02-27
- chodorowicz
-
- 2017-09-15
Giocainsieme a:
echo '<ul><li>'.implode('</li><li>', str_replace(str_replace('\\', '/', ABSPATH).'wp-content/', '', array_slice(str_replace('\\', '/', get_included_files()), (array_search(str_replace('\\', '/', ABSPATH).'wp-includes/template-loader.php', str_replace('\\', '/', get_included_files())) + 1)))).'</li></ul>';
Scritto a:
Comefai a scoprire qualepagina delmodello serve lapagina corrente?
seilpercorso
admin-bar stuff
viene visualizzatoin alto o qualsiasi altrofile,cambiailnome delfiletemplate-loader.php
in questa riga di codicein: qualunquenome delfile da cui deviinterrompere.sene haibisognonellabarra di amministrazione, usa lapriorità corretta (laprima) per assicurarti chenessunfile siainserito allafine di questoelenco. Adesempio:
add_action('admin_bar_menu', 'my_adminbar_template_monitor', -5);
priorità
-5
fain modo che venga caricatoperprimo. La chiave è rendere questa riga almomentogiusto.Non restituisceilfilemodello "corrente",matuttoilfile correntein usoperil caricamento dellapagina corrente. Forse "tagliato" con una logica da quell'idea .
La chiave
get_included_files()
"last" è l'ultimofileincluso registrato,probabilmente l'ultimofile-modello/parte utilizzatonelpiè dipagina dal widget dellabarra laterale o qualcosa delgenere. Probabilmente,cosìtantifileinclusinon si registrano dinuovo/popolano dinuovoin get_included_files ().Altrimenti, l'intenzione deveessere chiaraper hackerare questoproblema . Non èpossibile che unfileincluso si riporti comeinclusofinchénon è statoincluso . Quindi èprobabile che siatroppotardiper utilizzare lo scenario.
Lamaggiorparte delle volte ti piacerebbe :
$template = get_current_loaded_template(); if($template == 'single-product.php') add_filter('the_title' .... if($template == 'format-gallery.php') add_action('post_thumbnail' ....
Ma questonon èpossibile seilmodello viene caricato al difuori delmetodoprincipale di Wordpress di
get_template_part
. Riprogettainvece letueesigenze! Forseloop_start()
,in_the_loop()
eadd_action('the_post')
ha la soluzione che desideri,permodificarei dati a seconda delmodello che andrà caricareper ogni voce all'interno di un ciclo.Play along with:
echo '<ul><li>'.implode('</li><li>', str_replace(str_replace('\\', '/', ABSPATH).'wp-content/', '', array_slice(str_replace('\\', '/', get_included_files()), (array_search(str_replace('\\', '/', ABSPATH).'wp-includes/template-loader.php', str_replace('\\', '/', get_included_files())) + 1)))).'</li></ul>';
Written at:
How do you find out which template page is serving the current page?
if
admin-bar stuff
path is showing at the top, or any other file, change the filenametemplate-loader.php
in this line of code to: whatever filname you need to break from.if you need this in the admin bar, use the right priotity (earliest) to make shure no files are entered at the end of this list. For example:
add_action('admin_bar_menu', 'my_adminbar_template_monitor', -5);
priority
-5
make shure it loads first. The key is to render this line at the right moment.It does not returning the "current" template-file, but all the current in use for the current page-load. Maybe "cut out" with some logic from that idea.
The
get_included_files()
"last" key is the last registered included file, propably the last template-file/ -part used in the footer by sidebar widget or something. Propably, cos mutiple included files does not re-register/ populates again in get_included_files().Otherwise, the intension must be clear to hack this problem. There is no way for a included file to report itself as included, until it has been included. Then its propably to late to use the scenario.
Most of the "time" you would like:
$template = get_current_loaded_template(); if($template == 'single-product.php') add_filter('the_title' .... if($template == 'format-gallery.php') add_action('post_thumbnail' ....
But thats not possible if the template is loaded outside Wordpress core method of
get_template_part
. Re-design your needs instead! Maybeloop_start()
,in_the_loop()
andadd_action('the_post')
has the solution you want, to alter data depending of template thats gonna load for each entry within a loop. -
Hotrovato questoper visualizzareilnome corrente delfile utilizzatonelmodello:
Fonte: ottieniilnome delmodello dipagina su unapagina
Funziona abbastanzabene,tranneperilfatto chenelbackend,nella casella di selezione delmodello,ottengo questabrutta vocein più:
Qualcuno haidea di come risolverlo? Non sonemmenoperché questafunzione viene chiamatanelbackend. Esiste unafunzione condizionale come
is_frontend()
-forse questo risolverebbeilproblema?