wordpress get_terms()使用自定义字段meta_query筛选分类法

wordpress get_terms()使用自定义字段meta_query筛选分类法

最近wordpress官方发布了wordpress 4.4版,其中新增的特性就是给分类法新增自定义字段函数:add_term_meta() , get_term_meta() , update_term_meta() , delete_term_meta() 。

正好在给客户开发一款主题,其中要用到筛选分类(不是通过分类筛选文章,而是通过分类自定义字段筛选分类),类似于将分类来归类吧~~要用到get_terms函数里的meta_query

代码:

get_terms( 'category', array('hide_empty' => true, 'parent' => '0','child_of'=> 0, 'meta_query'=>array(array('key'=>'coursecat','value'=>$courseCat->term_id)) ) );

具体怎么给分类新增自定义字段,可以看看这篇文章。

www.smashingmagazine.com/2015/12/how-to-use-term-meta-data-in-wordpress/

if (!function_exists('get_article_for_category')) { function get_article_for_category( $category, $posts_per_page = 5, $tag = '' ,// 新增参数:标签(tag) $include_meta = true, $include_acf = true, $orderby = 'menu_order', $order = 'DESC' ) { // 限制只允许的排序字段 $allowed_orderby = array('date', 'menu_order'); if (!in_array($orderby, $allowed_orderby)) { $orderby = 'date'; // 默认回退到按时间排序 } // 设置基础查询参数 $args = array( 'posts_per_page' => $posts_per_page, 'orderby' => $orderby, 'order' => $order, ); // 添加分类查询条件 if (is_numeric($category)) { $args['tax_query'][] = array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => $category, ); } else { $args['tax_query'][] = array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => $category, ); } if (!empty($tag)) { $args['tax_query']['relation'] = 'AND'; if (is_numeric($tag)) { $args['tax_query'][] = array( 'taxonomy' => 'post_tag', 'field' => 'term_id', 'terms' => $tag, ); } else { $args['tax_query'][] = array( 'taxonomy' => 'post_tag', 'field' => 'slug', 'terms' => $tag, ); } } if ($orderby === 'menu_order') { $args['orderby'] = 'menu_order'; } $query = new WP_Query($args); if ($query->have_posts()) { $posts = array(); while ($query->have_posts()) { $query->the_post(); $post_id = get_the_ID(); $post_data = array( 'id' => $post_id, 'title' => get_the_title(), 'permalink' => get_the_permalink(), 'excerpt' => get_the_excerpt(), 'content' => get_the_content(), 'thumbnail' => has_post_thumbnail() ? get_the_post_thumbnail_url() : '', 'date' => get_the_date(), 'author' => get_the_author(), 'modified_date' => get_the_modified_date(), 'type' => get_post_type(), 'status' => get_post_status(), 'comment_count' => get_comments_number(), ); // 获取所有自定义字段(post meta) if ($include_meta) { $meta = get_post_meta($post_id); $post_data['meta'] = $meta; } // 如果使用了 ACF,获取 ACF 字段 if ($include_acf && function_exists('get_fields')) { $acf_fields = get_fields(); if ($acf_fields) { $post_data['acf'] = $acf_fields; } } $posts[] = $post_data; } wp_reset_postdata(); return $posts; } return false; } }
07-22
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值