[英]Filter posts by categories in Wordpress with ajax
所以這可能是重復的,但我找不到相同的問題。 我有一個很大的麻煩,可能有很小的原因。 我想使用 ajax 按類別過濾我的自定義帖子類型帖子。
它的作用是,當我想按創建並分配給帖子的類別進行過濾時,我有一個沒有帖子的空白響應。 javascript 控制台沒有問題,所以我認為蛞蝓/類別的名稱存在問題。
你能不能幫忙看看這個“冷頭”。
我的自定義帖子類型和自定義分類已注冊:
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');
在這里我有我的 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);
}
})
});
});
我如何顯示我的內容:
<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>
您的代碼中幾乎沒有邏輯錯誤和錯誤的實現。
category_name
,您必須使用tax_query
$_POST['categories']
進行處理之前,您需要進行適當的驗證並清理輸入if ( $catSlug == '' )
沒有意義,需要以一種好的方式重寫。建議:請在您的 function 和動作名稱上添加前綴,這樣它們就可以是唯一的,並且不會與任何其他內容沖突。 Prefix 還會提醒你添加了這個自定義的東西,它不是來自主題或任何其他插件,它是你的代碼。
現在讓我們修復您的代碼:
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' );
注意:當類別為空時,我們將獲取所有沒有類別的帖子。
如果您在使用代碼后發現任何語法或嚴重錯誤,我還沒有測試過代碼,如果我可以解決我的答案並可以解決問題,請告訴我
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.