简体   繁体   English

按 Wordpress 和 ajax 中的类别过滤帖子

[英]Filter posts by categories in Wordpress with ajax

so this can be duplicate but i can't find the same question.所以这可能是重复的,但我找不到相同的问题。 I have a big trouble that possibly have really small cause.我有一个很大的麻烦,可能有很小的原因。 I want to filter my custom post type posts by their category with ajax.我想使用 ajax 按类别过滤我的自定义帖子类型帖子。

What it does is that when i want to filter by my categories that are created and assigned to posts, i have a blank response with no posts.它的作用是,当我想按创建并分配给帖子的类别进行过滤时,我有一个没有帖子的空白响应。 No problems from javascript console, so i assume there is so problem with names of slugs/categories. javascript 控制台没有问题,所以我认为蛞蝓/类别的名称存在问题。

Can you please help and look at this with 'cold head'.你能不能帮忙看看这个“冷头”。

My custom post type and custom taxonomy registered:我的自定义帖子类型和自定义分类已注册:

add_action( 'init', 'blog_register' );   

function blog_register() {   

    $labels = array( 
        'name' => _x('Blog', 'post type general name'), 
        'singular_name' => _x('Blog', 'post type singular name'), 
        'add_new' => _x('Add New', 'work item'), 
        'add_new_item' => __('Add New Blog Item'), 
        'edit_item' => __('Edit Blog Item'), 
        'new_item' => __('New Blog Item'), 
        'view_item' => __('View Blog Item'), 
        'search_items' => __('Search Blog'), 
        'not_found' => __('Nothing found'), 
        'not_found_in_trash' => __('Nothing found in Trash'), 
        'parent_item_colon' => '',
        'taxonomies' => array ('categories')
    );   
    
    $args = array( 
        'labels' => $labels, 
        'public' => true, 
        'publicly_queryable' => true, 
        'show_ui' => true, 
        'query_var' => true, 
        'rewrite' => array( 'slug' => 'blog', 'with_front'=> false ), 
        'capability_type' => 'post', 
        'hierarchical' => true,
        'has_archive' => true,  
        'menu_position' => null, 
        'supports' => array('title','editor','thumbnail') 
    );   

    register_post_type( 'blog' , $args ); 

    register_taxonomy( 'categories', array('blog'), array(
        'hierarchical' => true, 
        'label' => 'Categories', 
        'singular_label' => 'Category', 
        'rewrite' => array( 'slug' => 'categories', 'with_front'=> false )
        )
    );

    register_taxonomy_for_object_type( 'categories', 'blog' ); // Better be safe than sorry
}
function filter_posts() {
    $catSlug = $_POST['categories'];
  
    $ajaxposts = new WP_Query([
      'post_type' => 'blog',
      'posts_per_page' => -1,
      'category_name' => $catSlug,
      'orderby'=> 'post_date', 
      'order' => 'desc',
    ]);
    $response = '';
  
    if($catSlug == '') {  
        $response .= get_template_part('template_parts/blog-item');
    } else {
        if($ajaxposts->have_posts()) {
          while($ajaxposts->have_posts()) : $ajaxposts->the_post();
            $response .= get_template_part('template_parts/blog-item');

          endwhile;
        } else {

            echo " ";
        }
    }
  
    echo $response;
    exit;
  
  }
  add_action('wp_ajax_filter_posts', 'filter_posts');
  add_action('wp_ajax_nopriv_filter_posts', 'filter_posts');

And here i have my js code:在这里我有我的 js 代码:

jQuery(function($){
$('.cat-item').on('click', function() {
    $('.cat-item').removeClass('active');
    $(this).addClass('active');

    $.ajax({
      type: 'POST',
      url: '/wp-admin/admin-ajax.php',
      dataType: 'html',
      data: {
        action: 'filter_posts',
        category: $(this).data('slug'),
      },
      success: function(res) {
        $('.blog-listing .row').html(res);
      }
    })
  });
});

How i display my content:我如何显示我的内容:

<div class="blog-listing">
        <div class='row'>
            <?php if (have_posts()) : while (have_posts()) : the_post();  ?>
                <?php get_template_part('template-parts/blog-item'); ?>
            <?php endwhile; endif; ?>
        </div>
      </div>

There are few logical mistakes and wrong implement in your code.您的代码中几乎没有逻辑错误和错误的实现。

  1. Since it's your custom taxonomy you can't use category_name , you'll have to work with tax_query由于这是您的自定义分类法,您不能使用category_name ,您必须使用tax_query
  2. You need to make proper validation and sanitize the input before processing with $_POST['categories']在使用$_POST['categories']进行处理之前,您需要进行适当的验证并清理输入
  3. if ( $catSlug == '' ) doesn't make sense, need to rewrite in a good way. if ( $catSlug == '' )没有意义,需要以一种好的方式重写。

Suggestion: Please add a prefix on your function and action name so that they could be unique and doesn't conflict with any other things.建议:请在您的 function 和动作名称上添加前缀,这样它们就可以是唯一的,并且不会与任何其他内容冲突。 Prefix will also remind you that you added this custom thing and it's not from theme or any other plugin, it's your code. Prefix 还会提醒你添加了这个自定义的东西,它不是来自主题或任何其他插件,它是你的代码。

Now Let's fix your code:现在让我们修复您的代码:

function filter_posts() {
    // Validate with isset and not empty then sanitize with sanitize_text_text also use wp_unslash.
    $cat_slug = isset( $_POST['categories'] ) && ! empty( $_POST['categories'] ) ? sanitize_text_field( wp_unslash( $_POST['categories'] ) ) : '';

    // Define query args in a variable, it will help us to add tax query conditionally.
    $query_args = array(
        'post_type'      => 'blog',
        'posts_per_page' => -1,
        'orderby'        => 'date',
        'order'          => 'DESC',
        'tax_query'      => array( 'AND' ),
    );

    // if category slug is not empty then add a tax query args in query.
    if ( ! empty( $cat_slug ) ) {
        $query_args['tax_query'] = array(
            'taxonomy' => 'categories',
            'field'    => 'slug',
            'operator' => '=',
            'terms'    => $cat_slug,
        );
    }

    // Run the query.
    $ajaxposts = new WP_Query( $query_args );

    // We will use ob functions to collect the buffered output.
    ob_start();

    // check if has posts.
    if ( $ajaxposts->have_posts() ) {

        // Loop through the posts.
        while ( $ajaxposts->have_posts() ) :

            $ajaxposts->the_post();

            // Get content.
            get_template_part( 'template_parts/blog-item' );

        endwhile;
    }

    wp_reset_postdata();

    $response = ob_get_clean();

    echo $response;

    exit;
}
add_action( 'wp_ajax_filter_posts', 'filter_posts' );
add_action( 'wp_ajax_nopriv_filter_posts', 'filter_posts' );

Note: When the category is empty we're fetching all the posts without a category.注意:当类别为空时,我们将获取所有没有类别的帖子。

I have not tested the code if you find any syntax or critical error after using the code, please let me know should that i could fix my answer and could fix the issue如果您在使用代码后发现任何语法或严重错误,我还没有测试过代码,如果我可以解决我的答案并可以解决问题,请告诉我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM