Come sovrascrivere i file JavaScript nel child theme?
-
-
Qual èiltemaprincipale?Come vengono * chiamati *gli script daltemaprincipale?What is the parent Theme? How are the scripts being *called* by the parent Theme?
- 1
- 2011-08-24
- Chip Bennett
-
4 risposta
- voti
-
- 2011-08-24
Itemi figlio sovrascrivono soloi filephp (come header.php)inclusiin funzioni comeget_template_part oget_header,ecc.
Ilmodo correttoper aggiungere script a WordPress è con wp_enqueue_script . Seiltuotemaprincipale lo utilizza,puoi sovrascriverei file JS utilizzando wp_dequeue_script e accodandoiltuo.
In questomodo ...
<?php // hook in late to make sure the parent theme's registration // has fired so you can undo it. Otherwise the parent will simply // enqueue its script anyway. add_action('wp_enqueue_scripts', 'wpse26822_script_fix', 100); function wpse26822_script_fix() { wp_dequeue_script('parent_theme_script_handle'); wp_enqueue_script('child_theme_script_handle', get_stylesheet_directory_uri().'/scripts/yourjs.js', array('jquery')); }
Seiltemaprincipalenon utilizza wp_enqueue_script,probabilmente si sta collegando a wp_head (o wp_footer)per riprodurregli scriptpresenti. Quindi useresti remove_action per sbarazzarti di quellefunzioni chefannoeco agli scripte poi accodareiltuo script.
Se lo script è hardcodednelfilemodello,dovrai solo sostituire quelfilemodelloneltuo childtheme senzailtag script.
Se hanno utilizzato chiamate wp_enqueue_script che utilizzano get_stylesheet_directory_uri ,non dovrestifarenulla. Poiché questonon sta accadendo,dovrai solo curiosaree vedere cosa hafatto l'autore deltema.
Child themes only override php files (like header.php) that are included with functions like get_template_part or get_header, etc.
The correct way to add scripts to WordPress is with wp_enqueue_script. If your parent theme uses this, you can override the JS files by using wp_dequeue_script and enqueuing your own.
Like so...
<?php // hook in late to make sure the parent theme's registration // has fired so you can undo it. Otherwise the parent will simply // enqueue its script anyway. add_action('wp_enqueue_scripts', 'wpse26822_script_fix', 100); function wpse26822_script_fix() { wp_dequeue_script('parent_theme_script_handle'); wp_enqueue_script('child_theme_script_handle', get_stylesheet_directory_uri().'/scripts/yourjs.js', array('jquery')); }
If the parent theme isn't using wp_enqueue_script, it's probably hooking into wp_head (or wp_footer) to echo out the scripts there. So you'd use remove_action to get rid of those functions echoing the scripts out, and then enqueue your own script.
If the script is hard coded into the template file, you'll just need to replace that template file in your child theme without the script tag.
If they used wp_enqueue_script calls that utilize get_stylesheet_directory_uri, then you shouldn't have to do anything. Since this isn't happening, you'll just have to poke around and see what the theme author did.
-
seiltemaprincipale utilizzaget_stylesheet_directory_uriper accodaregli script,iltemafiglio ** dovrà ** duplicaretuttigli script così accodati,perché altrimentinon verrannotrovati.Nonesiste unmeccanismo difallbackin get_stylesheet_directory_uriper verificare seesiste un **file singolo **neltemafiglioe tornare alfile deltemaprincipale,senecessario.if the parent theme uses get_stylesheet_directory_uri to enqueue scripts, then the child theme will **have** to duplicate all scripts thus enqueued, because otherwise they woun't be found. There is no fallback mechanism in get_stylesheet_directory_uri to check if an **individual file** exists in the child theme and fall back to the parent theme's file if necessary.
-
Dal Codex: "Wp_print_scriptsnon dovrebbeessere usatoper accodare stili o script sullaprimapagina.Usainvece wp_enqueue_scripts." http://codex.wordpress.org/Plugin_API/Action_Reference/wp_print_scriptsFrom the Codex: “wp_print_scripts should not be used to enqueue styles or scripts on the front page. Use wp_enqueue_scripts instead. ” http://codex.wordpress.org/Plugin_API/Action_Reference/wp_print_scripts
- 0
- 2013-08-13
- Christian Lescuyer
-
Tienipresente quando è stato scritto: due annifa.Prima che `wp_enqueue_scripts`potesseessere usato soloper accodaregli script sulfront-end.Aggiornato.Se vedi qualcosa di obsoleto,sentiti libero dimodificarlo.Keep in mind when this was written: two years ago. Before `wp_enqueue_scripts` could be used to only enqueue scripts on the front end. Updated. If you see something out of date, feel free to edit.
- 0
- 2013-08-13
- chrisguitarguy
-
Scusa,nessuna criticaimplicita,ho votatopositivamente latua risposta :)Sorry, no criticism implied, I did upvote your answer :)
- 0
- 2013-08-16
- Christian Lescuyer
-
Tienipresente chepotresti doverimpostare unaprioritàtardiva (adesempio 100)per assicurarti che la rimozione dalla coda avvenga * dopo * l'accodamento deltemaprincipale. "add_action ('wp_enqueue_scripts','wpse26822_script_fix',100);" da http://codex.wordpress.org/Function_Reference/wp_dequeue_scriptPlease note that you may have to set a late priority (for instance 100) to make sure your dequeue happens *after* the parent theme enqueue. `add_action( 'wp_enqueue_scripts', 'wpse26822_script_fix', 100 );` from http://codex.wordpress.org/Function_Reference/wp_dequeue_script
- 4
- 2014-09-04
- Spone
-
Aggiornamentoperil 2016: secondo http://stackoverflow.com/questions/23507179/wp-dequeue-script-for-child-theme-to-replace-script dobbiamo anche usare `wp_deregister_script ('parent-script-handle'); `per rimuovere completamente lo scriptprincipale.Ineffetti,non hafunzionatoperme senza diessa.WP 4.6.1Update for 2016: according to http://stackoverflow.com/questions/23507179/wp-dequeue-script-for-child-theme-to-replace-script we also have to use `wp_deregister_script('parent-script-handle');` to completely remove the parent script. Indeed, it didn't work for me without it. WP 4.6.1
- 4
- 2016-11-30
- PhiLho
-
puoi rispondere allamia domanda quiperfavore?Questa risposta è unpo 'confusa: https://wordpress.stackexchange.com/questions/286957/modifying-js-files-in-child-themecan you answer my question here please? This answer is a bit confusing:https://wordpress.stackexchange.com/questions/286957/modifying-js-files-in-child-theme
- 0
- 2017-11-26
- csandreas1
-
@PhiLho,sto usando 5.4,e `wp_dequeue_script ()` * ha *funzionato da soloperme.Iltemaprincipale aveva `wp_enqueue_script ('fitvids',get_template_directory_uri (). '/Js/fitvids.js',array ('jquery'),'1.1',true);` -forse ha a chefare conilmodoin cuiillo script è stato caricato daltemaprincipale?@PhiLho, I'm using 5.4, and `wp_dequeue_script()` *did* work for me by itself. The parent theme had `wp_enqueue_script( 'fitvids', get_template_directory_uri() . '/js/fitvids.js', array( 'jquery' ), '1.1', true );` -- maybe it has to do with the way the script was loaded by the parent theme?
- 0
- 2020-04-05
- kkm
-
@PhiLho,ho anche aggiunto `wp_deregister_script`,questonon ha cambiatonulla,maforse ha rilasciato unpo 'dimemoriainutilmentetenuta dalla registrazione dello script.Ho anche dovuto aggiungere due azioniper 'wp_enqueue_scripts',laprioritàpredefinitaper caricareilmiofoglio di sostituzione CSS,maper sbarazzarmi dello scriptne ho aggiunto un altro,conpriorità 100,come suggerito dalla risposta.Mailfatto chenon abbiafunzionatononpuòessere spiegato dalfiasco dell'ordine di caricamento,perchénelmio caso,lo scaricamento o l'annullamento della registrazionenelnormale hookpriotiry registrava soloerrori.Strano,in ogni caso.@PhiLho, I also added `wp_deregister_script`, this changed nothing, but maybe released some memory uselessly held by the script registration. I also had to add two actions for 'wp_enqueue_scripts', the default-priority to load my css override sheet, but to get rid of the script I added another, with the priority 100, as the answer suggested. But the fact it did not work cannot be explained by the load order fiasco, because in my case, unloading or deregistering in the normal-priotiry hook only logged errors. Strange, in any case.
- 0
- 2020-04-05
- kkm
-
- 2015-11-11
In alcuni casi èimportante dare lapriorità alle chiamate difunzione add_actione wp_enqueue_scriptin questomodo:
add_action('wp_enqueue_scripts', 'wpse26822_script_fix', 20120207); function wpse26822_script_fix() { wp_dequeue_script('storefront-navigation'); wp_enqueue_script('my_storefront-navigation', get_stylesheet_directory_uri().'/js/navigation.min.js', array('jquery'),20151110,true); }
In questo caso,wp_enqueue_scripts è stato chiamato dalgenitore con unapriorità di 20120206 (la data)e quindi questa azione viene aggiunta con unapriorità appenamaggiorein modo che vengaimmediatamente rimossa dalla coda. Quindi,l'istruzioneenqueue che segue vieneeffettivamente assegnata lapriorità dopo quellapergarantire che venga caricata dopo che quella vecchia è stata rimossa dalla coda. Il vero,in questo caso è ancheimportanteperché specifica che deveessere accodatonelpiè dipagina,che èilpuntoin cui lo scriptgenitore è stato accodatoper laprima volta.
Inoltre,non riesco a spiegarlo completamente,ma honotato che se stai attento a rimuovere lo scriptinizialeimmediatamente dopo che è stato accodato,sembra chetupossaeffettivamenteimpedirneil caricamentoin primo luogo. >
In some cases it is important to prioritize both the add_action and the wp_enqueue_script function calls like so:
add_action('wp_enqueue_scripts', 'wpse26822_script_fix', 20120207); function wpse26822_script_fix() { wp_dequeue_script('storefront-navigation'); wp_enqueue_script('my_storefront-navigation', get_stylesheet_directory_uri().'/js/navigation.min.js', array('jquery'),20151110,true); }
In this case, wp_enqueue_scripts was called by the parent with a priority of 20120206 (the date) and so this action is added with a priority just barely greater so that it will immediately be dequeued. Then, the enqueue statement that follows that follows is actually prioritized after that to ensure that it loads after the old one was dequeued. The true, in this case is also important because that specifies that it is to be enqueued in the footer, which is where the parent script was first enqueued.
Also, I can't quite explain it entirely, but I notice that if you are careful with dequeuing the initial script immediately after it being enqueued, it seems you can effectively prevent it from loading in the first place.
-
Lafunzione `wp_enqueue_script`non ha unparametro dipriorità,è solo unnumero di versione che è concatenato allafine delpercorso come stringa di query._Questoparametro viene utilizzatopergarantire che la versione corretta vengainviata al clientindipendentemente dallamemorizzazionenella cache [...] _The function `wp_enqueue_script` doesn't have a priority parameter, it's only a version number which is concatenated to the end of the path as a query string. _This parameter is used to ensure that the correct version is sent to the client regardless of caching [...]_
- 1
- 2016-01-18
- Emile Bergeron
-
- 2016-12-25
chiama wp_deregister_script prima di registrare latua versione
call wp_deregister_script before register your own version
-
Perché?Questo ènecessario solo quando usi la stessamaniglia,cosa chenon devifare.Probabilmentenon dovrestinemmeno,perché èpiùfacileeseguireil debug del codice la cuifonte è chiara.Why? This is only needed when you are using the same handle – something you don't have to do. You probably even shouldn't, because it is easier to debug code whose source is clear.
- 1
- 2016-12-25
- fuxia
-
- 2019-05-28
// enqueue your required script file add_action('wp_enqueue_scripts', 'your_child_theme_js_file_override'); function your_child_theme_js_file_override(){ wp_enqueue_script( 'child_theme_script_handle', get_stylesheet_directory_uri() . '/assets/js/your-file.js', array('jquery' ) ); } // dequeue your required script file function your_child_theme_js_file_dequeue() { wp_dequeue_script( 'parent_theme_script_handle' ); } add_action( 'wp_print_scripts', 'your_child_theme_js_file_dequeue', 100 );
// enqueue your required script file add_action('wp_enqueue_scripts', 'your_child_theme_js_file_override'); function your_child_theme_js_file_override(){ wp_enqueue_script( 'child_theme_script_handle', get_stylesheet_directory_uri() . '/assets/js/your-file.js', array('jquery' ) ); } // dequeue your required script file function your_child_theme_js_file_dequeue() { wp_dequeue_script( 'parent_theme_script_handle' ); } add_action( 'wp_print_scripts', 'your_child_theme_js_file_dequeue', 100 );
Sto caricando alcunifile JavaScriptneltemaprincipale.Ilpercorsoneltemaprincipale è:
Nel childtheme,sto creando lo stessopercorso (
scripts > custom.js
)e cambiandoparte dijQuery all'interno delfilecustom.js
.Ilproblema è che lemodifichenon vengono applicate.È questoilmodo sbagliatoper apportaremodifiche a questifilenel childtheme?