5t3ph

Use Baked-In AJAX to Query Checked Tags

Nov 16th, 2011
439
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.99 KB | None | 0 0
  1. <?php
  2.  
  3. /*
  4. Plugin Name: Ajax Tags
  5. Description: Retrieve list of posts instantly by selecting a tag.
  6. Version: 1.0
  7. Author: Stephanie Scharf
  8. Author URI: http://stephscharf.me
  9. */
  10.  
  11.  
  12. // Get all tags in use
  13. // call list_ajax_tags() in theme where you want to display these tags
  14. function list_ajax_tags() {
  15.    
  16.     $tags = get_tags();
  17.     $tag_list = '<div class="post_tags">';
  18.     foreach ($tags as $tag){
  19.         $tag_list .= '<input class="tagcheck" type="checkbox" value="'.$tag->slug.'" />'.$tag->name;
  20.  
  21.     }
  22.     $tag_list .= '</div>';
  23.     $tag_list .= '<div id="tag_results"></div>';
  24.  
  25. echo $tag_list;
  26. }
  27.  
  28.  
  29.  // Load jQuery/CSS
  30.  // Codex: http://codex.wordpress.org/AJAX_in_Plugins
  31. add_action('wp_head', 'ajax_tags_jquery');
  32. function ajax_tags_jquery() {
  33.     $filepath = plugin_dir_url( __FILE__ );
  34.     ?>
  35.    
  36.         <script type="text/javascript">
  37.         jQuery(document).ready(function($){
  38.           $(".tagcheck").click(function() {
  39.                 $slug = $(this).val();                     
  40.                 var data = {
  41.                     action: 'tag_slug',
  42.                     slug: $slug
  43.                 };
  44.  
  45.             var ajaxurl = 'wp-admin/admin-ajax.php';
  46.             jQuery.post(ajaxurl, data, function(response) {
  47.                 $('#tag_results').html(response);
  48.             });
  49.         });
  50.         });
  51.         </script>
  52.  
  53. <?php }
  54.  
  55. // Invoke baked-in WP ajax goodness
  56. // Codex: http://codex.wordpress.org/AJAX_in_Plugins
  57. add_action('wp_ajax_tag_slug', 'tag_slug_callback');
  58.  
  59. function tag_slug_callback() {
  60.     global $wpdb;
  61.  
  62. function taglist() {
  63.     // Retrieve tag slug from POST
  64.     $tagslug = $_POST['slug'];
  65.     ?>
  66.  
  67.     <ul>
  68.     <?php
  69.     // Query 5 posts from the tag that was selected
  70.     $args = array( 'posts_per_page' => 5, 'tag' => $tagslug );
  71.     $tag_query = new WP_Query( $args );
  72.     while ( $tag_query->have_posts() ) : $tag_query->the_post();
  73.     ?>
  74.         <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
  75.    
  76.     <?php endwhile; wp_reset_postdata(); ?>
  77.     </ul>
  78.    
  79.     <?php }
  80.  
  81.     echo taglist();
  82.  
  83.     die(); // this is required to return a proper result
  84. }
  85. ?>
  86.  
Advertisement
Add Comment
Please, Sign In to add comment