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

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

WordPress 后台文章列表,默认只有按日期、分类、形式筛选文章,网站开发的时候会遇到筛选某个自定义字段的问题。如何在后台文章列表中添加自定义字段筛选文章功能?可以通过在functions.php文件中加入以下,就能实现在 WordPress 后台添加按自定义字段筛选文章的功能。

// 按自定义字段筛选文章
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
}
版权声明
转载请注明本文地址:https://www.e363.com/1896.html
THE END
喜欢龙网的内容,就支持一下吧!
点赞65赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容