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

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

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

相关推荐