WordPress 后台文章列表,默认只有按日期、分类、形式筛选文章,有时想把一些添加了某个自定义字段的文章,从众多文章中找出来,还真是个难事,可以通过下面的代码,在 WordPress 后台添加按自定义字段筛选文章的功能,这样就简单了。
将下面代码添加到当前主题函数模板functions.php即可:
展开收缩
// 按自定义字段筛选文章 add_filter( 'parse_query', 'zm_posts_filter' ); add_action( 'restrict_manage_posts', 'zm_filter_field' ); function zm_posts_filter( $query ) { global $pagenow; if ( is_admin() && $pagenow=='edit.php' && isset( $_GET['ZMINGCX_FILTER_FIELD']) && $_GET['ZMINGCX_FILTER_FIELD'] != '' ) { $query->query_vars['meta_key'] = $_GET['ZMINGCX_FILTER_FIELD']; if ( isset($_GET['ZMINGCX_FIELD_VALUE'] ) && $_GET['ZMINGCX_FIELD_VALUE'] != '' ) $query->query_vars['meta_value'] = $_GET['ZMINGCX_FIELD_VALUE']; } } function zm_filter_field() { global $wpdb; $sql = 'SELECT DISTINCT meta_key FROM '.$wpdb->postmeta.' ORDER BY 1'; $fields = $wpdb->get_results( $sql, ARRAY_N ); ?> <select name="ZMINGCX_FILTER_FIELD"> <option value=""><?php _e( '自定义字段', 'zm' ); ?></option> <?php $current = isset( $_GET['ZMINGCX_FILTER_FIELD'] )? $_GET['ZMINGCX_FILTER_FIELD']:''; $current_v = isset( $_GET['ZMINGCX_FIELD_VALUE'] )? $_GET['ZMINGCX_FIELD_VALUE']:''; foreach ( $fields as $field ) { if ( substr($field[0],0,1) != "_" ){ printf ( '<option value="%s"%s>%s</option>', $field[0], $field[0] == $current? ' selected="selected"':'', $field[0] ); } } ?> </select> <?php _e( '值', 'zm' ); ?> <input type="TEXT" name="ZMINGCX_FIELD_VALUE" value="<?php echo $current_v; ?>" /> <?php }
最终效果:
本站文章大部分为原创,用于个人学习记录,可能对您有所帮助,仅供参考!
我的微信
微信号已复制
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!