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
}
最终效果:
欢迎访问秀主题博客,分享简单实用WP教程