Last active
March 20, 2018 14:07
-
-
Save webdados/053ad2fe6cfe3f35ad4bbce75784e897 to your computer and use it in GitHub Desktop.
Shortcode and automatic AJAX content reload immediately after page load - WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* Shortcode actualizado por Ajax */ | |
//My shortcode that outputs the DIV and the necessary javascript (which should be external actually) | |
add_shortcode( 'my_shortcode' , 'my_shortcode_function' ); | |
function my_shortcode_function() { | |
ob_start(); | |
echo my_shortcode_function_content(); | |
?> | |
<script type="text/javascript"> | |
jQuery(document).ready(function($) { | |
if ( $( '#my_shortcode_div' ).length ) { | |
$.ajax({ | |
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>', | |
type: 'get', | |
data: { | |
action: 'my_shortcode_ajax_action' | |
}, | |
success: function(data) { | |
$( '#my_shortcode_div' ).replaceWith( data ); | |
}, | |
fail: { | |
} | |
}); | |
} | |
}); | |
</script> | |
<?php | |
return ob_get_clean(); | |
} | |
//The actual DIV content | |
function my_shortcode_function_content() { | |
ob_start(); | |
?> | |
<div id="my_shortcode_div"> | |
This is the shortcode content. | |
<br/> | |
Date / time: <?php echo date( 'Y-m-d H:i:s' ); ?> | |
<br/> | |
Random number: <?php echo rand( 0, 1000 ); ?> | |
<br/> | |
Origin: <?php echo defined('DOING_AJAX') && DOING_AJAX ? 'AJAX' : 'Page load'; ?> | |
</div> | |
<?php | |
return ob_get_clean(); | |
} | |
//The Ajax action | |
add_action( 'wp_ajax_my_shortcode_ajax_action', 'my_shortcode_function_ajax' ); | |
add_action( 'wp_ajax_nopriv_my_shortcode_ajax_action', 'my_shortcode_function_ajax' ); | |
function my_shortcode_function_ajax() { | |
echo my_shortcode_function_content(); | |
wp_die(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment