使用 AJAX 使用自定义分类法过滤自定义帖子

问题描述

几个小时以来,我一直在寻找问题的解决方案,我创建了一个带有“专业”分类法的自定义帖子“工作”,我想显示我的帖子并按分类添加过滤器。下面的代码运行良好,但不是在同一页面中加载过滤器的结果,而是每次打开新页面时都会打开我。 我已经尝试了几种方法来达到这个结果,但我仍然有这个问题,所以我想知道问题是否不在其他地方,我的文件可能显示我的自定义帖子?

archive-work.PHP

<?PHP
/**
 * Template Name: Work List
 *
 */
get_header();

the_post();
?>


<section class="headerpage">
    <div class="head" >
        <div class="container">
            <div class="col-md-7">
                <h1><?PHP echo get_the_title( 14 ); ?></h1>

                <?PHP echo '<p class="subtitle">'. get_secondary_title( 14 ) .'</p>';?>
            </div>
        </div>

    </div>
</section>
<div class="container filters-projects-wrap">
    <div>
        <span class="small-text">FILTER BY</span>
    </div>
    <div>
        <ul class="filters-projects-ul">
            <li><a href="<?PHP echo esc_url( home_url( '/projects/' ) ); ?>">ALL</a></li>
        <?PHP $categories = get_categories('taxonomy=expertises&post_type=work'); ?>
                <?PHP foreach ($categories as $category) : ?>
                        <li><a class="projects-filter" href="<?PHP echo get_term_link($category->cat_ID); ?>"><?PHP echo $category->name; ?></a></li>
        <?PHP endforeach; ?>
        </ul>
    </div>
</div>



<div class="projects-results">
        <?PHP $res = my_get_posts();
                echo $res['response'];
        ?>
</div>

<?PHP get_footer(); ?>

functions.PHP

function ajax_filter_posts_scripts() {
  // Enqueue script
  wp_register_script('afp_script',get_template_directory_uri() . '/assets/js/work.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);


function ajax_filter_get_posts( $taxonomyproject ) {

  // Verify nonce
  if( !isset( $_POST['afp_nonce'] ) ||
      !wp_verify_nonce( $_POST['afp_nonce'],'afp_nonce' ))
    die('Permission denied');

     $taxonomyproject = $_POST['expertises'];
     $result = json_encode(my_get_posts($taxonomyproject,true));
     echo $result;

     die();

}

function my_get_posts($taxonomyproject = '',$ajax = false){

// WP Query
$args = array(
    'post_type' => 'work','posts_per_page' => -1,'tax_query' => array(
        array(
            'taxonomy' => 'expertises',)
    )
);

  // If taxonomy is not set,remove key from array and get all posts
  if( !$taxonomyproject ) {
    unset( $args['tax_query'] );
  }

  $query = new WP_Query( $args );
  $html = '';
  $items = array();

  if ( $query->have_posts() ) :
       while ( $query->have_posts() ) :
       $query->the_post();

       $res = '<div class="col-lg-4">'.
                  '<a href="'.get_permalink().'">'.
                      '<article class="panel panel-default" id="post-'.get_the_id().'">'.
                          '<div class="panel-body">'.
                              get_the_post_thumbnail().
                              '<div class="panel-cover">'.
                                  '<h3>'.get_the_title().'</h3>'.
                                      get_the_content().
                              '</div>'.
                          '</div>'.
                      '</article>'.
                  '</a>' .
              '</div>';


       $ajax ? $items[] = $res : $html .= $res;


   endwhile;

   $result['response'] = $ajax ? $items : $html;
   $result['status'] = 'success';

   else:
       $result['response'] = '<h2>No posts found</h2>';
       $result['status']   = '404';
   endif;
wp_reset_postdata();
return $result;
}

work.js

data = {
            action: 'filter_posts',// function to execute
            afp_nonce: afp_vars.afp_nonce,// wp_nonce
            post_type: "work",// selected tag
            };

        $.ajax({
            type: "post",dataType: "json",url: afp_vars.afp_ajax_url,data: data,success: function(data,textStatus,XMLHttpRequest) {
                console.log(data);
                // Restore div visibility
                $('.projects-results').fadeOut()
                    .queue(function(n) {
                            $(this).html(data.response);
                            n();
                }).fadeIn();
            },error: function( XMLHttpRequest,errorThrown ) {
                /*console.log( MLHttpRequest );
                console.log( textStatus );
                console.log( errorThrown );*/
                $('.projects-results').fadeOut()
                    .queue(function(n) {
                            $(this).html("No items found. ");
                            n();
                }).fadeIn();
            }
        });
    });

});

解决方法

当我过滤时,我终于设法将帖子加载到同一页面中。这是 ca 可以帮助其他人的代码。但是我还有一个小问题,我想添加一个“全部”按钮来加载所有帖子,有人可以帮助我吗?

work.js

$(document).ready(function(){

// work filters

$('.work-filter').click( function(event) {

    // Prevent default action - opening tag page
    if (event.preventDefault) {
        event.preventDefault();
    } else {
        event.returnValue = false;
    }

    // Get tag slug from title attirbute
    var expertises = $(this).attr('title');        

    data = {
        action: 'filter_posts',// function to execute
        afp_nonce: afp_vars.afp_nonce,// wp_nonce
        post_type: "work",// selected tag
        expertises: expertises,};

    $.ajax({ 
        type: "post",dataType: "json",url: afp_vars.afp_ajax_url,data: data,success: function(data,textStatus,XMLHttpRequest) {
            console.log(data);
            // Restore div visibility
            $('.work-results').fadeOut()
                .queue(function(n) {
                        $(this).html(data.response);
                        n();
            }).fadeIn();
        },error: function( XMLHttpRequest,errorThrown ) {
            /*console.log( MLHttpRequest );
            console.log( textStatus );
            console.log( errorThrown );*/
            $('.work-results').fadeOut()
                .queue(function(n) {
                        $(this).html("No items found. ");
                        n();
            }).fadeIn();
        }
    });
});

functions.php

function ajax_filter_posts_scripts() {

wp_register_script('afp_script',get_template_directory_uri() . '/assets/js/work.js',false,null,false);
wp_enqueue_script('afp_script');

wp_localize_script( 'afp_script','afp_vars',array(
     'afp_nonce' => wp_create_nonce( 'afp_nonce' ),'afp_ajax_url' => admin_url( 'admin-ajax.php' ),)
);
}
add_action('wp_enqueue_scripts','ajax_filter_posts_scripts',100);

$result = array();

function ajax_filter_get_posts( $work_item ) {

   if( !isset( $_POST['afp_nonce'] ) || 
       !wp_verify_nonce( $_POST['afp_nonce'],'afp_nonce' ))
     die('Permission denied');

      $work_item = $_POST['expertises'];
      $result = json_encode(my_get_posts($work_item,true));
      echo $result;

      die();

 }

function my_get_posts($work_item = '',$ajax = false){

   $args = array(
     'expertises' => $work_item,'post_type' => 'work','posts_per_page' => -1,);

   if( !$work_item ) {
     unset( $args['expertises'] );
   }

   $query = new WP_Query( $args );
   $html = '';
   $items = array();

   if ( $query->have_posts() ) : 
        while ( $query->have_posts() ) : 
        $query->the_post(); 

        $res = '<div class="col-lg-4">'.
                   '<a href="'.get_permalink().'">'.
                       '<article class="panel panel-default" id="post-'.get_the_id().'">'.
                           '<div class="panel-body">'.
                               get_the_post_thumbnail().
                               '<div class="panel-cover">'.
                                   '<h3>'.get_the_title().'</h3>'.
                                       get_the_content().
                               '</div>'.
                           '</div>'.      
                       '</article>'.
                   '</a>' .     
               '</div>';


        $ajax ? $items[] = $res : $html .= $res;


    endwhile;

    $result['response'] = $ajax ? $items : $html;
    $result['status'] = 'success';

    else:
        $result['response'] = '<h2>No posts found</h2>';
        $result['status']   = '404';
    endif;
wp_reset_postdata();
return $result;
}

add_action('wp_ajax_filter_posts','ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts','ajax_filter_get_posts');

function get_work_filters()
{
 $work_items = get_terms('expertises');
 $filters_html = false;
 $count = count( $work_items );

 if( $count > 0 ):
     foreach( $work_items as $work_item )
     {
         $work_item_id = $work_item->term_id;
         $work_item_name = $work_item->name;

         $filters_html .= '<a href="' . 
             get_term_link( $work_item ) . 
             '" class="btn work-filter" title="' . 
             $work_item->slug . '">' . $work_item->name . '</a> ';
     }
     echo $filters_html;
 endif;
}

archive-work.php

<div class="container">

           <div id="work-filter" class="text-center">
               <?php get_work_filters(); ?>
           </div>
           <br />

           <div class="work-results">
               <?php $res = my_get_posts();
               echo $res['response'];
       ?>
           </div>

       </div>