wp_create_nonce( 'asr_ajax_nonce' ), 'asr_ajax_url' => admin_url( 'admin-ajax.php' ), ) ); } add_action( 'wp_enqueue_scripts', 'asrafp_scripts' ); //shortcode function function asrafp_shortcode_mapper(){ $taxonomy = 'category'; $terms = get_terms($taxonomy); // Get all terms of a taxonomy if ( $terms && !is_wp_error( $terms ) ){ echo '
'; } $content = '
'; echo $content; } add_shortcode( 'asr_ajax', 'asrafp_shortcode_mapper' ); //ajax actions add_action('wp_ajax_asr_filter_posts', 'asrafp_ajax_functions'); add_action('wp_ajax_nopriv_asr_filter_posts', 'asrafp_ajax_functions'); //ajax main function function asrafp_ajax_functions(){ // Verify nonce if( !isset( $_POST['asr_ajax_nonce'] ) || !wp_verify_nonce( $_POST['asr_ajax_nonce'], 'asr_ajax_nonce' ) ) die('Permission denied'); $term_ID = sanitize_text_field( intval($_POST['term_ID']) ); //post query $query = new WP_Query( array( 'post_type' => 'post', 'post_per_pages' => -1, 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => $term_ID, ) ) ) ); if( $query->have_posts() ): while( $query->have_posts()): $query->the_post(); $results = '
'; $results .= '

'.get_the_title().'

'; $results .= '

'.get_the_excerpt().'

'; $results .= '
'; echo $results; endwhile; else: echo __('

No Posts Found

','asr_td'); endif; wp_reset_query(); die(); } // Register and load the widget function asrafp_load_widget() { register_widget( 'asrafp_widget' ); } add_action( 'widgets_init', 'asrafp_load_widget' ); // Creating the widget class asrafp_widget extends WP_Widget { function __construct() { parent::__construct( // Base ID of your widget 'asrafp_widget', // Widget name will appear in UI __('Ajax Filter Posts', ''), // Widget description array( 'description' => __( 'A widget for Ajax posts filter', '' ), ) ); } // Creating widget front-end public function widget( $args, $instance ) { $title = apply_filters( 'widget_title', $instance['title'] ); // before and after widget arguments are defined by themes echo $args['before_widget']; if ( ! empty( $title ) ) echo $args['before_title'] . $title . $args['after_title']; // This is where you run the code and display the output echo do_shortcode('[asr_ajax]'); echo $args['after_widget']; } // Widget Backend public function form( $instance ) { if ( isset( $instance[ 'title' ] ) ) { $title = $instance[ 'title' ]; } else { $title = __( 'Filter Posts', '' ); } // Widget admin form ?>