效果:实现商店类似的分类筛选效果 如图
functions.php 中方法
引入一个.class 文件 require_once(TEMPLATEPATH . '/extend/verify.php');
主要是这个方法做一下验证 $encryption->isArticle($value->ID,$class_id);
add_action('wp_ajax_nopriv_goodsList', 'goodsList');
add_action('wp_ajax_goodsList', 'goodsList');
function goodsList(){
if(!isset($_POST['class_id'])){
echo jsonArray(400,'','缺少分类id');
exit;
}
$class_id = $_POST['class_id
$page = isset($_POST['page']) ? $_POST['page'] : 1;
$size = isset($_POST['size']) ? $_POST['size'] : 8;
$res = [];
$offset =$size*($page-1
$args1 = array(
'category' => $class_id,
'post_status'=>'publish',
'numberposts'=>-1
);
$args = array(
'category' => $class_id,
'post_status'=>'publish',
'order' => 'DESC',
'numberposts'=>$size,
'offset'=>$offset,
);
$all_count= get_posts($args1);
$posts = get_posts($args);
$encryption = new SymmetricEncryption();
if($posts){
foreach ($posts as $key => $value) {
$res_post = $encryption->isArticle($value->ID,$class_id);
if($res_post){
$images_list = get_field('product_gallery',$value->ID);
$res[$key]['image'] = $images_list ? $images_list[0]['url'] : '';
$res[$key]['id'] = $value->ID;
$res[$key]['post_date'] = $value->post_date;
$res[$key]['post_title'] = $value->post_title;
$res[$key]['post_name'] = $encryption->getClassName($value->ID);
}
}
}
$data['data'] = $res;
$data['pages'] = ceil(count($all_count) / $size);
echo jsonArray(200,$data,'Success');
exit;
}
verify.php 文件 实现逻辑:获取到当前文章的当前分类和分类的父级分类,和前端传的分类做一个差集校验。
<?php
/**
* 2023-09-01
* xitianci
* 当前为接口扩展方法文件
*/
class SymmetricEncryption {
/**
* 筛选文章是否符合分类
* post_id=文章id
*/
public function isArticle($post_id,$class_str=''){
//获取文章所有分类id
$class_array = get_the_category($post_id);
if(!$class_array){
return false;
}
$class_ids = [];
foreach($class_array as $val){
$class_ids[] = $val->term_id;
$class_ids[] = $val->parent;
}
//判断传输的分类是否全部符合当前文章。
$now_class = explode(',',$class_str);
$diff = array_diff($now_class, $class_ids);
if (empty($diff)) {
return true;
} else {
return false;
}
}
}
?>