Le fichier functions.php est-il jamais appelé lors d'un appel AJAX?Déboguer AJAX
2 réponses
- votes
-
- 2013-04-20
admin-ajax.php
chargewp-load.php
:/** Load WordPress Bootstrap */ require_once( dirname( dirname( __FILE__ ) ) . '/wp-load.php' );
wp-load.php
chargewp-config.php
,et làwp-settings.php
est chargé.Etnoustrouvonsici ceci:
// Load the functions for the active theme, for both parent and child theme if applicable. if ( ! defined( 'WP_INSTALLING' ) || 'wp-activate.php' === $pagenow ) { if ( TEMPLATEPATH !== STYLESHEETPATH && file_exists( STYLESHEETPATH . '/functions.php' ) ) include( STYLESHEETPATH . '/functions.php' ); if ( file_exists( TEMPLATEPATH . '/functions.php' ) ) include( TEMPLATEPATH . '/functions.php' ); }
Donc,oui,le
functions.php
duthèmeest chargé.
Il y a uneexception dans
wp-settings.php
:// Stop most of WordPress from being loaded if we just want the basics. if ( SHORTINIT ) return false;
Lorsque
SHORTINIT
est défini commeTRUE
plustôt,lethèmene serapas chargé.Vérifiez donc si
SHORTINIT
estTRUE
pour une raison quelconque.
Une autreerreur couranteest lamauvaise utilisation de
is_admin()
. C'esttoujoursTRUE
dansadmin-ajax.php
,donc ce qui suit échouera:if ( ! is_admin() ) // register or execute AJAX stuff
Débogage AJAX
Uneméthode aussiprimitive qu'efficace consiste à utiliser l'en-tête HTTPpour déboguer AJAX.
Voici une simplefonction d'aide:
function send_debug_header( $msg ) { static $counter = 1; header( "X-Debug-Ajax-$counter: $msg" ); $counter += 1; }
Et cepluginmontre comment l'utiliser:
<?php # -*- coding: utf-8 -*- /** * Plugin Name: Debug AJAX per HTTP * Description: Look at the HTTP headers in your browser's network console */ // The constant is already defined when plugins are loaded. // Prove we have been called. if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) send_debug_header( 'File "' . __FILE__ . '" was called on an AJAX request.' ); function send_debug_header( $msg ) { static $counter = 1; header( "X-Debug-Ajax-$counter: $msg" ); $counter += 1; } add_action( 'wp_ajax_debug_test', 't5_debug_test' ); add_action( 'wp_ajax_nopriv_debug_test', 't5_debug_test' ); function t5_debug_test() { $in = is_user_logged_in() ? '' : 'not '; send_debug_header( 'Function "' . __FUNCTION__ . '" was called and the user is ' . $in . 'logged in.' ); print_r( debug_backtrace() ); die(1); } add_action( 'wp_enqueue_scripts', 't5_enqueue_jquery' ); function t5_enqueue_jquery() { wp_enqueue_script( 'jquery' ); } add_action( 'wp_footer', 't5_debug_ajax_test_button', 0 ); function t5_debug_ajax_test_button() { ?> <input type="submit" id="t5debugajax" value="Debug AJAX"> <script> jQuery( function($){ var sendFeedBack = function( response ){ console.log( response ); }; $("#t5debugajax").on("click", function(){ $.post( "<?php echo admin_url( 'admin-ajax.php' ); ?>", { action: "debug_test" }, sendFeedBack ); }); }); </script> <?php }
Cela ajoutera unbouton aufrontal qui déclenchera une requête AJAX lorsque l'utilisateur cliquera dessus. Ouvrez la console réseau de votrenavigateuret regardez lesen-têtes de réponsepour la demande:
admin-ajax.php
loadswp-load.php
:/** Load WordPress Bootstrap */ require_once( dirname( dirname( __FILE__ ) ) . '/wp-load.php' );
wp-load.php
loadswp-config.php
, and therewp-settings.php
is loaded.And here we find this:
// Load the functions for the active theme, for both parent and child theme if applicable. if ( ! defined( 'WP_INSTALLING' ) || 'wp-activate.php' === $pagenow ) { if ( TEMPLATEPATH !== STYLESHEETPATH && file_exists( STYLESHEETPATH . '/functions.php' ) ) include( STYLESHEETPATH . '/functions.php' ); if ( file_exists( TEMPLATEPATH . '/functions.php' ) ) include( TEMPLATEPATH . '/functions.php' ); }
So, yes, the theme’s
functions.php
is loaded.
There is one exception in
wp-settings.php
:// Stop most of WordPress from being loaded if we just want the basics. if ( SHORTINIT ) return false;
When
SHORTINIT
is defined asTRUE
earlier, the theme will not be loaded.So check if
SHORTINIT
isTRUE
for some reason.
Another common error is the wrong usage of
is_admin()
. This is alwaysTRUE
inadmin-ajax.php
, so the following will fail:if ( ! is_admin() ) // register or execute AJAX stuff
Debugging AJAX
One method as primitive as efficient is using HTTP header to debug AJAX.
Here is a simple helper function:
function send_debug_header( $msg ) { static $counter = 1; header( "X-Debug-Ajax-$counter: $msg" ); $counter += 1; }
And this plugin shows how to use it:
<?php # -*- coding: utf-8 -*- /** * Plugin Name: Debug AJAX per HTTP * Description: Look at the HTTP headers in your browser's network console */ // The constant is already defined when plugins are loaded. // Prove we have been called. if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) send_debug_header( 'File "' . __FILE__ . '" was called on an AJAX request.' ); function send_debug_header( $msg ) { static $counter = 1; header( "X-Debug-Ajax-$counter: $msg" ); $counter += 1; } add_action( 'wp_ajax_debug_test', 't5_debug_test' ); add_action( 'wp_ajax_nopriv_debug_test', 't5_debug_test' ); function t5_debug_test() { $in = is_user_logged_in() ? '' : 'not '; send_debug_header( 'Function "' . __FUNCTION__ . '" was called and the user is ' . $in . 'logged in.' ); print_r( debug_backtrace() ); die(1); } add_action( 'wp_enqueue_scripts', 't5_enqueue_jquery' ); function t5_enqueue_jquery() { wp_enqueue_script( 'jquery' ); } add_action( 'wp_footer', 't5_debug_ajax_test_button', 0 ); function t5_debug_ajax_test_button() { ?> <input type="submit" id="t5debugajax" value="Debug AJAX"> <script> jQuery( function($){ var sendFeedBack = function( response ){ console.log( response ); }; $("#t5debugajax").on("click", function(){ $.post( "<?php echo admin_url( 'admin-ajax.php' ); ?>", { action: "debug_test" }, sendFeedBack ); }); }); </script> <?php }
It will add a button to the front end that triggers an AJAX request when clicked. The open your browser’s network console and look at the response headers for the request:
-
Plus détaillé quejamais,@toscho.C'estparticulièrement difficile à déboguer lorsque le codefonctionne correctement de votre côtémaispaspour quelqu'un d'autre.Jen'arrivepas à reproduire leproblèmemais votre réponsem'enverraprobablement dans labonne direction.As detailed as ever, @toscho. Its especially hard to debug when the code runs fine on your end but not for someone else. Can't seem to reproduce the problem but your answer will probably send me in the right direction.
- 0
- 2013-04-20
- Manny Fleurmond
-
@MannyFleurmond J'ai ajouté unplugin d'aide au débogage.Cela devrait aider àtrouver leproblème.@MannyFleurmond I have added a debug helper plugin. That should help finding the problem.
- 0
- 2013-04-20
- fuxia
-
Mec,tuesminutieux :)Man, you are thorough :)
- 9
- 2013-04-20
- Manny Fleurmond
-
`TEMPLATEPATH`?;)`TEMPLATEPATH`? ;)
- 0
- 2013-07-14
- kaiser
-
- 2013-05-20
Je suppose que votreproblème était qu'AJAXfonctionnait si vous êtes connectéet qu'ilne fonctionnaitpasen statut déconnecté,n'est-cepas?
Ilexiste unefonction dans WordPresspour accéder auxfichiers AJAXpour les utilisateursnon connectés:wp_ajax_nopriv
,parexemple/* works for logged users */ add_action( 'wp_ajax_my_action', 'my_action_callback'); /* works for non logged users */ add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback');
I assume your problem was AJAX was working if your are logged in and it was not working in logged out status, right?
There is a function in WordPress to access AJAX-based files for non logged users:wp_ajax_nopriv
, for example/* works for logged users */ add_action( 'wp_ajax_my_action', 'my_action_callback'); /* works for non logged users */ add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback');
Essayer de comprendre unproblème rencontrépar un collègueprogrammeur.Jeme demandais si lefichier
functions.php
était appelé quand vousfaites AJAX côté administrateur?Je sais que lorsque vouseffectuez un appel AJAX,unepartie de WPest chargée detraiter l'appelet de renvoyer une réponse.Lefichierfunctions.php
est-ilinclus dans celui-ci?La raisonpour laquelleje pose la questionest qu'il utilise la classe duplugin Meta-Box`et la charge à laplace dans le cadre d'unthème.Il y a un AJAX dans cette classe quine renvoie que des réponses videset jepense que c'estparce que le code quigère la réponsene se chargepas.Existe-t-il une documentation sur ce quiest chargé lorsque WPgère AJAX?