在WordPress 后台添加自定义字段筛选文章功能


WordPress 后台文章列表,默认只有按日期、分类、形式筛选文章,有时想把一些添加了某个自定义字段的文章,从众多文章中找出来,还真是个难事,可以通过下面的代码,在 WordPress 后台添加按自定义字段筛选文章的功能,这样就简单了。

 

将下面代码添加到当前主题函数模板functions.php即可:

 

 

 
  1. // 按自定义字段筛选文章
  2. add_filter( 'parse_query', 'zm_posts_filter' );
  3. add_action( 'restrict_manage_posts', 'zm_filter_field' );
  4.  
  5. function zm_posts_filter( $query ) {
  6. global $pagenow;
  7. if ( is_admin() && $pagenow=='edit.php' && isset( $_GET['ZMINGCX_FILTER_FIELD']) && $_GET['ZMINGCX_FILTER_FIELD'] != '' ) {
  8. $query->query_vars['meta_key'] = $_GET['ZMINGCX_FILTER_FIELD'];
  9. if ( isset($_GET['ZMINGCX_FIELD_VALUE'] ) && $_GET['ZMINGCX_FIELD_VALUE'] != '' )
  10. $query->query_vars['meta_value'] = $_GET['ZMINGCX_FIELD_VALUE'];
  11. }
  12. }
  13.  
  14. function zm_filter_field() {
  15. global $wpdb;
  16. $sql = 'SELECT DISTINCT meta_key FROM '.$wpdb->postmeta.' ORDER BY 1';
  17. $fields = $wpdb->get_results( $sql, ARRAY_N );
  18. ?>
  19. <select name="ZMINGCX_FILTER_FIELD">
  20. <option value=""><?php _e( '自定义字段', 'zm' ); ?></option>
  21. <?php
  22. $current = isset( $_GET['ZMINGCX_FILTER_FIELD'] )? $_GET['ZMINGCX_FILTER_FIELD']:'';
  23. $current_v = isset( $_GET['ZMINGCX_FIELD_VALUE'] )? $_GET['ZMINGCX_FIELD_VALUE']:'';
  24. foreach ( $fields as $field ) {
  25. if ( substr($field[0],0,1) != "_" ){
  26. printf
  27. (
  28. '<option value="%s"%s>%s</option>',
  29. $field[0],
  30. $field[0] == $current? ' selected="selected"':'',
  31. $field[0]
  32. );
  33. }
  34. }
  35. ?>
  36. </select> <?php _e( '值', 'zm' ); ?> <input type="TEXT" name="ZMINGCX_FIELD_VALUE" value="<?php echo $current_v; ?>" />
  37. <?php
  38. }

 

 

 

打赏