rajudhaka

Ajax Load a page content by id

Jul 27th, 2019
329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Ajax Load a page content by id
  2.  
  3. add_action('wp_ajax_my_ajax_action', 'my_ajax_function');
  4. add_action('wp_ajax_nopriv_my_ajax_action', 'my_ajax_function');
  5.  
  6.  
  7. function my_ajax_function(){
  8.    
  9. if (wp_verify_nonce($_POST['nonce_get'], 'my_ajax_action')) {
  10.     $q = new WP_Query(array(
  11.         'posts_per_page' => 1,
  12.         'p' => $_POST['page_id_get'],
  13.         'post_type' => 'page'
  14.      ));
  15.     $html = '<div>';
  16.  
  17.     while($q->have_posts()) : $q->the_post();
  18.  
  19.  
  20.     $html .= '<div>'.get_the_content().'</div>';
  21.  
  22.    
  23. endwhile; wp_reset_query();
  24. $html .= '</div>';
  25. } else {
  26.     echo '<div class="alert alert-danger">Error</div>';
  27. }
  28.     echo $html;
  29.     die();
  30. };
  31.  
  32. function my_ajax_shortcode(){
  33.     $html = '<button data-nonce="'.wp_create_nonce('my_ajax_action').'" data-id="2" class="my_ajax_trigger">Load sample page content</button>
  34.         <div id="info"></div>
  35.         <script>
  36.             jQuery(document).ready(function($){
  37.                 $(".my_ajax_trigger").on("click", function(){
  38.                     var page_id = $(this).attr("data-id");
  39.                     var nonce = $(this).attr("data-nonce");
  40.                     $.ajax({
  41.                         url: "'.admin_url("admin-ajax.php").'",
  42.                         data: {
  43.                             action: "my_ajax_action",
  44.                             page_id_get: page_id,
  45.                             nonce_get: nonce
  46.                         },
  47.                         type: "POST",
  48.                         beforeSend: function(){
  49.                             $("#info").empty();
  50.                             $("#info").append("loading....");
  51.                         },
  52.                         success: function(html){
  53.                             $("#info").empty();
  54.                             $("#info").append(html);
  55.                         }
  56.                     });
  57.                 });
  58.             });
  59.         </script>
  60.         ';
  61.     return $html;
  62. }
  63. add_shortcode('ajax_shortcode', 'my_ajax_shortcode');
Advertisement
Add Comment
Please, Sign In to add comment