Advertisement
Guest User

add-ajax-text-search-for-custom-post-type.php

a guest
Jul 16th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.93 KB | None | 0 0
  1. function video_filter_function() {
  2.     check_ajax_referer( 'my_nonce' );
  3.  
  4.     $date = sanitize_text_field( $_POST['date'] );
  5.     $date = ( $date === 'ASC' ) ? 'ASC' : 'DESC'; // Make sure it's a valida date
  6.  
  7.     $args = array(
  8.         'post_type' => 'videos',
  9.         'orderby'   => 'date',
  10.         'order'     => $date,
  11.     );
  12.  
  13.     // Add to query only if it's not empty
  14.     if ( ! empty( $_POST['categoryfilter'] ) ) {
  15.         $categoryfilter = sanitize_text_field( $_POST['categoryfilter'] );
  16.  
  17.         $args['tax_query'] = array(
  18.             array(
  19.                 'taxonomy'  => 'category',
  20.                 'field'     => 'id',
  21.                 'terms'     => $categoryfilter,
  22.             ),
  23.         );
  24.     }
  25.  
  26.     // Add to query only if it's not empty
  27.     if ( ! empty( $_POST['description'] ) ) {
  28.         $description = sanitize_text_field( $_POST['description'] );
  29.  
  30.         $args['meta_query'] = array(
  31.             array(
  32.                 'key'       => 'video_description',
  33.                 'value'     => $description,
  34.                 'compare'   => 'LIKE',
  35.             ),
  36.         );
  37.     }
  38.  
  39.     $query = new WP_Query( $args );
  40.  
  41.     if ( $query->have_posts() ) :
  42.         while( $query->have_posts() ) : $query->the_post();
  43.     ?>
  44.  
  45.         <div class="video-grid-item">
  46.             <h2> <?php the_field('video_title'); ?></h2>
  47.             <p> <?php the_field('video_description'); ?></p>
  48.             <iframe src="https://player.vimeo.com/video/<?php the_field( 'vimeo' ); ?>" width="640" height="640" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
  49.         </div>
  50.  
  51. <?php
  52.         endwhile;
  53.         wp_reset_postdata();
  54.     else :
  55.         echo 'No posts found';
  56.     endif;
  57.  
  58.     die; // Search for wp_send_json() to check how to use the JSON away
  59. }
  60.  
  61.  
  62. add_action( 'wp_ajax_myfilter', 'video_filter_function' );
  63. add_action( 'wp_ajax_nopriv_myfilter', 'video_filter_function' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement