J'essaie d'obtenir les valeurs de profil utilisateur à l'aide d'un appel AJAX, mais la réponse est toujours 0. Voici mon PHP:
wp_enqueue_script( // Add JS to <head>
'cc-author-change-post-author',
plugins_url( 'assets/js/change-post-author.js', dirname( __FILE__ ) ),
'jquery'
);
wp_localize_script( // Localize script for AJAX calls
'cc-author-change-post-author', // Name of script call being localized
'authorchange', // AJAX object namespace, used to call values in the JS file
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ), // URL for admin AJAX calls
'nonce' => wp_create_nonce( 'cc-author-change-author-nonce' ) // Nonce to authenticate request
)
);
function cc_author_change_postauthor_callback() {
$nonce = $_POST['nonce']; // Assign a local variable for nonce
if ( ! wp_verify_nonce( $nonce, 'cc-author-change-author-nonce' ) ) { // If the nonce doesn't check out, fail the request
exit( 'Your request could not be authenticated' ); // Error message for unauthenticated request
}
if ( current_user_can( 'edit_others_posts' ) || current_user_can( 'edit_others_pages' ) ) { // Check for proper permissions before handling request
$author = $_POST['authorID']; // Assign local variable for submitted post author
if ( $author ) { // If an author ID was provided, get the user's details
$authordata = get_userdata( $author ); // Retrieve the selected user's data from their profile
$authormeta = json_encode( array( // Encode data as JSON
'display_name' => $authordata['display_name'], // Display name from profile
'description' => $authordata['description'] // Biographical info from profile
) );
}
else { // If no author ID was provided, send back an error message
$authormetaerror = 'No user ID provided. Please try again.'; // Error message to send back
$authormeta = json_encode( array( // Encode as JSON
'display_name' => $authormetaerror,
'description' => $authormetaerror
) );
}
echo $authormeta; // Return the values retrieved from the database
}
exit; // End response. Required for callback to return a proper result.
} // cc_author_change_postauthor_callback()
add_action( 'wp_ajax_cc_author_change_postauthor', 'cc_author_change_postauthor_callback' );
Et voici mon JavaScript:
jQuery( document ).ready( function( $ ) { // Don't execute anything until the page is loaded
$( "#cc_author_postauthor" ).change( function() { // If the author dropdown value is changed, execute the script
/* Data to pass to the server. Called below during $.post() */
var data = {
action : 'cc_author_change_postauthor', // Action hook for the server-side callback
nonce : authorchange.nonce, // Nonce received from server to authenticate request
authorID : $( "#cc_author_postauthor" ).val() // author ID for retrieving profile data
};
/* Send request to the server and process response */
$.post(
authorchange.ajaxurl, // URL to send the request to the server
data, // Data to send to the server, stored in var data
function( jsonString ) { // Script to execute upon successful response from server
var authormeta = $.parseJSON( jsonString ); // Parse the JSON received from the server response
$( "#cc_author_meta\\[0\\]\\[display_name\\]" ).val( authormeta.display_name ); // Change the value of the author display name to the value received from the server
$( "#cc_author_meta\\[0\\]\\[description\\]" ).val( authormeta.description ); // Change the value of the author bio to the value received from the server
} // function( jsonString )
); // $.post
}); // $( "#cc_author_postauthor" ).change()
});
Voici la boîte de méta où se trouve l'élément de formulaire:
function cc_author_metabox( $post ) {
/* Retrieve current values if they exist */
$cc_author_meta = get_post_meta( $post->ID, '_cc_author_meta', true ); // Author meta data (stored as an array)
$postauthorid = $post->post_author; // Get the user ID of the post author
/* If any of the values are missing from the post, retrieve them from the author's global profile */
if ( !$cc_author_meta ) {
$postauthor = get_userdata( $postauthorid ); // Retrieve the details of the post author
$cc_author_meta = array(); // Initialize main array
$cc_author_meta[0] = array( // Nested array for author data
'display_name' => $postauthor->display_name, // Set display name from post author's data
'description' => $postauthor->description // Set bio from the post author's data
);
}
/* Display the meta box contents */
?>
<div class="cc_author_metabox">
<p>Changes made to this information will only apply to this post, and will not be saved to the user's profile.</p>
<?php
if ( current_user_can( 'edit_others_posts' ) || current_user_can( 'edit_others_pages' ) ) { // Check the capabilities of the current user for sufficient privileges
wp_dropdown_users( array(
'name' => 'cc_author_postauthor', // Name for the form item
'id' => 'cc_author_postauthor', // Class for the form item
'selected' => $postauthorid // Select the post's author to be displayed by default
) );
?>
<noscript>
You have JavaScript disabled. If you change the post author in the dropdown, you will need to save the post for the fields below to update. Please enable JavaScript for a better experience.
</noscript>
<div id="cc_author_postauthor_loading" class="cc_author_postauthor_loading"><img id="cc_author_postauthor_loading_img" class="cc_author_postauthor_loading_img" src="<?php echo plugins_url( 'assets/img/loading.gif', dirname( __FILE__ ) ); ?>" width="20px" style="width: 20px;"></div>
<input type="hidden" name="cc_author_currentpostauthor" value="<?php echo $postauthorid; ?>">
<?php
}
?>
<label for="cc_author_meta[0][display_name]" class="selectit">Name</label>
<input type="text" name="cc_author_meta[0][display_name]" id="cc_author_meta[0][display_name]" value="<?php echo esc_attr( $cc_author_meta[0]['display_name'] ); ?>" />
<label for="cc_author_meta[0][description]" class="selectit">Bio</label>
<?
$descEditor = new ccAuthorDescEditor( $cc_author_meta[0]['description'], 'cc_author_meta[0][description]' ); // Create the bio editor object
echo $descEditor->editor(); // Display the editor
?>
</div>
<?php
}
Je suis sûr que la réponse est juste devant moi, mais c’est la première fois que j’utilise l’API WordPress AJAX. Qu'est-ce que je fais mal?
Vous pouvez voir le code complet du plugin sur son référentiel Github .
Votre crochet d’action devrait être
add_action( 'wp_ajax_cc_author_change_postauthor', 'cc_author_change_postauthor_callback' );
Je pense qu'en raison de votre mauvais crochet, votre fonction de rappel n'est jamais appelée.
Vous vous êtes peut-être trompé aussi. Dans votre code JS, veuillez modifier votre action de
cc-author-change-postauthor
à
cc_author_change_postauthor
J'ai résolu le problème. J'étais conditionnellement inclus dans le fichier où se trouvait mon code PHP uniquement si l'URI de la demande était l'un de ceux permettant de modifier une page ou une publication. En tant que tel, le code PHP n'était pas inclus lorsqu'une requête est arrivée via admin-ajax.php. J'ai corrigé cela et maintenant je suis prêt. Merci pour l'aide de tous!
au lieu de
exit; // End response. Required for callback to return a proper result.
utilisez les fonctions die()
ou wp_die()
". Cela devrait être corrigé.