Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Ajax Load a page content by id
- add_action('wp_ajax_my_ajax_action', 'my_ajax_function');
- add_action('wp_ajax_nopriv_my_ajax_action', 'my_ajax_function');
- function my_ajax_function(){
- if (wp_verify_nonce($_POST['nonce_get'], 'my_ajax_action')) {
- $q = new WP_Query(array(
- 'posts_per_page' => 1,
- 'p' => $_POST['page_id_get'],
- 'post_type' => 'page'
- ));
- $html = '<div>';
- while($q->have_posts()) : $q->the_post();
- $html .= '<div>'.get_the_content().'</div>';
- endwhile; wp_reset_query();
- $html .= '</div>';
- } else {
- echo '<div class="alert alert-danger">Error</div>';
- }
- echo $html;
- die();
- };
- function my_ajax_shortcode(){
- $html = '<button data-nonce="'.wp_create_nonce('my_ajax_action').'" data-id="2" class="my_ajax_trigger">Load sample page content</button>
- <div id="info"></div>
- <script>
- jQuery(document).ready(function($){
- $(".my_ajax_trigger").on("click", function(){
- var page_id = $(this).attr("data-id");
- var nonce = $(this).attr("data-nonce");
- $.ajax({
- url: "'.admin_url("admin-ajax.php").'",
- data: {
- action: "my_ajax_action",
- page_id_get: page_id,
- nonce_get: nonce
- },
- type: "POST",
- beforeSend: function(){
- $("#info").empty();
- $("#info").append("loading....");
- },
- success: function(html){
- $("#info").empty();
- $("#info").append(html);
- }
- });
- });
- });
- </script>
- ';
- return $html;
- }
- add_shortcode('ajax_shortcode', 'my_ajax_shortcode');
Advertisement
Add Comment
Please, Sign In to add comment