Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- Plugin Name: Ajax Tags
- Description: Retrieve list of posts instantly by selecting a tag.
- Version: 1.0
- Author: Stephanie Scharf
- Author URI: http://stephscharf.me
- */
- // Get all tags in use
- // call list_ajax_tags() in theme where you want to display these tags
- function list_ajax_tags() {
- $tags = get_tags();
- $tag_list = '<div class="post_tags">';
- foreach ($tags as $tag){
- $tag_list .= '<input class="tagcheck" type="checkbox" value="'.$tag->slug.'" />'.$tag->name;
- }
- $tag_list .= '</div>';
- $tag_list .= '<div id="tag_results"></div>';
- echo $tag_list;
- }
- // Load jQuery/CSS
- // Codex: http://codex.wordpress.org/AJAX_in_Plugins
- add_action('wp_head', 'ajax_tags_jquery');
- function ajax_tags_jquery() {
- $filepath = plugin_dir_url( __FILE__ );
- ?>
- <script type="text/javascript">
- jQuery(document).ready(function($){
- $(".tagcheck").click(function() {
- $slug = $(this).val();
- var data = {
- action: 'tag_slug',
- slug: $slug
- };
- var ajaxurl = 'wp-admin/admin-ajax.php';
- jQuery.post(ajaxurl, data, function(response) {
- $('#tag_results').html(response);
- });
- });
- });
- </script>
- <?php }
- // Invoke baked-in WP ajax goodness
- // Codex: http://codex.wordpress.org/AJAX_in_Plugins
- add_action('wp_ajax_tag_slug', 'tag_slug_callback');
- function tag_slug_callback() {
- global $wpdb;
- function taglist() {
- // Retrieve tag slug from POST
- $tagslug = $_POST['slug'];
- ?>
- <ul>
- <?php
- // Query 5 posts from the tag that was selected
- $args = array( 'posts_per_page' => 5, 'tag' => $tagslug );
- $tag_query = new WP_Query( $args );
- while ( $tag_query->have_posts() ) : $tag_query->the_post();
- ?>
- <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
- <?php endwhile; wp_reset_postdata(); ?>
- </ul>
- <?php }
- echo taglist();
- die(); // this is required to return a proper result
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment