WordPress Dashboard后台 非插件 纯代码 实现自定义字段过滤

前面我们介绍了 WordPress 主题/插件开发 自定义文章分类 筛选功能 图文教程

下面我们记录一下如何在后台实现过滤自定义字段,将以下代码放入 functions.php 文件中代码段如下:

add_filter( 'parse_query', 'jadmin_posts_filter' );
add_action( 'restrict_manage_posts', 'jadmin_posts_filter_restrict_manage_posts' );
 
function jadmin_posts_filter( $query )
{
    global $pagenow;
    if ( is_admin() && $pagenow=='edit.php' && isset($_GET['ADMIN_FILTER_FIELD_NAME']) && '' != $_GET['ADMIN_FILTER_FIELD_NAME']) {
        $query->query_vars['meta_key'] = sanitize_text_field($_GET['ADMIN_FILTER_FIELD_NAME']);
    if (isset($_GET['ADMIN_FILTER_FIELD_VALUE']) && '' != $_GET['ADMIN_FILTER_FIELD_VALUE'])
        $query->query_vars['meta_value'] = sanitize_text_field($_GET['ADMIN_FILTER_FIELD_VALUE']);
    }
}
 
function jadmin_posts_filter_restrict_manage_posts()
{
    global $wpdb;
    $sql = 'SELECT DISTINCT meta_key FROM '.$wpdb->postmeta.' ORDER BY 1';
    $fields = $wpdb->get_results($sql, ARRAY_N);
?>
<select name="ADMIN_FILTER_FIELD_NAME">
<option value=""><?php _e('Filter By Custom Fields', 'jiloc'); ?></option>
<?php
    $current = isset($_GET['ADMIN_FILTER_FIELD_NAME'])? $_GET['ADMIN_FILTER_FIELD_NAME']:'';
    $current_v = isset($_GET['ADMIN_FILTER_FIELD_VALUE'])? $_GET['ADMIN_FILTER_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:', 'jiloc'); ?><input type="TEXT" name="ADMIN_FILTER_FIELD_VALUE" value="<?php echo $current_v; ?>" />
<?php
}

腾讯云限时秒杀【点击购买】

搬瓦工,CN2高速线路,1GB带宽,电信联通优化KVM,延迟低,速度快,建站稳定,搬瓦工BandwagonHost VPS优惠码BWH26FXH3HIQ,支持<支付宝> 【点击购买】!

Vultr$3.5日本节点,512M内存/500G流量/1G带宽,电信联通优化,延迟低,速度快【点击购买】!

阿里云香港、新加坡VPS/1核/1G/25G SSD/1T流量/30M带宽/年付¥288【点击购买】


`微信`扫码 加好友

发表评论

您的电子邮箱地址不会被公开。