Add custom field filtering article function in WordPress background

WordPress comment eight hundred and nine Reading mode

The WordPress background article list only filters articles by date, category and form by default. Sometimes it is difficult to find articles with a custom field from many articles. You can add the function of filtering articles by user-defined fields in the WordPress background through the following code, which is simple.

 Add custom field filtering article function in WordPress background - Picture 1

Add the following code to the current theme function template functions.php:

open shrink
 //Filter articles by custom fields 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 ('Custom Field ',' 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 ('value ',' zm ');?>< input type="TEXT" name="ZMINGCX_FIELD_VALUE" value="<? php echo $current_v; ?>" /> <? php }

Final effect:

 Add custom field filtering article function in WordPress background - Picture 2

 

 

Code Source

Most of the articles on this site are original and used for personal learning records, which may be helpful to you, for reference only!

 weinxin
My Wechat
WeChat copied
Copyright Notice
Please indicate the source and link of the original article reprinted on this site. Thank you for your cooperation!
five hundred and ninety-eight million eight hundred and forty-five thousand and six
 
 Robin
five hundred and ninety-eight million eight hundred and forty-five thousand and six
 anonymous

Comment

Anonymous netizens
 :?:  :razz:  :sad:  :evil:  :!:  :smile:  :oops:  :grin:  :eek:  :shock:  :???:  :cool:  :lol:  :mad:  :twisted:  :roll:  :wink:  :idea:  :arrow:  :neutral:  :cry:  :mrgreen:

Drag the slider to complete validation