PHP:
The PHP code for the shortcode should include the following:
function random_quote( $atts ) { // Extract shortcode attributes extract( shortcode_atts( array( 'path' => get_template_directory_uri() . '/quotes.txt' // Default path ), $atts ) ); // Retrieve quotes from file $array = file( $path ); $r = rand( 0, count($array) - 1 ); // Render shortcode output $output = '<div>
jQuery:
Handle the button click and perform the AJAX request:
jQuery('#newquote').click( function() { // Send AJAX request to retrieve a new quote $.ajax({ type: 'POST', url: ajaxParams.themeURI+'js/ajax-load-quote.php', data: { file_path: ajaxParams.filePath }, beforeSend: function() { ajaxLoadingScreen(true,'#randomquotes'); }, success: function(data) { // Replace old quote with new one jQuery('#randomquotes').find('p').remove(); jQuery('#randomquotes').prepend(data); }, complete: function() { ajaxLoadingScreen(false,'#randomquotes'); } }); return false; });
The above is the detailed content of How to Integrate AJAX Functionality within a WordPress Shortcode?. For more information, please follow other related articles on the PHP Chinese website!