Advertisement
manchumahara

Ajax in Wordpress in wordpress way

Jul 8th, 2012
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. <script type="text/javascript">
  2. jQuery(document).ready(function($) {
  3. //console.log('ready');
  4. jQuery("#cbrpsearchfieldbt").click(function(){
  5. $("#cbrpsearchfield").keypress();
  6. });
  7.  
  8. $("#cbrpsearchfield").keypress(function() {
  9. var cbrpsearchterm = jQuery("#cbrpsearchfield").val();
  10. //console.log(cbrpsearchterm);
  11. //console.log(cbrpsearchterm.length);
  12. if(cbrpsearchterm.length > 2){
  13. //console.log('click');
  14. var data = {
  15. action: 'cbrelatedpostajax',
  16. rpsearchterm:cbrpsearchterm,
  17. postid:<?php echo $post->ID; ?>
  18. };
  19.  
  20. // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
  21. jQuery.post(ajaxurl, data, function(response) {
  22. //alert('Got this from the server: ' + response);
  23. jQuery('#cbrelatedpostsresult').html(response);
  24. });
  25. }
  26. })
  27.  
  28. });
  29. </script>
  30.  
  31.  
  32.  
  33. if( is_admin() )
  34. {
  35. add_action('wp_ajax_cbrelatedpostajax', 'cbrelatedpostajax_callback');
  36.  
  37. // Load "admin-only" scripts here
  38. }
  39.  
  40. function cbrelatedpostajax_callback(){
  41. ob_clean();
  42. $rpsearchterm = $_POST['rpsearchterm'] ;
  43. $postid = $_POST['postid'];
  44. $cbargs = array('post_type' => 'product', 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC', 'posts_per_page' => 20, 's' => $rpsearchterm );
  45. $upprev_query = new WP_Query( $cbargs );
  46. if ($upprev_query->have_posts()) {
  47. while ( $upprev_query->have_posts() ) {
  48. $upprev_query->the_post();
  49. $id = get_the_ID();
  50. if($postid != $id )echo '<li>'.get_the_title().' - '. $id .'</li>';
  51. }
  52. }
  53. else echo '<li>No search result found</li>';
  54.  
  55. die();
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement