rajudhaka

Ajax Show product list

Jul 27th, 2019
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. add_action('wp_ajax_my_ajax_action', 'my_ajax_function');
  2. add_action('wp_ajax_nopriv_my_ajax_action', 'my_ajax_function');
  3.  
  4. function my_ajax_function(){
  5.    
  6.     $q = new WP_Query(array(
  7.         'posts_per_page' => 10,
  8.         'post_type' => 'product'
  9.      ));
  10.     $html = '<ul>';
  11.  
  12.     while($q->have_posts()) : $q->the_post();
  13.  
  14.  
  15.     $html .= '<li>'.get_the_title().'</li>';
  16.  
  17.    
  18. endwhile; wp_reset_query();
  19. $html .= '</ul>';
  20.     echo $html;
  21.     die();
  22. };
  23.  
  24. function my_ajax_shortcode(){
  25.     $html = '<button class="my_ajax_trigger">Test</button>
  26.         <div id="info"></div>
  27.         <script>
  28.             jQuery(document).ready(function($){
  29.                 $(".my_ajax_trigger").on("click", function(){
  30.                     $.ajax({
  31.                         url: "'.admin_url("admin-ajax.php").'",
  32.                         data: {
  33.                             action: "my_ajax_action"
  34.                         },
  35.                         type: "POST",
  36.                         success: function(html){
  37.                             $("#info").append(html);
  38.                         }
  39.                     });
  40.                 });
  41.             });
  42.         </script>
  43.         ';
  44.     return $html;
  45. }
  46. add_shortcode('ajax_shortcode', 'my_ajax_shortcode');
Advertisement
Add Comment
Please, Sign In to add comment