按类别过滤帖子AJAX正在显示所有帖子

时间:2017-03-15 作者:Julio Rodrigues

我试图通过级联下拉类别过滤帖子。但当我选择级联选项时,他显示了所有的帖子。如何通过所选选项仅筛选帖子?

这是我的结构:

Functions.php

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

// 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(
    \'exclude\' => \'1,2,4,5,7,8,9,10,11,12\',
    \'post_type\' => \'post\',
    \'nopaging\' => true, // show all posts in one go
    );
  echo $taxonomy;
  // 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(); ?>
      <div class="col-md-4">
        <div class="img-thumb">
            <a href="<?php the_field(\'link_do_case\'); ?>">
                <?php the_post_thumbnail(); ?>      
            </a>                                                                    
        </div>
        <small><?php the_title(); ?></small>
    </div>

  <?php endwhile; ?>
  <?php else: ?>
    <h2>Case não encontrado</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\');
这是我的剧本

jQuery(document).ready(function(jQuery) {
    jQuery(\'.post-tags select\').on(\'change\', function(event) {
        console.log(\'mudou\');
        // Prevent default action - opening tag page
        if (event.preventDefault) {
            event.preventDefault();
        } else {
            event.returnValue = false;
        }

        // Get tag slug from title attirbute
        var selecetd_taxonomy = jQuery(this).attr(\'title\');

        // After user click on tag, fade out list of posts
        jQuery(\'.tagged-posts\').fadeOut();

        data = {
            action: \'filter_posts\', // function to execute
            afp_nonce: afp_vars.afp_nonce, // wp_nonce
            taxonomy: selecetd_taxonomy, // selected tag
            };

        jQuery.post( afp_vars.afp_ajax_url, data, function(response) {

            if( response ) {
                // Display posts on page
                jQuery(\'.tagged-posts\').html( response );
                // Restore div visibility
                jQuery(\'.tagged-posts\').fadeIn();
            };
        });
    });
});
这是我的结构页面

<div id="ajax-cases">
<?php
    // WP Query
    $args = array(
    \'post_type\' => \'post\',
    \'exclude\' => \'1,2,4,5,7,8,9,10,11\',
    \'post_status\' => \'publish\',
    \'nopaging\' => true, // show all posts in one go
    );
   $query = new WP_Query( $args );
   $tax = \'category\';
   $terms = get_terms( $tax, $args);
   $count = count( $terms );

    if ( $count > 0 ): ?>
        <div class="post-tags">
            <h2>Busque pelo tipo de Trabalho</h2>
            <?php
            echo \'<select>\';
                foreach ( $terms as $term ) {
                    $term_link = get_term_link( $term, $tax ); 
                    echo \'<option value="\' . $term_link . \'" class="tax-filter">\' . $term->name . \'</option> \';

                }
            echo \'</select>\';
             ?>
        </div>
    <?php endif ;?>
    <div class="tagged-posts">
      // here must be show the posts selected trough the category option
    </div>              

2 个回复
SO网友:AddWeb Solution Pvt Ltd

在您的代码中,我发现了两个问题:

1) 在ajax函数ajax\\u filter\\u get\\u posts()中,您的参数中缺少了tax\\u查询。

ajax函数ajax\\u filter\\u get\\u 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(
   \'exclude\' => \'1,2,4,5,7,8,9,10,11,12\',
   \'post_type\' => \'post\',
   \'nopaging\' => true, // show all posts in one go
   );
 echo $taxonomy;
 // If taxonomy is not set, remove key from array and get all posts
 if( !$taxonomy ) {
   unset( $args[\'tag\'] );
 }else{
   // This is the code which you are missing. You need to add taxonomy query if taxonomy is set.
   $arg[\'tax_query\']= array(
     array(
       \'taxonomy\' => \'category\',
       \'field\' => \'slug\',
       \'terms\' => array( $taxonomy ),
       \'include_children\' => true, // set true if you want post of its child category also
       \'operator\' => \'IN\'
           ),
   );
 }

 $query = new WP_Query( $args );

 if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
     <div class="col-md-4">
       <div class="img-thumb">
           <a href="<?php the_field(\'link_do_case\'); ?>">
               <?php the_post_thumbnail(); ?>      
           </a>                                                                    
       </div>
       <small><?php the_title(); ?></small>
   </div>

 <?php endwhile; ?>
 <?php else: ?>
   <h2>Case não encontrado</h2>
 <?php endif;

 die();
}
2)在结构页面中,将标记行链接替换为以下行:

echo \'<option value="\' . $term_link . \'" class="tax-filter" title="\'.$term->slug.\'">\' . $term->name . \'</option> \';
3)在jQuery中,更改获取所选分类法值的方式:

var selecetd_taxonomy = jQuery(this).find(\'option:selected\').attr("title");
通过做以上3个更改,您将获得仅选定类别的帖子。

希望这对你有帮助。

SO网友:Tony Djukic

在jQuery中jQuery(\'.post-tags select\').on(\'change\', function(event) { 但是当我查看你页面的源代码时,下拉列表是<select id="dropdown_select" class="dropdown_options">, 我认为你的脚本没有看到正确的项目。试着结合其他答案纠正这个问题,看看这是否有效果。

相关推荐

WordPress AJAX错误400向远程站点发送数据的错误请求

我正在使用发件人。net获取电子邮件订阅列表。这个网站给了我一些信息,可以将用户的电子邮件添加到订阅列表中。我想使用WordPress ajax来实现这一点。但它返回错误400错误请求。我的代码是:文件ajax新闻脚本。js公司: jQuery(document).ready(function($){ // Perform AJAX send news on form submit $(\'form#fnews\').on(\'submit\', funct