Created
August 12, 2016 16:06
-
-
Save Bobz-zg/5f2f55983000035b5da9263cdb83d8e9 to your computer and use it in GitHub Desktop.
Filter WP posts by tag - PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Enqueue JS file | |
* Be sure to update path to js | |
* | |
* @link https://gist.github.com/Bobz-zg/16578c3c173abfe2b22daffd67f6f1e0 | |
* | |
*/ | |
function ajax_filter_posts_scripts() { | |
// Enqueue script | |
wp_register_script('afp_script', get_template_directory_uri() . '/js-folder/ajax-filter-posts.js', false, null, false); | |
wp_enqueue_script('afp_script'); | |
wp_localize_script( 'afp_script', 'afp_vars', array( | |
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request | |
'afp_ajax_url' => admin_url( 'admin-ajax.php' ), | |
) | |
); | |
} | |
add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100); | |
/** | |
* Display list fo tags | |
* | |
* Place this in a template file | |
*/ | |
function tags_filter() { | |
$tax = 'post_tag'; | |
$terms = get_terms( $tax ); | |
$count = count( $terms ); | |
if ( $count > 0 ): ?> | |
<div class="post-tags"> | |
<?php | |
foreach ( $terms as $term ) { | |
$term_link = get_term_link( $term, $tax ); | |
echo '<a href="' . $term_link . '" class="tax-filter" title="' . $term->slug . '">' . $term->name . '</a> '; | |
} ?> | |
</div> | |
<?php endif; | |
} | |
// Script for getting posts | |
function ajax_filter_get_posts( $taxonomy ) { | |
// Verify nonce | |
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) ) | |
die('Permission denied'); | |
$taxonomy = $_POST['taxonomy']; | |
// WP Query | |
$args = array( | |
'tag' => $taxonomy, | |
'post_type' => 'post', | |
'posts_per_page' => 10, | |
); | |
// If taxonomy is not set, remove key from array and get all posts | |
if( !$taxonomy ) { | |
unset( $args['tag'] ); | |
} | |
$query = new WP_Query( $args ); | |
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?> | |
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> | |
<?php the_excerpt(); ?> | |
<?php endwhile; ?> | |
<?php else: ?> | |
<h2>No posts found</h2> | |
<?php endif; | |
die(); | |
} | |
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts'); | |
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment